diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index b3f8b276f..e2a4be2ee 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -23,7 +23,7 @@ jobs: # https://github.com/marketplace/actions/flutter-action - uses: subosito/flutter-action@v2 with: - flutter-version: "3.13.1" + flutter-version: "3.13.9" channel: "stable" - run: flutter pub get #- run: flutter analyze diff --git a/lib/get_animations/animations.dart b/lib/get_animations/animations.dart index e996bddff..a263e7a9e 100644 --- a/lib/get_animations/animations.dart +++ b/lib/get_animations/animations.dart @@ -9,10 +9,7 @@ typedef OffsetBuilder = Offset Function(BuildContext, double); class FadeInAnimation extends OpacityAnimation { FadeInAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, super.key, super.onComplete, super.begin = 0, super.end = 1, @@ -22,10 +19,7 @@ class FadeInAnimation extends OpacityAnimation { class FadeOutAnimation extends OpacityAnimation { FadeOutAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, super.key, super.onComplete, super.begin = 1, super.end = 0, @@ -35,20 +29,13 @@ class FadeOutAnimation extends OpacityAnimation { class OpacityAnimation extends GetAnimatedBuilder { OpacityAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, - required super.onComplete, - required double begin, - required double end, - required super.idleValue, + required super.duration, required super.delay, required super.child, required super.onComplete, required final double begin, required final double end, required super.idleValue, super.key, }) : super( tween: Tween(begin: begin, end: end), - builder: (context, value, child) { + builder: (final context, final value, final child) { return Opacity( opacity: value, - child: child!, + child: child, ); }, ); @@ -56,16 +43,11 @@ class OpacityAnimation extends GetAnimatedBuilder { class RotateAnimation extends GetAnimatedBuilder { RotateAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, super.key, super.onComplete, - required double begin, - required double end, super.idleValue = 0, }) : super( - builder: (context, value, child) => Transform.rotate( + builder: (final context, final value, final child) => Transform.rotate( angle: value, child: child, ), @@ -75,16 +57,11 @@ class RotateAnimation extends GetAnimatedBuilder { class ScaleAnimation extends GetAnimatedBuilder { ScaleAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, super.key, super.onComplete, - required double begin, - required double end, super.idleValue = 0, }) : super( - builder: (context, value, child) => Transform.scale( + builder: (final context, final value, final child) => Transform.scale( scale: value, child: child, ), @@ -113,17 +90,12 @@ class ScaleAnimation extends GetAnimatedBuilder { class BounceAnimation extends GetAnimatedBuilder { BounceAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, super.key, super.onComplete, super.curve = Curves.bounceOut, - required double begin, - required double end, super.idleValue = 0, }) : super( - builder: (context, value, child) => Transform.scale( + builder: (final context, final value, final child) => Transform.scale( scale: 1 + value.abs(), child: child, ), @@ -133,14 +105,11 @@ class BounceAnimation extends GetAnimatedBuilder { class SpinAnimation extends GetAnimatedBuilder { SpinAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, super.key, super.onComplete, super.idleValue = 0, }) : super( - builder: (context, value, child) => Transform.rotate( + builder: (final context, final value, final child) => Transform.rotate( angle: value * pi / 180.0, child: child, ), @@ -150,16 +119,11 @@ class SpinAnimation extends GetAnimatedBuilder { class SizeAnimation extends GetAnimatedBuilder { SizeAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, super.key, super.onComplete, super.idleValue = 0, - required double begin, - required double end, }) : super( - builder: (context, value, child) => Transform.scale( + builder: (final context, final value, final child) => Transform.scale( scale: value, child: child, ), @@ -169,16 +133,11 @@ class SizeAnimation extends GetAnimatedBuilder { class BlurAnimation extends GetAnimatedBuilder { BlurAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, super.key, super.onComplete, - required double begin, - required double end, super.idleValue = 0, }) : super( - builder: (context, value, child) => BackdropFilter( + builder: (final context, final value, final child) => BackdropFilter( filter: ImageFilter.blur( sigmaX: value, sigmaY: value, @@ -191,16 +150,11 @@ class BlurAnimation extends GetAnimatedBuilder { class FlipAnimation extends GetAnimatedBuilder { FlipAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, super.key, super.onComplete, - required double begin, - required double end, super.idleValue = 0, }) : super( - builder: (context, value, child) { + builder: (final context, final value, final child) { final radians = value * pi; return Transform( transform: Matrix4.rotationY(radians), @@ -214,16 +168,11 @@ class FlipAnimation extends GetAnimatedBuilder { class WaveAnimation extends GetAnimatedBuilder { WaveAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, super.key, super.onComplete, - required double begin, - required double end, super.idleValue = 0, }) : super( - builder: (context, value, child) => Transform( + builder: (final context, final value, final child) => Transform( transform: Matrix4.translationValues( 0.0, 20.0 * sin(value * pi * 2), @@ -237,16 +186,11 @@ class WaveAnimation extends GetAnimatedBuilder { class WobbleAnimation extends GetAnimatedBuilder { WobbleAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, super.key, super.onComplete, - required double begin, - required double end, super.idleValue = 0, }) : super( - builder: (context, value, child) => Transform( + builder: (final context, final value, final child) => Transform( transform: Matrix4.identity() ..setEntry(3, 2, 0.001) ..rotateZ(sin(value * pi * 2) * 0.1), @@ -259,81 +203,55 @@ class WobbleAnimation extends GetAnimatedBuilder { class SlideInLeftAnimation extends SlideAnimation { SlideInLeftAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required super.begin, required super.end, super.key, super.onComplete, - required super.begin, - required super.end, super.idleValue = 0, }) : super( - offsetBuild: (context, value) => + offsetBuild: (final context, final value) => Offset(value * MediaQuery.of(context).size.width, 0), ); } class SlideInRightAnimation extends SlideAnimation { SlideInRightAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required super.begin, required super.end, super.key, super.onComplete, - required super.begin, - required super.end, super.idleValue = 0, }) : super( - offsetBuild: (context, value) => + offsetBuild: (final context, final value) => Offset((1 - value) * MediaQuery.of(context).size.width, 0), ); } class SlideInUpAnimation extends SlideAnimation { SlideInUpAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required super.begin, required super.end, super.key, super.onComplete, - required super.begin, - required super.end, super.idleValue = 0, }) : super( - offsetBuild: (context, value) => + offsetBuild: (final context, final value) => Offset(0, value * MediaQuery.of(context).size.height), ); } class SlideInDownAnimation extends SlideAnimation { SlideInDownAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required super.begin, required super.end, super.key, super.onComplete, - required super.begin, - required super.end, super.idleValue = 0, }) : super( - offsetBuild: (context, value) => + offsetBuild: (final context, final value) => Offset(0, (1 - value) * MediaQuery.of(context).size.height), ); } class SlideAnimation extends GetAnimatedBuilder { SlideAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, - required double begin, - required double end, - required OffsetBuilder offsetBuild, + required super.duration, required super.delay, required super.child, required final double begin, required final double end, required final OffsetBuilder offsetBuild, super.key, super.onComplete, super.idleValue = 0, }) : super( - builder: (context, value, child) => Transform.translate( + builder: (final context, final value, final child) => Transform.translate( offset: offsetBuild(context, value), child: child, ), @@ -362,16 +280,11 @@ class SlideAnimation extends GetAnimatedBuilder { class ColorAnimation extends GetAnimatedBuilder { ColorAnimation({ - super.key, - required super.duration, - required super.delay, - required super.child, + required super.duration, required super.delay, required super.child, required final Color begin, required final Color end, super.key, super.onComplete, - required Color begin, - required Color end, - Color? idleColor, + final Color? idleColor, }) : super( - builder: (context, value, child) => ColorFiltered( + builder: (final context, final value, final child) => ColorFiltered( colorFilter: ColorFilter.mode( Color.lerp(begin, end, value!.value.toDouble())!, BlendMode.srcIn, diff --git a/lib/get_animations/extensions.dart b/lib/get_animations/extensions.dart index 3206c0d73..d2301b3b2 100644 --- a/lib/get_animations/extensions.dart +++ b/lib/get_animations/extensions.dart @@ -3,18 +3,18 @@ import 'package:flutter/material.dart'; import 'animations.dart'; import 'get_animated_builder.dart'; -const _defaultDuration = Duration(seconds: 2); -const _defaultDelay = Duration.zero; +const Duration _defaultDuration = Duration(seconds: 2); +const Duration _defaultDelay = Duration.zero; extension AnimationExtension on Widget { GetAnimatedBuilder? get _currentAnimation => (this is GetAnimatedBuilder) ? this as GetAnimatedBuilder : null; GetAnimatedBuilder fadeIn({ - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { assert(isSequential || this is! FadeOutAnimation, 'Can not use fadeOut + fadeIn when isSequential is false'); @@ -28,10 +28,10 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder fadeOut({ - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { assert(isSequential || this is! FadeInAnimation, 'Can not use fadeOut() + fadeIn when isSequential is false'); @@ -45,12 +45,12 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder rotate({ - required double begin, - required double end, - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + required final double begin, + required final double end, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return RotateAnimation( duration: duration, @@ -63,12 +63,12 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder scale({ - required double begin, - required double end, - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + required final double begin, + required final double end, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return ScaleAnimation( duration: duration, @@ -81,13 +81,13 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder slide({ - required OffsetBuilder offset, - double begin = 0, - double end = 1, - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + required final OffsetBuilder offset, + final double begin = 0, + final double end = 1, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return SlideAnimation( duration: duration, @@ -101,12 +101,12 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder bounce({ - required double begin, - required double end, - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + required final double begin, + required final double end, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return BounceAnimation( duration: duration, @@ -119,10 +119,10 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder spin({ - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return SpinAnimation( duration: duration, @@ -133,12 +133,12 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder size({ - required double begin, - required double end, - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + required final double begin, + required final double end, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return SizeAnimation( duration: duration, @@ -151,12 +151,12 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder blur({ - double begin = 0, - double end = 15, - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + final double begin = 0, + final double end = 15, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return BlurAnimation( duration: duration, @@ -169,12 +169,12 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder flip({ - double begin = 0, - double end = 1, - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + final double begin = 0, + final double end = 1, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return FlipAnimation( duration: duration, @@ -187,12 +187,12 @@ extension AnimationExtension on Widget { } GetAnimatedBuilder wave({ - double begin = 0, - double end = 1, - Duration duration = _defaultDuration, - Duration delay = _defaultDelay, - ValueSetter? onComplete, - bool isSequential = false, + final double begin = 0, + final double end = 1, + final Duration duration = _defaultDuration, + final Duration delay = _defaultDelay, + final ValueSetter? onComplete, + final bool isSequential = false, }) { return WaveAnimation( duration: duration, @@ -204,9 +204,9 @@ extension AnimationExtension on Widget { ); } - Duration _getDelay(bool isSequential, Duration delay) { + Duration _getDelay(final bool isSequential, final Duration delay) { assert(!(isSequential && delay != Duration.zero), - "Error: When isSequential is true, delay must be non-zero. Context: isSequential: $isSequential delay: $delay"); + 'Error: When isSequential is true, delay must be non-zero. Context: isSequential: $isSequential delay: $delay'); return isSequential ? (_currentAnimation?.totalDuration ?? Duration.zero) diff --git a/lib/get_animations/get_animated_builder.dart b/lib/get_animations/get_animated_builder.dart index 0fd233434..252ca96fe 100644 --- a/lib/get_animations/get_animated_builder.dart +++ b/lib/get_animations/get_animated_builder.dart @@ -3,6 +3,18 @@ import 'package:flutter/material.dart'; import 'animations.dart'; class GetAnimatedBuilder extends StatefulWidget { + const GetAnimatedBuilder({ + required this.duration, + required this.tween, + required this.idleValue, + required this.builder, + required this.child, + required this.delay, + super.key, + this.curve = Curves.linear, + this.onComplete, + this.onStart, + }); final Duration duration; final Duration delay; final Widget child; @@ -14,19 +26,6 @@ class GetAnimatedBuilder extends StatefulWidget { final Curve curve; Duration get totalDuration => duration + delay; - - const GetAnimatedBuilder({ - super.key, - this.curve = Curves.linear, - this.onComplete, - this.onStart, - required this.duration, - required this.tween, - required this.idleValue, - required this.builder, - required this.child, - required this.delay, - }); @override GetAnimatedBuilderState createState() => GetAnimatedBuilderState(); } @@ -48,7 +47,7 @@ class GetAnimatedBuilderState extends State> bool get willResetOnDispose => _willResetOnDispose; - void _listener(AnimationStatus status) { + void _listener(final AnimationStatus status) { switch (status) { case AnimationStatus.completed: widget.onComplete?.call(_controller); @@ -71,12 +70,12 @@ class GetAnimatedBuilderState extends State> super.initState(); if (widget is OpacityAnimation) { - final current = + final GetAnimatedBuilderState? current = context.findRootAncestorStateOfType(); - final isLast = current == null; + final bool isLast = current == null; if (widget is FadeInAnimation) { - _idleValue = 1.0 as dynamic; + _idleValue = 1.0 as T; } else { if (isLast) { _willResetOnDispose = false; @@ -121,10 +120,10 @@ class GetAnimatedBuilderState extends State> } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return AnimatedBuilder( animation: _animation, - builder: (context, child) { + builder: (final BuildContext context, final Widget? child) { final value = _wasStarted ? _animation.value : _idleValue; return widget.builder(context, value, child); }, diff --git a/lib/get_common/get_reset.dart b/lib/get_common/get_reset.dart index 7c0b9fdc9..a35ff03bd 100644 --- a/lib/get_common/get_reset.dart +++ b/lib/get_common/get_reset.dart @@ -1,7 +1,7 @@ import '../get.dart'; extension GetResetExt on GetInterface { - void reset({bool clearRouteBindings = true}) { + void reset({final bool clearRouteBindings = true}) { Get.resetInstance(clearRouteBindings: clearRouteBindings); // Get.clearRouteTree(); Get.clearTranslations(); diff --git a/lib/get_connect/connect.dart b/lib/get_connect/connect.dart index a952bc166..0a936d0a3 100644 --- a/lib/get_connect/connect.dart +++ b/lib/get_connect/connect.dart @@ -17,76 +17,76 @@ abstract class GetConnectInterface with GetLifeCycleMixin { GetHttpClient get httpClient; Future> get( - String url, { - Map? headers, - String? contentType, - Map? query, - Decoder? decoder, + final String url, { + final Map? headers, + final String? contentType, + final Map? query, + final Decoder? decoder, }); Future> request( - String url, - String method, { - dynamic body, - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, + final String url, + final String method, { + final dynamic body, + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, }); Future> post( - String url, - dynamic body, { - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, + final String url, + final dynamic body, { + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, }); Future> put( - String url, - dynamic body, { - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, + final String url, + final dynamic body, { + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, }); Future> delete( - String url, { - Map? headers, - String? contentType, - Map? query, - Decoder? decoder, + final String url, { + final Map? headers, + final String? contentType, + final Map? query, + final Decoder? decoder, }); Future> patch( - String url, - dynamic body, { - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - Progress? uploadProgress, + final String url, + final dynamic body, { + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final Progress? uploadProgress, }); Future> query( - String query, { - String? url, - Map? variables, - Map? headers, + final String query, { + final String? url, + final Map? variables, + final Map? headers, }); Future> mutation( - String mutation, { - String? url, - Map? variables, - Map? headers, + final String mutation, { + final String? url, + final Map? variables, + final Map? headers, }); GetSocket socket( - String url, { - Duration ping = const Duration(seconds: 5), + final String url, { + final Duration ping = const Duration(seconds: 5), }); } @@ -137,11 +137,11 @@ class GetConnect extends GetConnectInterface { @override Future> get( - String url, { - Map? headers, - String? contentType, - Map? query, - Decoder? decoder, + final String url, { + final Map? headers, + final String? contentType, + final Map? query, + final Decoder? decoder, }) { _checkIfDisposed(); return httpClient.get( @@ -155,13 +155,13 @@ class GetConnect extends GetConnectInterface { @override Future> post( - String? url, - dynamic body, { - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - Progress? uploadProgress, + final String? url, + final dynamic body, { + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final Progress? uploadProgress, }) { _checkIfDisposed(); return httpClient.post( @@ -177,13 +177,13 @@ class GetConnect extends GetConnectInterface { @override Future> put( - String url, - dynamic body, { - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - Progress? uploadProgress, + final String url, + final dynamic body, { + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final Progress? uploadProgress, }) { _checkIfDisposed(); return httpClient.put( @@ -199,13 +199,13 @@ class GetConnect extends GetConnectInterface { @override Future> patch( - String url, - dynamic body, { - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - Progress? uploadProgress, + final String url, + final dynamic body, { + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final Progress? uploadProgress, }) { _checkIfDisposed(); return httpClient.patch( @@ -221,14 +221,14 @@ class GetConnect extends GetConnectInterface { @override Future> request( - String url, - String method, { - dynamic body, - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - Progress? uploadProgress, + final String url, + final String method, { + final dynamic body, + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final Progress? uploadProgress, }) { _checkIfDisposed(); return httpClient.request( @@ -245,11 +245,11 @@ class GetConnect extends GetConnectInterface { @override Future> delete( - String url, { - Map? headers, - String? contentType, - Map? query, - Decoder? decoder, + final String url, { + final Map? headers, + final String? contentType, + final Map? query, + final Decoder? decoder, }) { _checkIfDisposed(); return httpClient.delete( @@ -263,17 +263,17 @@ class GetConnect extends GetConnectInterface { @override GetSocket socket( - String url, { - Duration ping = const Duration(seconds: 5), + final String url, { + final Duration ping = const Duration(seconds: 5), }) { _checkIfDisposed(isHttp: false); - final newSocket = GetSocket(_concatUrl(url)!, ping: ping); + final GetSocket newSocket = GetSocket(_concatUrl(url)!, ping: ping); sockets.add(newSocket); return newSocket; } - String? _concatUrl(String? url) { + String? _concatUrl(final String? url) { if (url == null) return baseUrl; return baseUrl == null ? url : baseUrl! + url; } @@ -299,15 +299,15 @@ class GetConnect extends GetConnectInterface { ///print(response.body); @override Future> query( - String query, { - String? url, - Map? variables, - Map? headers, + final String query, { + final String? url, + final Map? variables, + final Map? headers, }) async { try { - final res = await post( + final Response res = await post( url, - {'query': query, 'variables': variables}, + {'query': query, 'variables': variables}, headers: headers, ); @@ -315,17 +315,19 @@ class GetConnect extends GetConnectInterface { if ((listError is List) && listError.isNotEmpty) { return GraphQLResponse( graphQLErrors: listError - .map((e) => GraphQLError( - code: (e['extensions'] != null ? e['extensions']['code'] ?? '' : '').toString(), + .map((final e) => GraphQLError( + code: (e['extensions'] != null + ? e['extensions']['code'] ?? '' + : '') + .toString(), message: (e['message'] ?? '').toString(), )) .toList()); } return GraphQLResponse.fromResponse(res); } on Exception catch (_) { - return GraphQLResponse(graphQLErrors: [ + return GraphQLResponse(graphQLErrors: [ GraphQLError( - code: null, message: _.toString(), ) ]); @@ -334,15 +336,15 @@ class GetConnect extends GetConnectInterface { @override Future> mutation( - String mutation, { - String? url, - Map? variables, - Map? headers, + final String mutation, { + final String? url, + final Map? variables, + final Map? headers, }) async { try { - final res = await post( + final Response res = await post( url, - {'query': mutation, 'variables': variables}, + {'query': mutation, 'variables': variables}, headers: headers, ); @@ -350,7 +352,7 @@ class GetConnect extends GetConnectInterface { if ((listError is List) && listError.isNotEmpty) { return GraphQLResponse( graphQLErrors: listError - .map((e) => GraphQLError( + .map((final e) => GraphQLError( code: e['extensions']['code']?.toString(), message: e['message']?.toString(), )) @@ -358,9 +360,8 @@ class GetConnect extends GetConnectInterface { } return GraphQLResponse.fromResponse(res); } on Exception catch (_) { - return GraphQLResponse(graphQLErrors: [ + return GraphQLResponse(graphQLErrors: [ GraphQLError( - code: null, message: _.toString(), ) ]); @@ -371,7 +372,7 @@ class GetConnect extends GetConnectInterface { bool get isDisposed => _isDisposed; - void _checkIfDisposed({bool isHttp = true}) { + void _checkIfDisposed({final bool isHttp = true}) { if (_isDisposed) { throw 'Can not emit events to disposed clients'; } @@ -379,7 +380,7 @@ class GetConnect extends GetConnectInterface { void dispose() { if (_sockets != null) { - for (var socket in sockets) { + for (final GetSocket socket in sockets) { socket.close(); } _sockets?.clear(); diff --git a/lib/get_connect/http/src/certificates/certificates.dart b/lib/get_connect/http/src/certificates/certificates.dart index a1869d828..0da430acf 100644 --- a/lib/get_connect/http/src/certificates/certificates.dart +++ b/lib/get_connect/http/src/certificates/certificates.dart @@ -1,5 +1,5 @@ class TrustedCertificate { - final List bytes; const TrustedCertificate(this.bytes); + final List bytes; } diff --git a/lib/get_connect/http/src/exceptions/exceptions.dart b/lib/get_connect/http/src/exceptions/exceptions.dart index a64ea1f61..518790dea 100644 --- a/lib/get_connect/http/src/exceptions/exceptions.dart +++ b/lib/get_connect/http/src/exceptions/exceptions.dart @@ -1,10 +1,10 @@ class GetHttpException implements Exception { + + GetHttpException(this.message, [this.uri]); final String message; final Uri? uri; - GetHttpException(this.message, [this.uri]); - @override String toString() => message; } @@ -26,8 +26,8 @@ class UnauthorizedException implements Exception { } class UnexpectedFormat implements Exception { - final String message; UnexpectedFormat(this.message); + final String message; @override String toString() { return 'Unexpected format: $message'; diff --git a/lib/get_connect/http/src/http.dart b/lib/get_connect/http/src/http.dart index c1d927346..43a01ed5b 100644 --- a/lib/get_connect/http/src/http.dart +++ b/lib/get_connect/http/src/http.dart @@ -20,6 +20,28 @@ typedef ResponseInterceptor = Future?> Function( Request request, Type targetType, HttpClientResponse response); class GetHttpClient { + GetHttpClient({ + this.userAgent = 'getx-client', + this.timeout = const Duration(seconds: 8), + this.followRedirects = true, + this.maxRedirects = 5, + this.sendUserAgent = false, + this.sendContentLength = true, + this.maxAuthRetries = 1, + final bool allowAutoSignedCert = false, + this.baseUrl, + final List? trustedCertificates, + final bool withCredentials = false, + final String Function(Uri url)? findProxy, + final IClient? customClient, + }) : _httpClient = customClient ?? + createHttp( + allowAutoSignedCert: allowAutoSignedCert, + trustedCertificates: trustedCertificates, + withCredentials: withCredentials, + findProxy: findProxy, + ), + _modifier = GetModifier(); String userAgent; String? baseUrl; @@ -45,54 +67,31 @@ class GetHttpClient { String Function(Uri url)? findProxy; - GetHttpClient({ - this.userAgent = 'getx-client', - this.timeout = const Duration(seconds: 8), - this.followRedirects = true, - this.maxRedirects = 5, - this.sendUserAgent = false, - this.sendContentLength = true, - this.maxAuthRetries = 1, - bool allowAutoSignedCert = false, - this.baseUrl, - List? trustedCertificates, - bool withCredentials = false, - String Function(Uri url)? findProxy, - IClient? customClient, - }) : _httpClient = customClient ?? - createHttp( - allowAutoSignedCert: allowAutoSignedCert, - trustedCertificates: trustedCertificates, - withCredentials: withCredentials, - findProxy: findProxy, - ), - _modifier = GetModifier(); - - void addAuthenticator(RequestModifier auth) { + void addAuthenticator(final RequestModifier auth) { _modifier.authenticator = auth as RequestModifier; } - void addRequestModifier(RequestModifier interceptor) { + void addRequestModifier(final RequestModifier interceptor) { _modifier.addRequestModifier(interceptor); } - void removeRequestModifier(RequestModifier interceptor) { + void removeRequestModifier(final RequestModifier interceptor) { _modifier.removeRequestModifier(interceptor); } - void addResponseModifier(ResponseModifier interceptor) { + void addResponseModifier(final ResponseModifier interceptor) { _modifier.addResponseModifier(interceptor); } - void removeResponseModifier(ResponseModifier interceptor) { + void removeResponseModifier(final ResponseModifier interceptor) { _modifier.removeResponseModifier(interceptor); } - Uri createUri(String? url, Map? query) { + Uri createUri(String? url, final Map? query) { if (baseUrl != null) { url = baseUrl! + url!; } - final uri = Uri.parse(url!); + final Uri uri = Uri.parse(url!); if (query != null) { return uri.replace(queryParameters: query); } @@ -100,18 +99,18 @@ class GetHttpClient { } Future> _requestWithBody( - String? url, - String? contentType, - dynamic body, - String method, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, - Progress? uploadProgress, + final String? url, + final String? contentType, + final dynamic body, + final String method, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, + final Progress? uploadProgress, ) async { List? bodyBytes; Stream>? bodyStream; - final headers = {}; + final Map headers = {}; if (sendUserAgent) { headers['user-agent'] = userAgent; @@ -125,17 +124,18 @@ class GetHttpClient { } else if (contentType != null && contentType.toLowerCase() == 'application/x-www-form-urlencoded' && body is Map) { - var parts = []; - (body as Map).forEach((key, value) { + final List parts = []; + (body as Map) + .forEach((final String key, final dynamic value) { parts.add('${Uri.encodeQueryComponent(key)}=' '${Uri.encodeQueryComponent(value.toString())}'); }); - var formData = parts.join('&'); + final String formData = parts.join('&'); bodyBytes = utf8.encode(formData); _setContentLength(headers, bodyBytes.length); headers['content-type'] = contentType; } else if (body is Map || body is List) { - var jsonString = json.encode(body); + final String jsonString = json.encode(body); bodyBytes = utf8.encode(jsonString); _setContentLength(headers, bodyBytes.length); headers['content-type'] = contentType ?? defaultContentType; @@ -157,7 +157,7 @@ class GetHttpClient { bodyStream = _trackProgress(bodyBytes, uploadProgress); } - final uri = createUri(url, query); + final Uri uri = createUri(url, query); return Request( method: method, url: uri, @@ -170,25 +170,28 @@ class GetHttpClient { responseInterceptor: responseInterceptor); } - void _setContentLength(Map headers, int contentLength) { + void _setContentLength( + final Map headers, final int contentLength) { if (sendContentLength) { headers['content-length'] = '$contentLength'; } } Stream> _trackProgress( - List bodyBytes, - Progress? uploadProgress, + final List bodyBytes, + final Progress? uploadProgress, ) { - var total = 0; - var length = bodyBytes.length; - - var byteStream = - Stream.fromIterable(bodyBytes.map((i) => [i])).transform>( - StreamTransformer.fromHandlers(handleData: (data, sink) { + int total = 0; + final int length = bodyBytes.length; + + final Stream> byteStream = + Stream>.fromIterable(bodyBytes.map((final int i) => [i])) + .transform>( + StreamTransformer, List>.fromHandlers( + handleData: (final List data, final EventSink> sink) { total += data.length; if (uploadProgress != null) { - var percent = total / length * 100; + final double percent = total / length * 100; uploadProgress(percent); } sink.add(data); @@ -198,8 +201,8 @@ class GetHttpClient { } void _setSimpleHeaders( - Map headers, - String? contentType, + final Map headers, + final String? contentType, ) { headers['content-type'] = contentType ?? defaultContentType; if (sendUserAgent) { @@ -208,25 +211,27 @@ class GetHttpClient { } Future> _performRequest( - HandlerExecute handler, { - bool authenticate = false, - int requestNumber = 1, - Map? headers, + final HandlerExecute handler, { + final bool authenticate = false, + final int requestNumber = 1, + final Map? headers, }) async { - var request = await handler(); + final Request request = await handler(); - headers?.forEach((key, value) { + headers?.forEach((final String key, final String value) { request.headers[key] = value; }); - if (authenticate) await _modifier.authenticator!(request); - final newRequest = await _modifier.modifyRequest(request); + if (authenticate) { + await _modifier.authenticator!(request); + } + final Request newRequest = await _modifier.modifyRequest(request); _httpClient.timeout = timeout; try { - var response = await _httpClient.send(newRequest); + final Response response = await _httpClient.send(newRequest); - final newResponse = + final Response newResponse = await _modifier.modifyResponse(newRequest, response); if (HttpStatus.unauthorized == newResponse.statusCode && @@ -262,26 +267,24 @@ class GetHttpClient { return Response( request: newRequest, headers: null, - statusCode: null, - body: null, - statusText: "$err", + statusText: '$err', ); } } } Future> _get( - String url, - String? contentType, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, + final String url, + final String? contentType, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, ) { - final headers = {}; + final Map headers = {}; _setSimpleHeaders(headers, contentType); - final uri = createUri(url, query); + final Uri uri = createUri(url, query); - return Future.value(Request( + return Future>.value(Request( method: 'get', url: uri, headers: headers, @@ -294,25 +297,28 @@ class GetHttpClient { } ResponseInterceptor? _responseInterceptor( - ResponseInterceptor? actual) { - if (actual != null) return actual; - final defaultInterceptor = defaultResponseInterceptor; + final ResponseInterceptor? actual) { + if (actual != null) { + return actual; + } + final ResponseInterceptor? defaultInterceptor = defaultResponseInterceptor; return defaultInterceptor != null - ? (request, targetType, response) async => + ? (final Request request, final Type targetType, + final HttpClientResponse response) async => await defaultInterceptor(request, targetType, response) as Response? : null; } Future> _request( - String? url, - String method, { - String? contentType, - required dynamic body, - required Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, - required Progress? uploadProgress, + final String? url, + final String method, { + required final dynamic body, + required final Map? query, + required final Progress? uploadProgress, + final String? contentType, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, }) { return _requestWithBody( url, @@ -327,15 +333,15 @@ class GetHttpClient { } Request _delete( - String url, - String? contentType, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, + final String url, + final String? contentType, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, ) { - final headers = {}; + final Map headers = {}; _setSimpleHeaders(headers, contentType); - final uri = createUri(url, query); + final Uri uri = createUri(url, query); return Request( method: 'delete', @@ -346,33 +352,34 @@ class GetHttpClient { ); } - Future> send(Request request) async { + Future> send(final Request request) async { try { - var response = await _performRequest(() => Future.value(request)); + final Response response = + await _performRequest(() => Future>.value(request)); return response; } on Exception catch (e) { if (!errorSafety) { throw GetHttpException(e.toString()); } - return Future.value(Response( + return Future>.value(Response( statusText: 'Can not connect to server. Reason: $e', )); } } Future> patch( - String url, { - dynamic body, - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, - Progress? uploadProgress, + final String url, { + final dynamic body, + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, + final Progress? uploadProgress, // List files, }) async { try { - var response = await _performRequest( + final Response response = await _performRequest( () => _request( url, 'patch', @@ -390,25 +397,25 @@ class GetHttpClient { if (!errorSafety) { throw GetHttpException(e.toString()); } - return Future.value(Response( + return Future>.value(Response( statusText: 'Can not connect to server. Reason: $e', )); } } Future> post( - String? url, { - dynamic body, - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, - Progress? uploadProgress, + final String? url, { + final dynamic body, + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, + final Progress? uploadProgress, // List files, }) async { try { - var response = await _performRequest( + final Response response = await _performRequest( () => _request( url, 'post', @@ -426,25 +433,25 @@ class GetHttpClient { if (!errorSafety) { throw GetHttpException(e.toString()); } - return Future.value(Response( + return Future>.value(Response( statusText: 'Can not connect to server. Reason: $e', )); } } Future> request( - String url, - String method, { - dynamic body, - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, - Progress? uploadProgress, + final String url, + final String method, { + final dynamic body, + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, + final Progress? uploadProgress, }) async { try { - var response = await _performRequest( + final Response response = await _performRequest( () => _request( url, method, @@ -462,24 +469,24 @@ class GetHttpClient { if (!errorSafety) { throw GetHttpException(e.toString()); } - return Future.value(Response( + return Future>.value(Response( statusText: 'Can not connect to server. Reason: $e', )); } } Future> put( - String url, { - dynamic body, - String? contentType, - Map? headers, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, - Progress? uploadProgress, + final String url, { + final dynamic body, + final String? contentType, + final Map? headers, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, + final Progress? uploadProgress, }) async { try { - var response = await _performRequest( + final Response response = await _performRequest( () => _request( url, 'put', @@ -497,22 +504,22 @@ class GetHttpClient { if (!errorSafety) { throw GetHttpException(e.toString()); } - return Future.value(Response( + return Future>.value(Response( statusText: 'Can not connect to server. Reason: $e', )); } } Future> get( - String url, { - Map? headers, - String? contentType, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, + final String url, { + final Map? headers, + final String? contentType, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, }) async { try { - var response = await _performRequest( + final Response response = await _performRequest( () => _get(url, contentType, query, decoder, responseInterceptor), headers: headers, ); @@ -521,20 +528,20 @@ class GetHttpClient { if (!errorSafety) { throw GetHttpException(e.toString()); } - return Future.value(Response( + return Future>.value(Response( statusText: 'Can not connect to server. Reason: $e', )); } } - Future> delete(String url, - {Map? headers, - String? contentType, - Map? query, - Decoder? decoder, - ResponseInterceptor? responseInterceptor}) async { + Future> delete(final String url, + {final Map? headers, + final String? contentType, + final Map? query, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor}) async { try { - var response = await _performRequest( + final Response response = await _performRequest( () async => _delete(url, contentType, query, decoder, responseInterceptor), headers: headers, @@ -544,7 +551,7 @@ class GetHttpClient { if (!errorSafety) { throw GetHttpException(e.toString()); } - return Future.value(Response( + return Future>.value(Response( statusText: 'Can not connect to server. Reason: $e', )); } diff --git a/lib/get_connect/http/src/http/html/file_decoder_html.dart b/lib/get_connect/http/src/http/html/file_decoder_html.dart index 73a83a532..687b6d34b 100644 --- a/lib/get_connect/http/src/http/html/file_decoder_html.dart +++ b/lib/get_connect/http/src/http/html/file_decoder_html.dart @@ -1,6 +1,6 @@ // import 'dart:html' as html; -List fileToBytes(dynamic data) { +List fileToBytes(final dynamic data) { if (data is List) { return data; } else { diff --git a/lib/get_connect/http/src/http/html/http_request_html.dart b/lib/get_connect/http/src/http/html/http_request_html.dart index 6fbfb8669..732f9f139 100644 --- a/lib/get_connect/http/src/http/html/http_request_html.dart +++ b/lib/get_connect/http/src/http/html/http_request_html.dart @@ -12,10 +12,10 @@ import '../utils/body_decoder.dart'; /// A `dart:html` implementation of `IClient`. class HttpRequestImpl implements IClient { HttpRequestImpl({ - bool allowAutoSignedCert = true, - List? trustedCertificates, + final bool allowAutoSignedCert = true, + final List? trustedCertificates, this.withCredentials = false, - String Function(Uri url)? findProxy, + final String Function(Uri url)? findProxy, }); /// The currently active XHRs. @@ -30,8 +30,8 @@ class HttpRequestImpl implements IClient { /// Sends an HTTP request and asynchronously returns the response. @override - Future> send(Request request) async { - var bytes = await request.bodyBytes.toBytes(); + Future> send(final Request request) async { + final bytes = await request.bodyBytes.toBytes(); HttpRequest xhr; xhr = HttpRequest() @@ -45,13 +45,13 @@ class HttpRequestImpl implements IClient { ..withCredentials = withCredentials; request.headers.forEach(xhr.setRequestHeader); - var completer = Completer>(); - xhr.onLoad.first.then((_) { - var blob = xhr.response as Blob? ?? Blob([]); - var reader = FileReader(); + final completer = Completer>(); + xhr.onLoad.first.then((final _) { + final blob = xhr.response as Blob? ?? Blob([]); + final reader = FileReader(); - reader.onLoad.first.then((_) async { - var bodyBytes = (reader.result as List).toStream(); + reader.onLoad.first.then((final _) async { + final bodyBytes = (reader.result as List).toStream(); if(request.responseInterceptor != null) throw 'response interception not implemented for web yet!'; @@ -95,7 +95,7 @@ class HttpRequestImpl implements IClient { completer.complete(response); }); - reader.onError.first.then((error) { + reader.onError.first.then((final error) { completer.completeError( GetHttpException(error.toString(), request.url), StackTrace.current, @@ -105,7 +105,7 @@ class HttpRequestImpl implements IClient { reader.readAsArrayBuffer(blob); }); - xhr.onError.first.then((_) { + xhr.onError.first.then((final _) { completer.completeError( GetHttpException('XMLHttpRequest error.', request.url), StackTrace.current); @@ -123,7 +123,7 @@ class HttpRequestImpl implements IClient { /// Closes the client and abort all active requests. @override void close() { - for (var xhr in _xhrs) { + for (final xhr in _xhrs) { xhr.abort(); } } diff --git a/lib/get_connect/http/src/http/interface/request_base.dart b/lib/get_connect/http/src/http/interface/request_base.dart index 92af97110..5bb29eec8 100644 --- a/lib/get_connect/http/src/http/interface/request_base.dart +++ b/lib/get_connect/http/src/http/interface/request_base.dart @@ -4,7 +4,7 @@ import '../../response/response.dart'; /// Abstract interface of [HttpRequestImpl]. abstract class IClient { /// Sends an HTTP [Request]. - Future> send(Request request); + Future> send(final Request request); /// Closes the [Request] and cleans up any resources associated with it. void close(); diff --git a/lib/get_connect/http/src/http/io/file_decoder_io.dart b/lib/get_connect/http/src/http/io/file_decoder_io.dart index f3fe013f7..3e56a0006 100644 --- a/lib/get_connect/http/src/http/io/file_decoder_io.dart +++ b/lib/get_connect/http/src/http/io/file_decoder_io.dart @@ -1,6 +1,6 @@ import 'dart:io'; -List fileToBytes(dynamic data) { +List fileToBytes(final dynamic data) { if (data is File) { return data.readAsBytesSync(); } else if (data is String) { @@ -17,4 +17,4 @@ List fileToBytes(dynamic data) { } } -void writeOnFile(List bytes) {} +void writeOnFile(final List bytes) {} diff --git a/lib/get_connect/http/src/http/io/http_request_io.dart b/lib/get_connect/http/src/http/io/http_request_io.dart index bc54a0ec0..efd215bbe 100644 --- a/lib/get_connect/http/src/http/io/http_request_io.dart +++ b/lib/get_connect/http/src/http/io/http_request_io.dart @@ -10,14 +10,12 @@ import '../utils/body_decoder.dart'; /// A `dart:io` implementation of `IClient`. class HttpRequestImpl extends IClient { - io.HttpClient? _httpClient; - io.SecurityContext? _securityContext; HttpRequestImpl({ - bool allowAutoSignedCert = true, - List? trustedCertificates, - bool withCredentials = false, - String Function(Uri url)? findProxy, + final bool allowAutoSignedCert = true, + final List? trustedCertificates, + final bool withCredentials = false, + final String Function(Uri url)? findProxy, }) { _httpClient = io.HttpClient(); if (trustedCertificates != null) { @@ -29,13 +27,15 @@ class HttpRequestImpl extends IClient { } _httpClient = io.HttpClient(context: _securityContext); - _httpClient!.badCertificateCallback = (_, __, ___) => allowAutoSignedCert; + _httpClient!.badCertificateCallback = (final _, final __, final ___) => allowAutoSignedCert; _httpClient!.findProxy = findProxy; } + io.HttpClient? _httpClient; + io.SecurityContext? _securityContext; @override - Future> send(Request request) async { - var stream = request.bodyBytes.asBroadcastStream(); + Future> send(final Request request) async { + final stream = request.bodyBytes.asBroadcastStream(); io.HttpClientRequest? ioRequest; try { _httpClient!.connectionTimeout = timeout; @@ -46,17 +46,17 @@ class HttpRequestImpl extends IClient { ..contentLength = request.contentLength ?? -1; request.headers.forEach(ioRequest.headers.set); - var response = timeout == null + final response = timeout == null ? await stream.pipe(ioRequest) as io.HttpClientResponse : await stream.pipe(ioRequest).timeout(timeout!) as io.HttpClientResponse; - var headers = {}; - response.headers.forEach((key, values) { + final headers = {}; + response.headers.forEach((final key, final values) { headers[key] = values.join(','); }); - final bodyBytes = (response); + final bodyBytes = response; final interceptionResponse = await request.responseInterceptor?.call(request, T, response); diff --git a/lib/get_connect/http/src/http/mock/http_request_mock.dart b/lib/get_connect/http/src/http/mock/http_request_mock.dart index 2010b4d09..5860f7f8a 100644 --- a/lib/get_connect/http/src/http/mock/http_request_mock.dart +++ b/lib/get_connect/http/src/http/mock/http_request_mock.dart @@ -6,23 +6,23 @@ import '../utils/body_decoder.dart'; typedef MockClientHandler = Future Function(Request request); class MockClient extends IClient { - /// The handler for than transforms request on response - final MockClientHandler _handler; /// Creates a [MockClient] with a handler that receives [Request]s and sends /// [Response]s. MockClient(this._handler); + /// The handler for than transforms request on response + final MockClientHandler _handler; @override - Future> send(Request request) async { - var requestBody = await request.bodyBytes.toBytes(); - var bodyBytes = requestBody.toStream(); + Future> send(final Request request) async { + final requestBody = await request.bodyBytes.toBytes(); + final bodyBytes = requestBody.toStream(); - var response = await _handler(request); + final response = await _handler(request); final stringBody = await bodyBytesToString(bodyBytes, response.headers!); - var mimeType = response.headers!.containsKey('content-type') + final mimeType = response.headers!.containsKey('content-type') ? response.headers!['content-type'] : ''; diff --git a/lib/get_connect/http/src/http/request/http_request.dart b/lib/get_connect/http/src/http/request/http_request.dart index 76ee90ace..39b21c84d 100644 --- a/lib/get_connect/http/src/http/request/http_request.dart +++ b/lib/get_connect/http/src/http/request/http_request.dart @@ -4,10 +4,10 @@ import '../stub/http_request_stub.dart' if (dart.library.io) '../io/http_request_io.dart'; HttpRequestImpl createHttp({ - bool allowAutoSignedCert = true, - List? trustedCertificates, - bool withCredentials = false, - String Function(Uri url)? findProxy, + final bool allowAutoSignedCert = true, + final List? trustedCertificates, + final bool withCredentials = false, + final String Function(Uri url)? findProxy, }) { return HttpRequestImpl( allowAutoSignedCert: allowAutoSignedCert, diff --git a/lib/get_connect/http/src/http/stub/file_decoder_stub.dart b/lib/get_connect/http/src/http/stub/file_decoder_stub.dart index 0a9ae9f9c..9de6bba15 100644 --- a/lib/get_connect/http/src/http/stub/file_decoder_stub.dart +++ b/lib/get_connect/http/src/http/stub/file_decoder_stub.dart @@ -1,5 +1,5 @@ -void writeOnFile(List bytes) {} +void writeOnFile(final List bytes) {} -List fileToBytes(dynamic data) { +List fileToBytes(final dynamic data) { throw UnimplementedError(); } diff --git a/lib/get_connect/http/src/http/stub/http_request_stub.dart b/lib/get_connect/http/src/http/stub/http_request_stub.dart index c121ce21b..9876aeeab 100644 --- a/lib/get_connect/http/src/http/stub/http_request_stub.dart +++ b/lib/get_connect/http/src/http/stub/http_request_stub.dart @@ -5,16 +5,16 @@ import '../interface/request_base.dart'; class HttpRequestImpl extends IClient { HttpRequestImpl({ - bool allowAutoSignedCert = true, - List? trustedCertificates, - bool withCredentials = false, - String Function(Uri url)? findProxy, + final bool allowAutoSignedCert = true, + final List? trustedCertificates, + final bool withCredentials = false, + final String Function(Uri url)? findProxy, }); @override void close() {} @override - Future> send(Request request) { + Future> send(final Request request) { throw UnimplementedError(); } } diff --git a/lib/get_connect/http/src/http/utils/body_decoder.dart b/lib/get_connect/http/src/http/utils/body_decoder.dart index 99a6942cd..928f4cf9d 100644 --- a/lib/get_connect/http/src/http/utils/body_decoder.dart +++ b/lib/get_connect/http/src/http/utils/body_decoder.dart @@ -3,7 +3,7 @@ import 'dart:convert'; import '../../../../../get_core/get_core.dart'; import '../../request/request.dart'; -T? bodyDecoded(Request request, String stringBody, String? mimeType) { +T? bodyDecoded(final Request request, final String stringBody, final String? mimeType) { T? body; dynamic bodyToDecode; diff --git a/lib/get_connect/http/src/interceptors/get_modifiers.dart b/lib/get_connect/http/src/interceptors/get_modifiers.dart index 4ddc3f81e..1baebe5a2 100644 --- a/lib/get_connect/http/src/interceptors/get_modifiers.dart +++ b/lib/get_connect/http/src/interceptors/get_modifiers.dart @@ -5,36 +5,36 @@ import '../response/response.dart'; typedef RequestModifier = FutureOr> Function(Request request); -typedef ResponseModifier = FutureOr Function( +typedef ResponseModifier = FutureOr Function( Request request, Response response); typedef HandlerExecute = Future> Function(); class GetModifier { - final _requestModifiers = []; - final _responseModifiers = []; + final List _requestModifiers = []; + final List _responseModifiers = []; RequestModifier? authenticator; - void addRequestModifier(RequestModifier interceptor) { + void addRequestModifier(final RequestModifier interceptor) { _requestModifiers.add(interceptor as RequestModifier); } - void removeRequestModifier(RequestModifier interceptor) { + void removeRequestModifier(final RequestModifier interceptor) { _requestModifiers.remove(interceptor); } - void addResponseModifier(ResponseModifier interceptor) { + void addResponseModifier(final ResponseModifier interceptor) { _responseModifiers.add(interceptor as ResponseModifier); } - void removeResponseModifier(ResponseModifier interceptor) { + void removeResponseModifier(final ResponseModifier interceptor) { _requestModifiers.remove(interceptor); } - Future> modifyRequest(Request request) async { - var newRequest = request; + Future> modifyRequest(final Request request) async { + Request newRequest = request; if (_requestModifiers.isNotEmpty) { - for (var interceptor in _requestModifiers) { + for (final RequestModifier interceptor in _requestModifiers) { newRequest = await interceptor(newRequest) as Request; } } @@ -43,10 +43,10 @@ class GetModifier { } Future> modifyResponse( - Request request, Response response) async { - var newResponse = response; + final Request request, final Response response) async { + Response newResponse = response; if (_responseModifiers.isNotEmpty) { - for (var interceptor in _responseModifiers) { + for (final ResponseModifier interceptor in _responseModifiers) { newResponse = await interceptor(request, response) as Response; } } diff --git a/lib/get_connect/http/src/multipart/form_data.dart b/lib/get_connect/http/src/multipart/form_data.dart index 352098645..f264211fc 100644 --- a/lib/get_connect/http/src/multipart/form_data.dart +++ b/lib/get_connect/http/src/multipart/form_data.dart @@ -7,15 +7,15 @@ import '../utils/utils.dart'; import 'multipart_file.dart'; class FormData { - FormData(Map map) : boundary = _getBoundary() { - map.forEach((key, value) { + FormData(final Map map) : boundary = _getBoundary() { + map.forEach((final key, final value) { if (value == null) return; if (value is MultipartFile) { files.add(MapEntry(key, value)); } else if (value is List) { - files.addAll(value.map((e) => MapEntry(key, e))); + files.addAll(value.map((final e) => MapEntry(key, e))); } else if (value is List) { - fields.addAll(value.map((e) => MapEntry(key, e.toString()))); + fields.addAll(value.map((final e) => MapEntry(key, e.toString()))); } else { fields.add(MapEntry(key, value.toString())); } @@ -26,8 +26,8 @@ class FormData { static String _getBoundary() { final newRandom = Random(); - var list = List.generate(_maxBoundaryLength - GET_BOUNDARY.length, - (_) => boundaryCharacters[newRandom.nextInt(boundaryCharacters.length)], + final list = List.generate(_maxBoundaryLength - GET_BOUNDARY.length, + (final _) => boundaryCharacters[newRandom.nextInt(boundaryCharacters.length)], growable: false); return '$GET_BOUNDARY${String.fromCharCodes(list)}'; } @@ -42,7 +42,7 @@ class FormData { /// Returns the header string for a field. The return value is guaranteed to /// contain only ASCII characters. - String _fieldHeader(String name, String value) { + String _fieldHeader(final String name, final String value) { var header = 'content-disposition: form-data; name="${browserEncode(name)}"'; if (!isPlainAscii(value)) { @@ -55,7 +55,7 @@ class FormData { /// Returns the header string for a file. The return value is guaranteed to /// contain only ASCII characters. - String _fileHeader(MapEntry file) { + String _fileHeader(final MapEntry file) { var header = 'content-disposition: form-data; name="${browserEncode(file.key)}"'; header = '$header; filename="${browserEncode(file.value.filename)}"'; @@ -77,7 +77,7 @@ class FormData { '\r\n'.length; } - for (var file in files) { + for (final file in files) { length += '--'.length + _maxBoundaryLength + '\r\n'.length + @@ -98,7 +98,7 @@ class FormData { final separator = utf8.encode('--$boundary\r\n'); final close = utf8.encode('--$boundary--\r\n'); - for (var field in fields) { + for (final field in fields) { yield separator; yield utf8.encode(_fieldHeader(field.key, field.value)); yield utf8.encode(field.value); diff --git a/lib/get_connect/http/src/multipart/multipart_file.dart b/lib/get_connect/http/src/multipart/multipart_file.dart index 3e0704b35..93c6bd040 100644 --- a/lib/get_connect/http/src/multipart/multipart_file.dart +++ b/lib/get_connect/http/src/multipart/multipart_file.dart @@ -5,7 +5,7 @@ import '../request/request.dart'; class MultipartFile { MultipartFile( - dynamic data, { + final dynamic data, { required this.filename, this.contentType = 'application/octet-stream', }) : _bytes = fileToBytes(data) { diff --git a/lib/get_connect/http/src/request/request.dart b/lib/get_connect/http/src/request/request.dart index f7d34af21..f3d42170b 100644 --- a/lib/get_connect/http/src/request/request.dart +++ b/lib/get_connect/http/src/request/request.dart @@ -6,6 +6,50 @@ import '../http.dart'; import '../multipart/form_data.dart'; class Request { + + factory Request({ + required final Uri url, + required final String method, + required final Map headers, + Stream>? bodyBytes, + final bool followRedirects = true, + final int maxRedirects = 4, + final int? contentLength, + final FormData? files, + final bool persistentConnection = true, + final Decoder? decoder, + final ResponseInterceptor? responseInterceptor, + }) { + if (followRedirects) { + assert(maxRedirects > 0); + } + return Request._( + url: url, + method: method, + bodyBytes: bodyBytes ??= [].toStream(), + headers: Map.from(headers), + followRedirects: followRedirects, + maxRedirects: maxRedirects, + contentLength: contentLength, + files: files, + persistentConnection: persistentConnection, + decoder: decoder, + responseInterceptor: responseInterceptor); + } + + const Request._({ + required this.method, + required this.bodyBytes, + required this.url, + required this.headers, + required this.contentLength, + required this.followRedirects, + required this.maxRedirects, + required this.files, + required this.persistentConnection, + required this.decoder, + this.responseInterceptor, + }); /// Headers attach to this [Request] final Map headers; @@ -35,63 +79,19 @@ class Request { final FormData? files; - const Request._({ - required this.method, - required this.bodyBytes, - required this.url, - required this.headers, - required this.contentLength, - required this.followRedirects, - required this.maxRedirects, - required this.files, - required this.persistentConnection, - required this.decoder, - this.responseInterceptor, - }); - - factory Request({ - required Uri url, - required String method, - required Map headers, - Stream>? bodyBytes, - bool followRedirects = true, - int maxRedirects = 4, - int? contentLength, - FormData? files, - bool persistentConnection = true, - Decoder? decoder, - ResponseInterceptor? responseInterceptor, - }) { - if (followRedirects) { - assert(maxRedirects > 0); - } - return Request._( - url: url, - method: method, - bodyBytes: bodyBytes ??= [].toStream(), - headers: Map.from(headers), - followRedirects: followRedirects, - maxRedirects: maxRedirects, - contentLength: contentLength, - files: files, - persistentConnection: persistentConnection, - decoder: decoder, - responseInterceptor: responseInterceptor); - } - Request copyWith({ - Uri? url, - String? method, - Map? headers, - Stream>? bodyBytes, - bool? followRedirects, - int? maxRedirects, - int? contentLength, - FormData? files, - bool? persistentConnection, - Decoder? decoder, - bool appendHeader = true, - ResponseInterceptor? responseInterceptor, + final Uri? url, + final String? method, + final Map? headers, + final Stream>? bodyBytes, + final bool? followRedirects, + final int? maxRedirects, + final int? contentLength, + final FormData? files, + final bool? persistentConnection, + final Decoder? decoder, + final bool appendHeader = true, + final ResponseInterceptor? responseInterceptor, }) { // If appendHeader is set to true, we will merge origin headers with that if (appendHeader && headers != null) { @@ -119,19 +119,19 @@ extension StreamExt on List { extension BodyBytesStream on Stream> { Future toBytes() { - var completer = Completer(); - var sink = ByteConversionSink.withCallback( - (bytes) => completer.complete( + final completer = Completer(); + final sink = ByteConversionSink.withCallback( + (final bytes) => completer.complete( Uint8List.fromList(bytes), ), ); - listen((val) => sink.add(val), + listen((final val) => sink.add(val), onError: completer.completeError, onDone: sink.close, cancelOnError: true); return completer.future; } - Future bytesToString([Encoding encoding = utf8]) => + Future bytesToString([final Encoding encoding = utf8]) => encoding.decodeStream(this); } diff --git a/lib/get_connect/http/src/response/response.dart b/lib/get_connect/http/src/response/response.dart index 66a3265a7..c6533e857 100644 --- a/lib/get_connect/http/src/response/response.dart +++ b/lib/get_connect/http/src/response/response.dart @@ -6,11 +6,10 @@ import '../request/request.dart'; import '../status/http_status.dart'; class GraphQLResponse extends Response { - final List? graphQLErrors; - GraphQLResponse({T? body, this.graphQLErrors}) : super(body: body); + GraphQLResponse({super.body, this.graphQLErrors}); - GraphQLResponse.fromResponse(Response res) + GraphQLResponse.fromResponse(final Response res) : graphQLErrors = null, super( request: res.request, @@ -20,6 +19,7 @@ class GraphQLResponse extends Response { statusText: res.statusText, headers: res.headers, body: res.body['data'] as T?); + final List? graphQLErrors; } class Response { @@ -34,13 +34,13 @@ class Response { }); Response copyWith({ - Request? request, - int? statusCode, - Stream>? bodyBytes, - String? bodyString, - String? statusText, - Map? headers, - T? body, + final Request? request, + final int? statusCode, + final Stream>? bodyBytes, + final String? bodyString, + final String? statusText, + final Map? headers, + final T? body, }) { return Response( request: request ?? this.request, @@ -94,7 +94,7 @@ class Response { } Future bodyBytesToString( - Stream> bodyBytes, Map headers) { + final Stream> bodyBytes, final Map headers) { return bodyBytes.bytesToString(_encodingForHeaders(headers)); } @@ -102,14 +102,14 @@ Future bodyBytesToString( /// /// Defaults to [utf8] if the headers don't specify a charset or if that /// charset is unknown. -Encoding _encodingForHeaders(Map headers) => +Encoding _encodingForHeaders(final Map headers) => _encodingForCharset(_contentTypeForHeaders(headers).parameters!['charset']); /// Returns the [Encoding] that corresponds to [charset]. /// /// Returns [fallback] if [charset] is null or if no [Encoding] was found that /// corresponds to [charset]. -Encoding _encodingForCharset(String? charset, [Encoding fallback = utf8]) { +Encoding _encodingForCharset(final String? charset, [final Encoding fallback = utf8]) { if (charset == null) return fallback; return Encoding.getByName(charset) ?? fallback; } @@ -117,28 +117,28 @@ Encoding _encodingForCharset(String? charset, [Encoding fallback = utf8]) { /// Returns the MediaType object for the given headers's content-type. /// /// Defaults to `application/octet-stream`. -HeaderValue _contentTypeForHeaders(Map headers) { - var contentType = headers['content-type']; +HeaderValue _contentTypeForHeaders(final Map headers) { + final contentType = headers['content-type']; if (contentType != null) return HeaderValue.parse(contentType); return HeaderValue('application/octet-stream'); } class HeaderValue { - String _value; - Map? _parameters; - Map? _unmodifiableParameters; - HeaderValue([this._value = '', Map? parameters]) { + HeaderValue([this._value = '', final Map? parameters]) { if (parameters != null) { _parameters = HashMap.from(parameters); } } + String _value; + Map? _parameters; + Map? _unmodifiableParameters; - static HeaderValue parse(String value, - {String parameterSeparator = ';', - String? valueSeparator, - bool preserveBackslash = false}) { - var result = HeaderValue(); + static HeaderValue parse(final String value, + {final String parameterSeparator = ';', + final String? valueSeparator, + final bool preserveBackslash = false}) { + final result = HeaderValue(); result._parse(value, parameterSeparator, valueSeparator, preserveBackslash); return result; } @@ -157,10 +157,10 @@ class HeaderValue { @override String toString() { - var stringBuffer = StringBuffer(); + final stringBuffer = StringBuffer(); stringBuffer.write(_value); if (parameters != null && parameters!.isNotEmpty) { - _parameters!.forEach((name, value) { + _parameters!.forEach((final name, final value) { stringBuffer ..write('; ') ..write(name) @@ -171,8 +171,8 @@ class HeaderValue { return stringBuffer.toString(); } - void _parse(String value, String parameterSeparator, String? valueSeparator, - bool preserveBackslash) { + void _parse(final String value, final String parameterSeparator, final String? valueSeparator, + final bool preserveBackslash) { var index = 0; bool done() => index == value.length; @@ -185,7 +185,7 @@ class HeaderValue { } String parseValue() { - var start = index; + final start = index; while (!done()) { if (value[index] == ' ' || value[index] == '\t' || @@ -198,23 +198,23 @@ class HeaderValue { return value.substring(start, index); } - void expect(String expected) { + void expect(final String expected) { if (done() || value[index] != expected) { throw StateError('Failed to parse header value'); } index++; } - void maybeExpect(String expected) { + void maybeExpect(final String expected) { if (value[index] == expected) index++; } void parseParameters() { - var parameters = HashMap(); + final parameters = HashMap(); _parameters = UnmodifiableMapView(parameters); String parseParameterName() { - var start = index; + final start = index; while (!done()) { if (value[index] == ' ' || value[index] == '\t' || @@ -230,10 +230,10 @@ class HeaderValue { String? parseParameterValue() { if (!done() && value[index] == '"') { - var stringBuffer = StringBuffer(); + final stringBuffer = StringBuffer(); index++; while (!done()) { - if (value[index] == '\\') { + if (value[index] == r'\') { if (index + 1 == value.length) { throw StateError('Failed to parse header value'); } @@ -250,7 +250,7 @@ class HeaderValue { } return stringBuffer.toString(); } else { - var val = parseValue(); + final val = parseValue(); return val == '' ? null : val; } } @@ -258,7 +258,7 @@ class HeaderValue { while (!done()) { bump(); if (done()) return; - var name = parseParameterName(); + final name = parseParameterName(); bump(); if (done()) { parameters[name] = null; diff --git a/lib/get_connect/http/src/status/http_status.dart b/lib/get_connect/http/src/status/http_status.dart index 188cfe046..bebf513dc 100644 --- a/lib/get_connect/http/src/status/http_status.dart +++ b/lib/get_connect/http/src/status/http_status.dart @@ -82,7 +82,7 @@ class HttpStatus { bool get isServerError => between(internalServerError, networkConnectTimeoutError); - bool between(int begin, int end) { + bool between(final int begin, final int end) { return !connectionError && code! >= begin && code! <= end; } diff --git a/lib/get_connect/http/src/utils/utils.dart b/lib/get_connect/http/src/utils/utils.dart index ccda2b7bb..b24eccdb1 100644 --- a/lib/get_connect/http/src/utils/utils.dart +++ b/lib/get_connect/http/src/utils/utils.dart @@ -2,11 +2,11 @@ import 'dart:convert'; -bool isTokenChar(int byte) { +bool isTokenChar(final int byte) { return byte > 31 && byte < 128 && !SEPARATOR_MAP[byte]; } -bool isValueChar(int byte) { +bool isValueChar(final int byte) { return (byte > 31 && byte < 128) || (byte == CharCode.SP) || (byte == CharCode.HT); @@ -42,7 +42,7 @@ const SEPARATOR_MAP = [ F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F ]; -String validateField(String field) { +String validateField(final String field) { for (var i = 0; i < field.length; i++) { if (!isTokenChar(field.codeUnitAt(i))) { throw FormatException( @@ -62,12 +62,12 @@ final newlineRegExp = RegExp(r'\r\n|\r|\n'); /// Returns whether [string] is composed entirely of ASCII-compatible /// characters. -bool isPlainAscii(String string) => _asciiOnly.hasMatch(string); +bool isPlainAscii(final String string) => _asciiOnly.hasMatch(string); const String GET_BOUNDARY = 'getx-http-boundary-'; /// Encode [value] like browsers -String browserEncode(String value) { +String browserEncode(final String value) { return value.replaceAll(newlineRegExp, '%0D%0A').replaceAll('"', '%22'); } diff --git a/lib/get_connect/sockets/sockets.dart b/lib/get_connect/sockets/sockets.dart index faf985562..9fcd6fc42 100644 --- a/lib/get_connect/sockets/sockets.dart +++ b/lib/get_connect/sockets/sockets.dart @@ -3,7 +3,6 @@ import 'src/sockets_stub.dart' if (dart.library.io) 'src/sockets_io.dart'; class GetSocket extends BaseWebSocket { - GetSocket(String url, - {Duration ping = const Duration(seconds: 5), bool allowSelfSigned = true}) - : super(url, ping: ping, allowSelfSigned: allowSelfSigned); + GetSocket(super.url, + {super.ping, super.allowSelfSigned}); } diff --git a/lib/get_connect/sockets/src/socket_notifier.dart b/lib/get_connect/sockets/src/socket_notifier.dart index f8a30faf5..125a82525 100644 --- a/lib/get_connect/sockets/src/socket_notifier.dart +++ b/lib/get_connect/sockets/src/socket_notifier.dart @@ -11,10 +11,10 @@ typedef OpenSocket = void Function(); /// Wrapper class to message and reason from SocketNotifier class Close { - final String? message; - final int? reason; Close(this.message, this.reason); + final String? message; + final int? reason; @override String toString() { @@ -33,23 +33,23 @@ class SocketNotifier { late OpenSocket open; /// subscribe to close events - void addCloses(CloseSocket socket) { + void addCloses(final CloseSocket socket) { _onCloses!.add(socket); } /// subscribe to error events - void addErrors(CloseSocket socket) { - _onErrors!.add((socket)); + void addErrors(final CloseSocket socket) { + _onErrors!.add(socket); } /// subscribe to named events - void addEvents(String event, MessageSocket socket) { + void addEvents(final String event, final MessageSocket socket) { _onEvents![event] = socket; } /// subscribe to message events - void addMessages(MessageSocket socket) { - _onMessages!.add((socket)); + void addMessages(final MessageSocket socket) { + _onMessages!.add(socket); } /// Dispose messages, events, closes and errors subscriptions @@ -61,15 +61,15 @@ class SocketNotifier { } /// Notify all subscriptions on [addCloses] - void notifyClose(Close err) { - for (var item in _onCloses!) { + void notifyClose(final Close err) { + for (final item in _onCloses!) { item(err); } } /// Notify all subscriptions on [addMessages] - void notifyData(dynamic data) { - for (var item in _onMessages!) { + void notifyData(final dynamic data) { + for (final item in _onMessages!) { item(data); } if (data is String) { @@ -78,16 +78,16 @@ class SocketNotifier { } /// Notify all subscriptions on [addErrors] - void notifyError(Close err) { + void notifyError(final Close err) { // rooms.removeWhere((key, value) => value.contains(_ws)); - for (var item in _onErrors!) { + for (final item in _onErrors!) { item(err); } } - void _tryOn(String message) { + void _tryOn(final String message) { try { - var msg = jsonDecode(message); + final msg = jsonDecode(message); final event = msg['type']; final data = msg['data']; if (_onEvents!.containsKey(event)) { diff --git a/lib/get_connect/sockets/src/sockets_html.dart b/lib/get_connect/sockets/src/sockets_html.dart index d2a9317ca..5ee8a1ccb 100644 --- a/lib/get_connect/sockets/src/sockets_html.dart +++ b/lib/get_connect/sockets/src/sockets_html.dart @@ -7,15 +7,6 @@ import '../../../get_core/get_core.dart'; import 'socket_notifier.dart'; class BaseWebSocket { - String url; - WebSocket? socket; - SocketNotifier? socketNotifier = SocketNotifier(); - Duration ping; - bool isDisposed = false; - bool allowSelfSigned; - - ConnectionStatus? connectionStatus; - Timer? _t; BaseWebSocket( this.url, { this.ping = const Duration(seconds: 5), @@ -25,8 +16,17 @@ class BaseWebSocket { ? url.replaceAll('https:', 'wss:') : url.replaceAll('http:', 'ws:'); } + String url; + WebSocket? socket; + SocketNotifier? socketNotifier = SocketNotifier(); + Duration ping; + bool isDisposed = false; + bool allowSelfSigned; + + ConnectionStatus? connectionStatus; + Timer? _t; - void close([int? status, String? reason]) { + void close([final int? status, final String? reason]) { socket?.close(status, reason); } @@ -35,25 +35,25 @@ class BaseWebSocket { try { connectionStatus = ConnectionStatus.connecting; socket = WebSocket(url); - socket!.onOpen.listen((e) { + socket!.onOpen.listen((final e) { socketNotifier?.open(); - _t = Timer?.periodic(ping, (t) { + _t = Timer?.periodic(ping, (final t) { socket!.send(''); }); connectionStatus = ConnectionStatus.connected; }); - socket!.onMessage.listen((event) { + socket!.onMessage.listen((final event) { socketNotifier!.notifyData(event.data); }); - socket!.onClose.listen((e) { + socket!.onClose.listen((final e) { _t?.cancel(); connectionStatus = ConnectionStatus.closed; socketNotifier!.notifyClose(Close(e.reason, e.code)); }); - socket!.onError.listen((event) { + socket!.onError.listen((final event) { _t?.cancel(); socketNotifier!.notifyError(Close(event.toString(), 0)); connectionStatus = ConnectionStatus.closed; @@ -72,32 +72,32 @@ class BaseWebSocket { isDisposed = true; } - void emit(String event, dynamic data) { + void emit(final String event, final dynamic data) { send(jsonEncode({'type': event, 'data': data})); } - void on(String event, MessageSocket message) { + void on(final String event, final MessageSocket message) { socketNotifier!.addEvents(event, message); } - void onClose(CloseSocket fn) { + void onClose(final CloseSocket fn) { socketNotifier!.addCloses(fn); } - void onError(CloseSocket fn) { + void onError(final CloseSocket fn) { socketNotifier!.addErrors(fn); } - void onMessage(MessageSocket fn) { + void onMessage(final MessageSocket fn) { socketNotifier!.addMessages(fn); } // ignore: use_setters_to_change_properties - void onOpen(OpenSocket fn) { + void onOpen(final OpenSocket fn) { socketNotifier!.open = fn; } - void send(dynamic data) { + void send(final dynamic data) { if (connectionStatus == ConnectionStatus.closed) { connect(); } diff --git a/lib/get_connect/sockets/src/sockets_io.dart b/lib/get_connect/sockets/src/sockets_io.dart index 6b7f5d535..1910aa6df 100644 --- a/lib/get_connect/sockets/src/sockets_io.dart +++ b/lib/get_connect/sockets/src/sockets_io.dart @@ -7,6 +7,12 @@ import '../../../get_core/get_core.dart'; import 'socket_notifier.dart'; class BaseWebSocket { + + BaseWebSocket( + this.url, { + this.ping = const Duration(seconds: 5), + this.allowSelfSigned = true, + }); String url; WebSocket? socket; SocketNotifier? socketNotifier = SocketNotifier(); @@ -15,13 +21,7 @@ class BaseWebSocket { bool allowSelfSigned; ConnectionStatus? connectionStatus; - BaseWebSocket( - this.url, { - this.ping = const Duration(seconds: 5), - this.allowSelfSigned = true, - }); - - void close([int? status, String? reason]) { + void close([final int? status, final String? reason]) { socket?.close(status, reason); } @@ -40,9 +40,9 @@ class BaseWebSocket { socketNotifier?.open(); connectionStatus = ConnectionStatus.connected; - socket!.listen((data) { + socket!.listen((final data) { socketNotifier!.notifyData(data); - }, onError: (err) { + }, onError: (final err) { socketNotifier!.notifyError(Close(err.toString(), 1005)); }, onDone: () { connectionStatus = ConnectionStatus.closed; @@ -64,32 +64,32 @@ class BaseWebSocket { isDisposed = true; } - void emit(String event, dynamic data) { + void emit(final String event, final dynamic data) { send(jsonEncode({'type': event, 'data': data})); } - void on(String event, MessageSocket message) { + void on(final String event, final MessageSocket message) { socketNotifier!.addEvents(event, message); } - void onClose(CloseSocket fn) { + void onClose(final CloseSocket fn) { socketNotifier!.addCloses(fn); } - void onError(CloseSocket fn) { + void onError(final CloseSocket fn) { socketNotifier!.addErrors(fn); } - void onMessage(MessageSocket fn) { + void onMessage(final MessageSocket fn) { socketNotifier!.addMessages(fn); } // ignore: use_setters_to_change_properties - void onOpen(OpenSocket fn) { + void onOpen(final OpenSocket fn) { socketNotifier!.open = fn; } - void send(dynamic data) async { + void send(final dynamic data) async { if (connectionStatus == ConnectionStatus.closed) { await connect(); } @@ -99,28 +99,28 @@ class BaseWebSocket { } } - Future _connectForSelfSignedCert(String url) async { + Future _connectForSelfSignedCert(final String url) async { try { - var r = Random(); - var key = base64.encode(List.generate(8, (_) => r.nextInt(255))); - var client = HttpClient(context: SecurityContext()); - client.badCertificateCallback = (cert, host, port) { + final r = Random(); + final key = base64.encode(List.generate(8, (final _) => r.nextInt(255))); + final client = HttpClient(context: SecurityContext()); + client.badCertificateCallback = (final cert, final host, final port) { Get.log( 'BaseWebSocket: Allow self-signed certificate => $host:$port. '); return true; }; - var request = await client.getUrl(Uri.parse(url)) + final request = await client.getUrl(Uri.parse(url)) ..headers.add('Connection', 'Upgrade') ..headers.add('Upgrade', 'websocket') ..headers.add('Cache-Control', 'no-cache') ..headers.add('Sec-WebSocket-Version', '13') ..headers.add('Sec-WebSocket-Key', key.toLowerCase()); - var response = await request.close(); + final response = await request.close(); // ignore: close_sinks - var socket = await response.detachSocket(); - var webSocket = WebSocket.fromUpgradedSocket( + final socket = await response.detachSocket(); + final webSocket = WebSocket.fromUpgradedSocket( socket, serverSide: false, ); diff --git a/lib/get_connect/sockets/src/sockets_stub.dart b/lib/get_connect/sockets/src/sockets_stub.dart index 98ebd911d..fa54169cf 100644 --- a/lib/get_connect/sockets/src/sockets_stub.dart +++ b/lib/get_connect/sockets/src/sockets_stub.dart @@ -1,9 +1,6 @@ import './socket_notifier.dart'; class BaseWebSocket { - String url; - Duration ping; - bool allowSelfSigned; BaseWebSocket( this.url, { this.ping = const Duration(seconds: 5), @@ -11,36 +8,39 @@ class BaseWebSocket { }) { throw 'To use sockets you need dart:io or dart:html'; } + String url; + Duration ping; + bool allowSelfSigned; Future connect() async { throw 'To use sockets you need dart:io or dart:html'; } - void onOpen(OpenSocket fn) { + void onOpen(final OpenSocket fn) { throw 'To use sockets you need dart:io or dart:html'; } - void onClose(CloseSocket fn) { + void onClose(final CloseSocket fn) { throw 'To use sockets you need dart:io or dart:html'; } - void onError(CloseSocket fn) { + void onError(final CloseSocket fn) { throw 'To use sockets you need dart:io or dart:html'; } - void onMessage(MessageSocket fn) { + void onMessage(final MessageSocket fn) { throw 'To use sockets you need dart:io or dart:html'; } - void on(String event, MessageSocket message) { + void on(final String event, final MessageSocket message) { throw 'To use sockets you need dart:io or dart:html'; } - void close([int? status, String? reason]) { + void close([final int? status, final String? reason]) { throw 'To use sockets you need dart:io or dart:html'; } - void send(dynamic data) async { + void send(final dynamic data) async { throw 'To use sockets you need dart:io or dart:html'; } @@ -48,7 +48,7 @@ class BaseWebSocket { throw 'To use sockets you need dart:io or dart:html'; } - void emit(String event, dynamic data) { + void emit(final String event, final dynamic data) { throw 'To use sockets you need dart:io or dart:html'; } } diff --git a/lib/get_core/src/log.dart b/lib/get_core/src/log.dart index 01dd302fe..08819fb5a 100644 --- a/lib/get_core/src/log.dart +++ b/lib/get_core/src/log.dart @@ -5,6 +5,6 @@ import 'get_main.dart'; typedef LogWriterCallback = void Function(String text, {bool isError}); /// default logger from GetX -void defaultLogWriterCallback(String value, {bool isError = false}) { +void defaultLogWriterCallback(final String value, {final bool isError = false}) { if (isError || Get.isLogEnable) developer.log(value, name: 'GETX'); } diff --git a/lib/get_core/src/typedefs.dart b/lib/get_core/src/typedefs.dart index 328fd8092..8b67b6cc4 100644 --- a/lib/get_core/src/typedefs.dart +++ b/lib/get_core/src/typedefs.dart @@ -6,4 +6,4 @@ typedef ValueUpdater = T Function(); /// We use this so that APIs that have become /// non-nullable can still be used with `!` and `?` /// to support older versions of the API as well. -T? ambiguate(T? value) => value; +T? ambiguate(final T? value) => value; diff --git a/lib/get_instance/src/extension_instance.dart b/lib/get_instance/src/extension_instance.dart index 211463912..7ca54fcba 100644 --- a/lib/get_instance/src/extension_instance.dart +++ b/lib/get_instance/src/extension_instance.dart @@ -7,12 +7,6 @@ import '../../get_navigation/src/router_report.dart'; import 'lifecycle.dart'; class InstanceInfo { - final bool? isPermanent; - final bool? isSingleton; - bool get isCreate => !isSingleton!; - final bool isRegistered; - final bool isPrepared; - final bool? isInit; const InstanceInfo({ required this.isPermanent, required this.isSingleton, @@ -20,6 +14,12 @@ class InstanceInfo { required this.isPrepared, required this.isInit, }); + final bool? isPermanent; + final bool? isSingleton; + bool get isCreate => !isSingleton!; + final bool isRegistered; + final bool isPrepared; + final bool? isInit; @override String toString() { @@ -35,7 +35,7 @@ extension ResetInstance on GetInterface { /// `clearFactory` clears the callbacks registered by [lazyPut] /// `clearRouteBindings` clears Instances associated with routes. /// - bool resetInstance({bool clearRouteBindings = true}) { + bool resetInstance({final bool clearRouteBindings = true}) { // if (clearFactory) _factory.clear(); // deleteAll(force: true); if (clearRouteBindings) RouterReportManager.instance.clearRouteKeys(); @@ -50,7 +50,8 @@ extension Inst on GetInterface { /// Holds references to every registered Instance when using /// `Get.put()` - static final Map _singl = {}; + static final Map _singl = + {}; /// Holds a reference to every registered callback when using /// `Get.lazyPut()` @@ -71,15 +72,15 @@ extension Inst on GetInterface { // } S put( - S dependency, { - String? tag, - bool permanent = false, + final S dependency, { + final String? tag, + final bool permanent = false, }) { _insert( isSingleton: true, name: tag, permanent: permanent, - builder: (() => dependency)); + builder: () => dependency); return find(tag: tag); } @@ -106,10 +107,10 @@ extension Inst on GetInterface { /// Subsequent calls to `Get.lazyPut()` with the same parameters /// (<[S]> and optionally [tag] will **not** override the original). void lazyPut( - InstanceBuilderCallback builder, { - String? tag, - bool? fenix, - bool permanent = false, + final InstanceBuilderCallback builder, { + final String? tag, + final bool? fenix, + final bool permanent = false, }) { _insert( isSingleton: true, @@ -137,9 +138,9 @@ extension Inst on GetInterface { /// Repl b = find(); /// print(a==b); (false)``` void spawn( - InstanceBuilderCallback builder, { - String? tag, - bool permanent = true, + final InstanceBuilderCallback builder, { + final String? tag, + final bool permanent = true, }) { _insert( isSingleton: false, @@ -151,17 +152,17 @@ extension Inst on GetInterface { /// Injects the Instance [S] builder into the `_singleton` HashMap. void _insert({ - bool? isSingleton, - String? name, - bool permanent = false, - required InstanceBuilderCallback builder, - bool fenix = false, + required final InstanceBuilderCallback builder, + final bool? isSingleton, + final String? name, + final bool permanent = false, + final bool fenix = false, }) { - final key = _getKey(S, name); + final String key = _getKey(S, name); _InstanceBuilderFactory? dep; if (_singl.containsKey(key)) { - final newDep = _singl[key]; + final _InstanceBuilderFactory? newDep = _singl[key]; if (newDep == null || !newDep.isDirty) { return; } else { @@ -188,12 +189,12 @@ extension Inst on GetInterface { /// (not for Singletons access). /// Returns the instance if not initialized, required for Get.create() to /// work properly. - S? _initDependencies({String? name}) { - final key = _getKey(S, name); - final isInit = _singl[key]!.isInit; + S? _initDependencies({final String? name}) { + final String key = _getKey(S, name); + final bool isInit = _singl[key]!.isInit; S? i; if (!isInit) { - final isSingleton = _singl[key]?.isSingleton ?? false; + final bool isSingleton = _singl[key]?.isSingleton ?? false; if (isSingleton) { _singl[key]!.isInit = true; } @@ -209,8 +210,8 @@ extension Inst on GetInterface { return i; } - InstanceInfo getInstanceInfo({String? tag}) { - final build = _getDependency(tag: tag); + InstanceInfo getInstanceInfo({final String? tag}) { + final _InstanceBuilderFactory? build = _getDependency(tag: tag); return InstanceInfo( isPermanent: build?.permanent, @@ -221,8 +222,9 @@ extension Inst on GetInterface { ); } - _InstanceBuilderFactory? _getDependency({String? tag, String? key}) { - final newKey = key ?? _getKey(S, tag); + _InstanceBuilderFactory? _getDependency( + {final String? tag, final String? key}) { + final String newKey = key ?? _getKey(S, tag); if (!_singl.containsKey(newKey)) { Get.log('Instance "$newKey" is not registered.', isError: true); @@ -232,10 +234,10 @@ extension Inst on GetInterface { } } - void markAsDirty({String? tag, String? key}) { - final newKey = key ?? _getKey(S, tag); + void markAsDirty({final String? tag, final String? key}) { + final String newKey = key ?? _getKey(S, tag); if (_singl.containsKey(newKey)) { - final dep = _singl[newKey]; + final _InstanceBuilderFactory? dep = _singl[newKey]; if (dep != null && !dep.permanent) { dep.isDirty = true; } @@ -243,8 +245,8 @@ extension Inst on GetInterface { } /// Initializes the controller - S _startController({String? tag}) { - final key = _getKey(S, tag); + S _startController({final String? tag}) { + final String key = _getKey(S, tag); final i = _singl[key]!.getDependency() as S; if (i is GetLifeCycleMixin) { i.onStart(); @@ -260,8 +262,8 @@ extension Inst on GetInterface { return i; } - S putOrFind(InstanceBuilderCallback dep, {String? tag}) { - final key = _getKey(S, tag); + S putOrFind(final InstanceBuilderCallback dep, {final String? tag}) { + final String key = _getKey(S, tag); if (_singl.containsKey(key)) { return _singl[key]!.getDependency() as S; @@ -275,10 +277,10 @@ extension Inst on GetInterface { /// it will create an instance each time you call [find]. /// If the registered type <[S]> (or [tag]) is a Controller, /// it will initialize it's lifecycle. - S find({String? tag}) { - final key = _getKey(S, tag); + S find({final String? tag}) { + final String key = _getKey(S, tag); if (isRegistered(tag: tag)) { - final dep = _singl[key]; + final _InstanceBuilderFactory? dep = _singl[key]; if (dep == null) { if (tag == null) { throw 'Class "$S" is not registered'; @@ -300,7 +302,7 @@ extension Inst on GetInterface { /// The findOrNull method will return the instance if it is registered; /// otherwise, it will return null. - S? findOrNull({String? tag}) { + S? findOrNull({final String? tag}) { if (isRegistered(tag: tag)) { return find(tag: tag); } @@ -310,9 +312,9 @@ extension Inst on GetInterface { /// Replace a parent instance of a class in dependency management /// with a [child] instance /// - [tag] optional, if you use a [tag] to register the Instance. - void replace

(P child, {String? tag}) { - final info = getInstanceInfo

(tag: tag); - final permanent = (info.isPermanent ?? false); + void replace

(final P child, {final String? tag}) { + final InstanceInfo info = getInstanceInfo

(tag: tag); + final bool permanent = info.isPermanent ?? false; delete

(tag: tag, force: permanent); put(child, tag: tag, permanent: permanent); } @@ -324,17 +326,17 @@ extension Inst on GetInterface { /// /// Note: if fenix is not provided it will be set to true if /// the parent instance was permanent - void lazyReplace

(InstanceBuilderCallback

builder, - {String? tag, bool? fenix}) { - final info = getInstanceInfo

(tag: tag); - final permanent = (info.isPermanent ?? false); + void lazyReplace

(final InstanceBuilderCallback

builder, + {final String? tag, final bool? fenix}) { + final InstanceInfo info = getInstanceInfo

(tag: tag); + final bool permanent = info.isPermanent ?? false; delete

(tag: tag, force: permanent); lazyPut(builder, tag: tag, fenix: fenix ?? permanent); } /// Generates the key based on [type] (and optionally a [name]) /// to register an Instance Builder in the hashmap. - String _getKey(Type type, String? name) { + String _getKey(final Type type, final String? name) { return name == null ? type.toString() : type.toString() + name; } @@ -354,15 +356,16 @@ extension Inst on GetInterface { /// - [key] For internal usage, is the processed key used to register /// the Instance. **don't use** it unless you know what you are doing. /// - [force] Will delete an Instance even if marked as `permanent`. - bool delete({String? tag, String? key, bool force = false}) { - final newKey = key ?? _getKey(S, tag); + bool delete( + {final String? tag, final String? key, final bool force = false}) { + final String newKey = key ?? _getKey(S, tag); if (!_singl.containsKey(newKey)) { Get.log('Instance "$newKey" already removed.', isError: true); return false; } - final dep = _singl[newKey]; + final _InstanceBuilderFactory? dep = _singl[newKey]; if (dep == null) return false; @@ -417,15 +420,15 @@ extension Inst on GetInterface { /// controllers `DisposableInterface`, cleans up the memory /// /// - [force] Will delete the Instances even if marked as `permanent`. - void deleteAll({bool force = false}) { - final keys = _singl.keys.toList(); - for (final key in keys) { + void deleteAll({final bool force = false}) { + final List keys = _singl.keys.toList(); + for (final String key in keys) { delete(key: key, force: force); } } - void reloadAll({bool force = false}) { - _singl.forEach((key, value) { + void reloadAll({final bool force = false}) { + _singl.forEach((final String key, final _InstanceBuilderFactory value) { if (value.permanent && !force) { Get.log('Instance "$key" is permanent. Skipping reload'); } else { @@ -437,13 +440,14 @@ extension Inst on GetInterface { } void reload({ - String? tag, - String? key, - bool force = false, + final String? tag, + final String? key, + final bool force = false, }) { - final newKey = key ?? _getKey(S, tag); + final String newKey = key ?? _getKey(S, tag); - final builder = _getDependency(tag: tag, key: newKey); + final _InstanceBuilderFactory? builder = + _getDependency(tag: tag, key: newKey); if (builder == null) return; if (builder.permanent && !force) { @@ -472,15 +476,17 @@ extension Inst on GetInterface { /// Check if a Class Instance<[S]> (or [tag]) is registered in memory. /// - [tag] is optional, if you used a [tag] to register the Instance. - bool isRegistered({String? tag}) => _singl.containsKey(_getKey(S, tag)); + bool isRegistered({final String? tag}) => + _singl.containsKey(_getKey(S, tag)); /// Checks if a lazy factory callback `Get.lazyPut()` that returns an /// Instance<[S]> is registered in memory. /// - [tag] is optional, if you used a [tag] to register the lazy Instance. - bool isPrepared({String? tag}) { - final newKey = _getKey(S, tag); + bool isPrepared({final String? tag}) { + final String newKey = _getKey(S, tag); - final builder = _getDependency(tag: tag, key: newKey); + final _InstanceBuilderFactory? builder = + _getDependency(tag: tag, key: newKey); if (builder == null) { return false; } @@ -504,6 +510,16 @@ typedef AsyncInstanceBuilderCallback = Future Function(); /// Internal class to register instances with `Get.put()`. class _InstanceBuilderFactory { + _InstanceBuilderFactory({ + required this.isSingleton, + required this.builderFunc, + required this.permanent, + required this.isInit, + required this.fenix, + required this.tag, + required this.lateRemove, + }); + /// Marks the Builder as a single instance. /// For reusing [dependency] instead of [builderFunc] bool? isSingleton; @@ -531,16 +547,6 @@ class _InstanceBuilderFactory { String? tag; - _InstanceBuilderFactory({ - required this.isSingleton, - required this.builderFunc, - required this.permanent, - required this.isInit, - required this.fenix, - required this.tag, - required this.lateRemove, - }); - void _showInitLog() { if (tag == null) { Get.log('Instance "$S" has been created'); diff --git a/lib/get_instance/src/lifecycle.dart b/lib/get_instance/src/lifecycle.dart index 0f146b450..e44c9d051 100644 --- a/lib/get_instance/src/lifecycle.dart +++ b/lib/get_instance/src/lifecycle.dart @@ -17,7 +17,7 @@ mixin GetLifeCycleMixin { @protected @mustCallSuper void onInit() { - ambiguate(Engine.instance)?.addPostFrameCallback((_) => onReady()); + ambiguate(Engine.instance)?.addPostFrameCallback((final _) => onReady()); } /// Called 1 frame after onInit(). It is the perfect place to enter diff --git a/lib/get_navigation/src/bottomsheet/bottomsheet.dart b/lib/get_navigation/src/bottomsheet/bottomsheet.dart index 25c29f9bb..9257e5b98 100644 --- a/lib/get_navigation/src/bottomsheet/bottomsheet.dart +++ b/lib/get_navigation/src/bottomsheet/bottomsheet.dart @@ -5,7 +5,7 @@ import '../router_report.dart'; class GetModalBottomSheetRoute extends PopupRoute { GetModalBottomSheetRoute({ - this.builder, + required this.isScrollControlled, this.builder, this.theme, this.barrierLabel, this.backgroundColor, @@ -17,12 +17,11 @@ class GetModalBottomSheetRoute extends PopupRoute { this.modalBarrierColor, this.isDismissible = true, this.enableDrag = true, - required this.isScrollControlled, - RouteSettings? settings, + super.settings, this.enterBottomSheetDuration = const Duration(milliseconds: 250), this.exitBottomSheetDuration = const Duration(milliseconds: 200), this.curve, - }) : super(settings: settings) { + }) { RouterReportManager.instance.reportCurrentRoute(this); } final bool? isPersistent; @@ -82,8 +81,8 @@ class GetModalBottomSheetRoute extends PopupRoute { } @override - Widget buildPage(BuildContext context, Animation animation, - Animation secondaryAnimation) { + Widget buildPage(final BuildContext context, final Animation animation, + final Animation secondaryAnimation) { final sheetTheme = theme?.bottomSheetTheme ?? Theme.of(context).bottomSheetTheme; // By definition, the bottom sheet is aligned to the bottom of the page @@ -115,7 +114,7 @@ class GetModalBottomSheetRoute extends PopupRoute { class _GetModalBottomSheet extends StatefulWidget { const _GetModalBottomSheet({ - Key? key, + super.key, this.route, this.backgroundColor, this.elevation, @@ -124,7 +123,7 @@ class _GetModalBottomSheet extends StatefulWidget { this.isScrollControlled = false, this.enableDrag = true, this.isPersistent = false, - }) : super(key: key); + }); final bool isPersistent; final GetModalBottomSheetRoute? route; final bool isScrollControlled; @@ -139,7 +138,7 @@ class _GetModalBottomSheet extends StatefulWidget { } class _GetModalBottomSheetState extends State<_GetModalBottomSheet> { - String _getRouteLabel(MaterialLocalizations localizations) { + String _getRouteLabel(final MaterialLocalizations localizations) { if ((Theme.of(context).platform == TargetPlatform.android) || (Theme.of(context).platform == TargetPlatform.fuchsia)) { return localizations.dialogLabel; @@ -149,7 +148,7 @@ class _GetModalBottomSheetState extends State<_GetModalBottomSheet> { } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMaterialLocalizations(context)); final mediaQuery = MediaQuery.of(context); @@ -158,7 +157,7 @@ class _GetModalBottomSheetState extends State<_GetModalBottomSheet> { return AnimatedBuilder( animation: widget.route!.animation!, - builder: (context, child) { + builder: (final context, final child) { // Disable the initial animation when accessible navigation is on so // that the semantics are added to the tree at the correct time. final animationValue = mediaQuery.accessibleNavigation @@ -214,7 +213,7 @@ class _GetModalBottomSheetState extends State<_GetModalBottomSheet> { class _GetPerModalBottomSheet extends StatefulWidget { const _GetPerModalBottomSheet({ - Key? key, + super.key, this.route, this.isPersistent, this.backgroundColor, @@ -223,7 +222,7 @@ class _GetPerModalBottomSheet extends StatefulWidget { this.clipBehavior, this.isScrollControlled = false, this.enableDrag = true, - }) : super(key: key); + }); final bool? isPersistent; final GetModalBottomSheetRoute? route; final bool isScrollControlled; @@ -242,7 +241,7 @@ class _GetPerModalBottomSheet extends StatefulWidget { // ignore: lines_longer_than_80_chars class _GetPerModalBottomSheetState extends State<_GetPerModalBottomSheet> { - String _getRouteLabel(MaterialLocalizations localizations) { + String _getRouteLabel(final MaterialLocalizations localizations) { if ((Theme.of(context).platform == TargetPlatform.android) || (Theme.of(context).platform == TargetPlatform.fuchsia)) { return localizations.dialogLabel; @@ -252,7 +251,7 @@ class _GetPerModalBottomSheetState } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMaterialLocalizations(context)); final mediaQuery = MediaQuery.of(context); @@ -261,7 +260,7 @@ class _GetPerModalBottomSheetState return AnimatedBuilder( animation: widget.route!.animation!, - builder: (context, child) { + builder: (final context, final child) { // Disable the initial animation when accessible navigation is on so // that the semantics are added to the tree at the correct time. final animationValue = mediaQuery.accessibleNavigation @@ -322,11 +321,10 @@ class _GetModalBottomSheetLayout extends SingleChildLayoutDelegate { final bool isScrollControlled; @override - BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + BoxConstraints getConstraintsForChild(final BoxConstraints constraints) { return BoxConstraints( minWidth: constraints.maxWidth, maxWidth: constraints.maxWidth, - minHeight: 0.0, maxHeight: isScrollControlled ? constraints.maxHeight : constraints.maxHeight * 9.0 / 16.0, @@ -334,12 +332,12 @@ class _GetModalBottomSheetLayout extends SingleChildLayoutDelegate { } @override - Offset getPositionForChild(Size size, Size childSize) { + Offset getPositionForChild(final Size size, final Size childSize) { return Offset(0.0, size.height - childSize.height * progress); } @override - bool shouldRelayout(_GetModalBottomSheetLayout oldDelegate) { + bool shouldRelayout(final _GetModalBottomSheetLayout oldDelegate) { return progress != oldDelegate.progress; } } diff --git a/lib/get_navigation/src/dialog/dialog_route.dart b/lib/get_navigation/src/dialog/dialog_route.dart index 4e32b95de..6442e8154 100644 --- a/lib/get_navigation/src/dialog/dialog_route.dart +++ b/lib/get_navigation/src/dialog/dialog_route.dart @@ -4,20 +4,19 @@ import '../router_report.dart'; class GetDialogRoute extends PopupRoute { GetDialogRoute({ - required RoutePageBuilder pageBuilder, - bool barrierDismissible = true, - String? barrierLabel, - Color barrierColor = const Color(0x80000000), - Duration transitionDuration = const Duration(milliseconds: 200), - RouteTransitionsBuilder? transitionBuilder, - RouteSettings? settings, + required final RoutePageBuilder pageBuilder, + final bool barrierDismissible = true, + final String? barrierLabel, + final Color barrierColor = const Color(0x80000000), + final Duration transitionDuration = const Duration(milliseconds: 200), + final RouteTransitionsBuilder? transitionBuilder, + super.settings, }) : widget = pageBuilder, _barrierDismissible = barrierDismissible, _barrierLabel = barrierLabel, _barrierColor = barrierColor, _transitionDuration = transitionDuration, - _transitionBuilder = transitionBuilder, - super(settings: settings) { + _transitionBuilder = transitionBuilder { RouterReportManager.instance.reportCurrentRoute(this); } @@ -48,8 +47,8 @@ class GetDialogRoute extends PopupRoute { final RouteTransitionsBuilder? _transitionBuilder; @override - Widget buildPage(BuildContext context, Animation animation, - Animation secondaryAnimation) { + Widget buildPage(final BuildContext context, final Animation animation, + final Animation secondaryAnimation) { return Semantics( scopesRoute: true, explicitChildNodes: true, @@ -58,8 +57,8 @@ class GetDialogRoute extends PopupRoute { } @override - Widget buildTransitions(BuildContext context, Animation animation, - Animation secondaryAnimation, Widget child) { + Widget buildTransitions(final BuildContext context, final Animation animation, + final Animation secondaryAnimation, final Widget child) { if (_transitionBuilder == null) { return FadeTransition( opacity: CurvedAnimation( diff --git a/lib/get_navigation/src/extension_navigation.dart b/lib/get_navigation/src/extension_navigation.dart index 3eb151a73..8fa51558e 100644 --- a/lib/get_navigation/src/extension_navigation.dart +++ b/lib/get_navigation/src/extension_navigation.dart @@ -13,26 +13,26 @@ NavigatorState? get navigator => GetNavigationExt(Get).key.currentState; extension ExtensionBottomSheet on GetInterface { Future bottomSheet( - Widget bottomsheet, { - Color? backgroundColor, - double? elevation, - bool persistent = true, - ShapeBorder? shape, - Clip? clipBehavior, - Color? barrierColor, - bool? ignoreSafeArea, - bool isScrollControlled = false, - bool useRootNavigator = false, - bool isDismissible = true, - bool enableDrag = true, - RouteSettings? settings, - Duration? enterBottomSheetDuration, - Duration? exitBottomSheetDuration, - Curve? curve, + final Widget bottomsheet, { + final Color? backgroundColor, + final double? elevation, + final bool persistent = true, + final ShapeBorder? shape, + final Clip? clipBehavior, + final Color? barrierColor, + final bool? ignoreSafeArea, + final bool isScrollControlled = false, + final bool useRootNavigator = false, + final bool isDismissible = true, + final bool enableDrag = true, + final RouteSettings? settings, + final Duration? enterBottomSheetDuration, + final Duration? exitBottomSheetDuration, + final Curve? curve, }) { return Navigator.of(overlayContext!, rootNavigator: useRootNavigator) .push(GetModalBottomSheetRoute( - builder: (_) => bottomsheet, + builder: (final _) => bottomsheet, isPersistent: persistent, // theme: Theme.of(key.currentContext, shadowThemeOnly: true), theme: Theme.of(key.currentContext!), @@ -65,26 +65,30 @@ extension ExtensionDialog on GetInterface { /// overriding the defaults when the dialog shows up and closes. /// When the dialog closes, uses those animations in reverse. Future dialog( - Widget widget, { - bool barrierDismissible = true, - Color? barrierColor, - bool useSafeArea = true, - GlobalKey? navigatorKey, - Object? arguments, - Duration? transitionDuration, - Curve? transitionCurve, - String? name, - RouteSettings? routeSettings, - String? id, + final Widget widget, { + final bool barrierDismissible = true, + final Color? barrierColor, + final bool useSafeArea = true, + final GlobalKey? navigatorKey, + final Object? arguments, + final Duration? transitionDuration, + final Curve? transitionCurve, + final String? name, + final RouteSettings? routeSettings, + final String? id, }) { assert(debugCheckHasMaterialLocalizations(context!)); // final theme = Theme.of(context, shadowThemeOnly: true); - final theme = Theme.of(context!); + final ThemeData theme = Theme.of(context!); return generalDialog( - pageBuilder: (buildContext, animation, secondaryAnimation) { - final pageChild = widget; - Widget dialog = Builder(builder: (context) { + pageBuilder: ( + final BuildContext buildContext, + final Animation animation, + final Animation secondaryAnimation, + ) { + final Widget pageChild = widget; + Widget dialog = Builder(builder: (final BuildContext context) { return Theme(data: theme, child: pageChild); }); if (useSafeArea) { @@ -96,7 +100,12 @@ extension ExtensionDialog on GetInterface { barrierLabel: MaterialLocalizations.of(context!).modalBarrierDismissLabel, barrierColor: barrierColor ?? Colors.black54, transitionDuration: transitionDuration ?? defaultDialogTransitionDuration, - transitionBuilder: (context, animation, secondaryAnimation, child) { + transitionBuilder: ( + final BuildContext context, + final Animation animation, + final Animation secondaryAnimation, + final Widget child, + ) { return FadeTransition( opacity: CurvedAnimation( parent: animation, @@ -114,18 +123,19 @@ extension ExtensionDialog on GetInterface { /// Api from showGeneralDialog with no context Future generalDialog( - {required RoutePageBuilder pageBuilder, - bool barrierDismissible = false, - String? barrierLabel, - Color barrierColor = const Color(0x80000000), - Duration transitionDuration = const Duration(milliseconds: 200), - RouteTransitionsBuilder? transitionBuilder, - GlobalKey? navigatorKey, - RouteSettings? routeSettings, - String? id}) { + {required final RoutePageBuilder pageBuilder, + final bool barrierDismissible = false, + final String? barrierLabel, + final Color barrierColor = const Color(0x80000000), + final Duration transitionDuration = const Duration(milliseconds: 200), + final RouteTransitionsBuilder? transitionBuilder, + final GlobalKey? navigatorKey, + final RouteSettings? routeSettings, + final String? id}) { assert(!barrierDismissible || barrierLabel != null); - final key = navigatorKey ?? Get.nestedKey(id)?.navigatorKey; - final nav = key?.currentState ?? + final GlobalKey? key = + navigatorKey ?? Get.nestedKey(id)?.navigatorKey; + final NavigatorState nav = key?.currentState ?? Navigator.of(overlayContext!, rootNavigator: true); //overlay context will always return the root navigator @@ -144,41 +154,41 @@ extension ExtensionDialog on GetInterface { /// Custom UI Dialog. Future defaultDialog({ - String title = "Alert", - EdgeInsetsGeometry? titlePadding, - TextStyle? titleStyle, - Widget? content, - String? id, - EdgeInsetsGeometry? contentPadding, - VoidCallback? onConfirm, - VoidCallback? onCancel, - VoidCallback? onCustom, - Color? cancelTextColor, - Color? confirmTextColor, - String? textConfirm, - String? textCancel, - String? textCustom, - Widget? confirm, - Widget? cancel, - Widget? custom, - Color? backgroundColor, - bool barrierDismissible = true, - Color? buttonColor, - String middleText = "\n", - TextStyle? middleTextStyle, - double radius = 20.0, + final String title = 'Alert', + final EdgeInsetsGeometry? titlePadding, + final TextStyle? titleStyle, + final Widget? content, + final String? id, + final EdgeInsetsGeometry? contentPadding, + final VoidCallback? onConfirm, + final VoidCallback? onCancel, + final VoidCallback? onCustom, + final Color? cancelTextColor, + final Color? confirmTextColor, + final String? textConfirm, + final String? textCancel, + final String? textCustom, + final Widget? confirm, + final Widget? cancel, + final Widget? custom, + final Color? backgroundColor, + final bool barrierDismissible = true, + final Color? buttonColor, + final String middleText = '\n', + final TextStyle? middleTextStyle, + final double radius = 20.0, // ThemeData themeData, List? actions, // onWillPop Scope - WillPopCallback? onWillPop, + final WillPopCallback? onWillPop, // the navigator used to push the dialog - GlobalKey? navigatorKey, + final GlobalKey? navigatorKey, }) { - var leanCancel = onCancel != null || textCancel != null; - var leanConfirm = onConfirm != null || textConfirm != null; - actions ??= []; + final bool leanCancel = onCancel != null || textCancel != null; + final bool leanConfirm = onConfirm != null || textConfirm != null; + actions ??= []; if (cancel != null) { actions.add(cancel); @@ -191,8 +201,7 @@ extension ExtensionDialog on GetInterface { shape: RoundedRectangleBorder( side: BorderSide( color: buttonColor ?? theme.colorScheme.secondary, - width: 2, - style: BorderStyle.solid), + width: 2), borderRadius: BorderRadius.circular(radius)), ), onPressed: () { @@ -200,7 +209,7 @@ extension ExtensionDialog on GetInterface { back(); }, child: Text( - textCancel ?? "Cancel", + textCancel ?? 'Cancel', style: TextStyle( color: cancelTextColor ?? theme.colorScheme.secondary), ), @@ -219,7 +228,7 @@ extension ExtensionDialog on GetInterface { borderRadius: BorderRadius.circular(radius)), ), child: Text( - textConfirm ?? "Ok", + textConfirm ?? 'Ok', style: TextStyle( color: confirmTextColor ?? theme.colorScheme.background), ), @@ -229,7 +238,7 @@ extension ExtensionDialog on GetInterface { } } - Widget baseAlertDialog = AlertDialog( + final Widget baseAlertDialog = AlertDialog( titlePadding: titlePadding ?? const EdgeInsets.all(8), contentPadding: contentPadding ?? const EdgeInsets.all(8), @@ -238,9 +247,8 @@ extension ExtensionDialog on GetInterface { borderRadius: BorderRadius.all(Radius.circular(radius))), title: Text(title, textAlign: TextAlign.center, style: titleStyle), content: Column( - crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, - children: [ + children: [ content ?? Text(middleText, textAlign: TextAlign.center, style: middleTextStyle), @@ -277,44 +285,44 @@ extension ExtensionDialog on GetInterface { extension ExtensionSnackbar on GetInterface { SnackbarController rawSnackbar({ - String? title, - String? message, - Widget? titleText, - Widget? messageText, - Widget? icon, - bool instantInit = true, - bool shouldIconPulse = true, - double? maxWidth, - EdgeInsets margin = const EdgeInsets.all(0.0), - EdgeInsets padding = const EdgeInsets.all(16), - double borderRadius = 0.0, - Color? borderColor, - double borderWidth = 1.0, - Color backgroundColor = const Color(0xFF303030), - Color? leftBarIndicatorColor, - List? boxShadows, - Gradient? backgroundGradient, - Widget? mainButton, - OnTap? onTap, - Duration? duration = const Duration(seconds: 3), - bool isDismissible = true, - DismissDirection? dismissDirection, - bool showProgressIndicator = false, - AnimationController? progressIndicatorController, - Color? progressIndicatorBackgroundColor, - Animation? progressIndicatorValueColor, - SnackPosition snackPosition = SnackPosition.bottom, - SnackStyle snackStyle = SnackStyle.floating, - Curve forwardAnimationCurve = Curves.easeOutCirc, - Curve reverseAnimationCurve = Curves.easeOutCirc, - Duration animationDuration = const Duration(seconds: 1), - SnackbarStatusCallback? snackbarStatus, - double barBlur = 0.0, - double overlayBlur = 0.0, - Color? overlayColor, - Form? userInputForm, + final String? title, + final String? message, + final Widget? titleText, + final Widget? messageText, + final Widget? icon, + final bool instantInit = true, + final bool shouldIconPulse = true, + final double? maxWidth, + final EdgeInsets margin = const EdgeInsets.all(0.0), + final EdgeInsets padding = const EdgeInsets.all(16), + final double borderRadius = 0.0, + final Color? borderColor, + final double borderWidth = 1.0, + final Color backgroundColor = const Color(0xFF303030), + final Color? leftBarIndicatorColor, + final List? boxShadows, + final Gradient? backgroundGradient, + final Widget? mainButton, + final OnTap? onTap, + final Duration? duration = const Duration(seconds: 3), + final bool isDismissible = true, + final DismissDirection? dismissDirection, + final bool showProgressIndicator = false, + final AnimationController? progressIndicatorController, + final Color? progressIndicatorBackgroundColor, + final Animation? progressIndicatorValueColor, + final SnackPosition snackPosition = SnackPosition.bottom, + final SnackStyle snackStyle = SnackStyle.floating, + final Curve forwardAnimationCurve = Curves.easeOutCirc, + final Curve reverseAnimationCurve = Curves.easeOutCirc, + final Duration animationDuration = const Duration(seconds: 1), + final SnackbarStatusCallback? snackbarStatus, + final double barBlur = 0.0, + final double overlayBlur = 0.0, + final Color? overlayColor, + final Form? userInputForm, }) { - final getSnackBar = GetSnackBar( + final GetSnackBar getSnackBar = GetSnackBar( snackbarStatus: snackbarStatus, title: title, message: message, @@ -352,67 +360,67 @@ extension ExtensionSnackbar on GetInterface { userInputForm: userInputForm, ); - final controller = SnackbarController(getSnackBar); + final SnackbarController controller = SnackbarController(getSnackBar); if (instantInit) { controller.show(); } else { - ambiguate(Engine.instance)!.addPostFrameCallback((_) { + ambiguate(Engine.instance)!.addPostFrameCallback((final _) { controller.show(); }); } return controller; } - SnackbarController showSnackbar(GetSnackBar snackbar) { - final controller = SnackbarController(snackbar); + SnackbarController showSnackbar(final GetSnackBar snackbar) { + final SnackbarController controller = SnackbarController(snackbar); controller.show(); return controller; } SnackbarController snackbar( - String title, - String message, { - Color? colorText, - Duration? duration = const Duration(seconds: 3), + final String title, + final String message, { + final Color? colorText, + final Duration? duration = const Duration(seconds: 3), /// with instantInit = false you can put snackbar on initState - bool instantInit = true, - SnackPosition? snackPosition, - Widget? titleText, - Widget? messageText, - Widget? icon, - bool? shouldIconPulse, - double? maxWidth, - EdgeInsets? margin, - EdgeInsets? padding, - double? borderRadius, - Color? borderColor, - double? borderWidth, - Color? backgroundColor, - Color? leftBarIndicatorColor, - List? boxShadows, - Gradient? backgroundGradient, - TextButton? mainButton, - OnTap? onTap, - OnHover? onHover, - bool? isDismissible, - bool? showProgressIndicator, - DismissDirection? dismissDirection, - AnimationController? progressIndicatorController, - Color? progressIndicatorBackgroundColor, - Animation? progressIndicatorValueColor, - SnackStyle? snackStyle, - Curve? forwardAnimationCurve, - Curve? reverseAnimationCurve, - Duration? animationDuration, - double? barBlur, - double? overlayBlur, - SnackbarStatusCallback? snackbarStatus, - Color? overlayColor, - Form? userInputForm, + final bool instantInit = true, + final SnackPosition? snackPosition, + final Widget? titleText, + final Widget? messageText, + final Widget? icon, + final bool? shouldIconPulse, + final double? maxWidth, + final EdgeInsets? margin, + final EdgeInsets? padding, + final double? borderRadius, + final Color? borderColor, + final double? borderWidth, + final Color? backgroundColor, + final Color? leftBarIndicatorColor, + final List? boxShadows, + final Gradient? backgroundGradient, + final TextButton? mainButton, + final OnTap? onTap, + final OnHover? onHover, + final bool? isDismissible, + final bool? showProgressIndicator, + final DismissDirection? dismissDirection, + final AnimationController? progressIndicatorController, + final Color? progressIndicatorBackgroundColor, + final Animation? progressIndicatorValueColor, + final SnackStyle? snackStyle, + final Curve? forwardAnimationCurve, + final Curve? reverseAnimationCurve, + final Duration? animationDuration, + final double? barBlur, + final double? overlayBlur, + final SnackbarStatusCallback? snackbarStatus, + final Color? overlayColor, + final Form? userInputForm, }) { - final getSnackBar = GetSnackBar( + final GetSnackBar getSnackBar = GetSnackBar( snackbarStatus: snackbarStatus, titleText: titleText ?? Text( @@ -464,13 +472,13 @@ extension ExtensionSnackbar on GetInterface { overlayColor: overlayColor ?? Colors.transparent, userInputForm: userInputForm); - final controller = SnackbarController(getSnackBar); + final SnackbarController controller = SnackbarController(getSnackBar); if (instantInit) { controller.show(); } else { //routing.isSnackbar = true; - ambiguate(Engine.instance)!.addPostFrameCallback((_) { + ambiguate(Engine.instance)!.addPostFrameCallback((final _) { controller.show(); }); } @@ -503,22 +511,22 @@ extension GetNavigationExt on GetInterface { /// /// By default, GetX will prevent you from push a route that you already in, /// if you want to push anyway, set [preventDuplicates] to false - Future? to(Widget Function() page, - {bool? opaque, - Transition? transition, - Curve? curve, - Duration? duration, - String? id, - String? routeName, - bool fullscreenDialog = false, - dynamic arguments, - List bindings = const [], - bool preventDuplicates = true, - bool? popGesture, - bool showCupertinoParallax = true, - double Function(BuildContext context)? gestureWidth, - bool rebuildStack = true, - PreventDuplicateHandlingMode preventDuplicateHandlingMode = + Future? to(final Widget Function() page, + {final bool? opaque, + final Transition? transition, + final Curve? curve, + final Duration? duration, + final String? id, + final String? routeName, + final bool fullscreenDialog = false, + final dynamic arguments, + final List bindings = const [], + final bool preventDuplicates = true, + final bool? popGesture, + final bool showCupertinoParallax = true, + final double Function(BuildContext context)? gestureWidth, + final bool rebuildStack = true, + final PreventDuplicateHandlingMode preventDuplicateHandlingMode = PreventDuplicateHandlingMode.reorderRoutes}) { return searchDelegate(id).to( page, @@ -578,17 +586,17 @@ extension GetNavigationExt on GetInterface { /// Note: Always put a slash on the route ('/page1'), to avoid unexpected errors Future? toNamed( String page, { - dynamic arguments, - dynamic id, - bool preventDuplicates = true, - Map? parameters, + final dynamic arguments, + final String? id, + final bool preventDuplicates = true, + final Map? parameters, }) { // if (preventDuplicates && page == currentRoute) { // return null; // } if (parameters != null) { - final uri = Uri(path: page, queryParameters: parameters); + final Uri uri = Uri(path: page, queryParameters: parameters); page = uri.toString(); } @@ -619,16 +627,16 @@ extension GetNavigationExt on GetInterface { /// Note: Always put a slash on the route ('/page1'), to avoid unexpected errors Future? offNamed( String page, { - dynamic arguments, - String? id, - Map? parameters, + final dynamic arguments, + final String? id, + final Map? parameters, }) { // if (preventDuplicates && page == currentRoute) { // return null; // } if (parameters != null) { - final uri = Uri(path: page, queryParameters: parameters); + final Uri uri = Uri(path: page, queryParameters: parameters); page = uri.toString(); } return searchDelegate(id).offNamed( @@ -653,7 +661,8 @@ extension GetNavigationExt on GetInterface { /// or also like this: /// `Get.until((route) => !Get.isDialogOpen())`, to make sure the /// dialog is closed - void until(bool Function(GetPage) predicate, {String? id}) { + void until(final bool Function(GetPage) predicate, + {final String? id}) { // if (key.currentState.mounted) // add this if appear problems on future with route navigate // when widget don't mounted return searchDelegate(id).backUntil(predicate); @@ -679,13 +688,13 @@ extension GetNavigationExt on GetInterface { /// Note: Always put a slash on the route name ('/page1'), to avoid unexpected errors Future? offNamedUntil( String page, - bool Function(GetPage)? predicate, { - String? id, - dynamic arguments, - Map? parameters, + final bool Function(GetPage)? predicate, { + final String? id, + final dynamic arguments, + final Map? parameters, }) { if (parameters != null) { - final uri = Uri(path: page, queryParameters: parameters); + final Uri uri = Uri(path: page, queryParameters: parameters); page = uri.toString(); } @@ -711,13 +720,13 @@ extension GetNavigationExt on GetInterface { /// The route transition animation is different. Future? offAndToNamed( String page, { - dynamic arguments, - String? id, - dynamic result, - Map? parameters, + final dynamic arguments, + final String? id, + final dynamic result, + final Map? parameters, }) { if (parameters != null) { - final uri = Uri(path: page, queryParameters: parameters); + final Uri uri = Uri(path: page, queryParameters: parameters); page = uri.toString(); } return searchDelegate(id).backAndtoNamed( @@ -733,7 +742,7 @@ extension GetNavigationExt on GetInterface { /// /// [id] is for when you are using nested navigation, /// as explained in documentation - void removeRoute(String name, {String? id}) { + void removeRoute(final String name, {final String? id}) { return searchDelegate(id).removeRoute(name); } @@ -760,12 +769,12 @@ extension GetNavigationExt on GetInterface { Future? offAllNamed( String newRouteName, { // bool Function(GetPage)? predicate, - dynamic arguments, - String? id, - Map? parameters, + final dynamic arguments, + final String? id, + final Map? parameters, }) { if (parameters != null) { - final uri = Uri(path: newRouteName, queryParameters: parameters); + final Uri uri = Uri(path: newRouteName, queryParameters: parameters); newRouteName = uri.toString(); } @@ -780,11 +789,11 @@ extension GetNavigationExt on GetInterface { /// Returns true if a Snackbar, Dialog or BottomSheet is currently OPEN bool get isOverlaysOpen => - (isSnackbarOpen || isDialogOpen! || isBottomSheetOpen!); + isSnackbarOpen || isDialogOpen! || isBottomSheetOpen!; /// Returns true if there is no Snackbar, Dialog or BottomSheet open bool get isOverlaysClosed => - (!isSnackbarOpen && !isDialogOpen! && !isBottomSheetOpen!); + !isSnackbarOpen && !isDialogOpen! && !isBottomSheetOpen!; /// **Navigation.popUntil()** shortcut.

/// @@ -799,18 +808,19 @@ extension GetNavigationExt on GetInterface { /// It has the advantage of not needing context, so you can call /// from your business logic. void back({ - T? result, - bool canPop = true, + final T? result, + final bool canPop = true, int times = 1, - String? id, + final String? id, }) { if (times < 1) { times = 1; } if (times > 1) { - var count = 0; - return searchDelegate(id).backUntil((route) => count++ == times); + int count = 0; + return searchDelegate(id) + .backUntil((final GetPage route) => count++ == times); } else { if (canPop) { if (searchDelegate(id).canBack == true) { @@ -833,11 +843,11 @@ extension GetNavigationExt on GetInterface { /// It has the advantage of not needing context, so you can call /// from your business logic. void backLegacy({ - T? result, - bool closeOverlays = false, - bool canPop = true, + final T? result, + final bool closeOverlays = false, + final bool canPop = true, int times = 1, - String? id, + final String? id, }) { if (closeOverlays) { closeAllOverlays(); @@ -848,8 +858,11 @@ extension GetNavigationExt on GetInterface { } if (times > 1) { - var count = 0; - return searchDelegate(id).navigatorKey.currentState?.popUntil((route) { + int count = 0; + return searchDelegate(id) + .navigatorKey + .currentState + ?.popUntil((final Route route) { return count++ == times; }); } else { @@ -864,30 +877,30 @@ extension GetNavigationExt on GetInterface { } void closeAllDialogsAndBottomSheets( - String? id, + final String? id, ) { // It can not be divided, because dialogs and bottomsheets can not be consecutive - while ((isDialogOpen! && isBottomSheetOpen!)) { + while (isDialogOpen! && isBottomSheetOpen!) { closeOverlay(id: id); } } void closeAllDialogs({ - String? id, + final String? id, }) { - while ((isDialogOpen!)) { + while (isDialogOpen!) { closeOverlay(id: id); } } - void closeOverlay({String? id}) { + void closeOverlay({final String? id}) { searchDelegate(id).navigatorKey.currentState?.pop(); } void closeAllBottomSheets({ - String? id, + final String? id, }) { - while ((isBottomSheetOpen!)) { + while (isBottomSheetOpen!) { searchDelegate(id).navigatorKey.currentState?.pop(); } } @@ -904,16 +917,16 @@ extension GetNavigationExt on GetInterface { /// [id] is for when you are using nested navigation, /// as explained in documentation void close({ - bool closeAll = true, - bool closeSnackbar = true, - bool closeDialog = true, - bool closeBottomSheet = true, - String? id, - T? result, + final bool closeAll = true, + final bool closeSnackbar = true, + final bool closeDialog = true, + final bool closeBottomSheet = true, + final String? id, + final T? result, }) { - void handleClose(bool closeCondition, Function closeAllFunction, - Function closeSingleFunction, - [bool? isOpenCondition]) { + void handleClose(final bool closeCondition, final Function closeAllFunction, + final Function closeSingleFunction, + [final bool? isOpenCondition]) { if (closeCondition) { if (closeAll) { closeAllFunction(); @@ -955,21 +968,21 @@ extension GetNavigationExt on GetInterface { /// By default, GetX will prevent you from push a route that you already in, /// if you want to push anyway, set [preventDuplicates] to false Future? off( - Widget Function() page, { - bool? opaque, - Transition? transition, - Curve? curve, - bool? popGesture, - String? id, + final Widget Function() page, { + final bool? opaque, + final Transition? transition, + final Curve? curve, + final bool? popGesture, + final String? id, String? routeName, - dynamic arguments, - List bindings = const [], - bool fullscreenDialog = false, - bool preventDuplicates = true, - Duration? duration, - double Function(BuildContext context)? gestureWidth, + final dynamic arguments, + final List bindings = const [], + final bool fullscreenDialog = false, + final bool preventDuplicates = true, + final Duration? duration, + final double Function(BuildContext context)? gestureWidth, }) { - routeName ??= "/${page.runtimeType.toString()}"; + routeName ??= '/${page.runtimeType}'; routeName = _cleanRouteName(routeName); if (preventDuplicates && routeName == currentRoute) { return null; @@ -992,10 +1005,10 @@ extension GetNavigationExt on GetInterface { } Future offUntil( - Widget Function() page, - bool Function(GetPage) predicate, [ - Object? arguments, - String? id, + final Widget Function() page, + final bool Function(GetPage) predicate, [ + final Object? arguments, + final String? id, ]) { return searchDelegate(id).offUntil( page, @@ -1035,21 +1048,21 @@ extension GetNavigationExt on GetInterface { /// By default, GetX will prevent you from push a route that you already in, /// if you want to push anyway, set [preventDuplicates] to false Future? offAll( - Widget Function() page, { - bool Function(GetPage)? predicate, - bool? opaque, - bool? popGesture, - String? id, + final Widget Function() page, { + final bool Function(GetPage)? predicate, + final bool? opaque, + final bool? popGesture, + final String? id, String? routeName, - dynamic arguments, - List bindings = const [], - bool fullscreenDialog = false, - Transition? transition, - Curve? curve, - Duration? duration, - double Function(BuildContext context)? gestureWidth, + final dynamic arguments, + final List bindings = const [], + final bool fullscreenDialog = false, + final Transition? transition, + final Curve? curve, + final Duration? duration, + final double Function(BuildContext context)? gestureWidth, }) { - routeName ??= "/${page.runtimeType.toString()}"; + routeName ??= '/${page.runtimeType}'; routeName = _cleanRouteName(routeName); return searchDelegate(id).offAll( page, @@ -1114,7 +1127,7 @@ extension GetNavigationExt on GetInterface { // } // } - Future updateLocale(Locale l) async { + Future updateLocale(final Locale l) async { Get.locale = l; await forceAppUpdate(); } @@ -1138,23 +1151,23 @@ extension GetNavigationExt on GetInterface { void appUpdate() => rootController.update(); - void changeTheme(ThemeData theme) { + void changeTheme(final ThemeData theme) { rootController.setTheme(theme); } - void changeThemeMode(ThemeMode themeMode) { + void changeThemeMode(final ThemeMode themeMode) { rootController.setThemeMode(themeMode); } - GlobalKey? addKey(GlobalKey newKey) { + GlobalKey? addKey(final GlobalKey newKey) { return rootController.addKey(newKey); } - GetDelegate? nestedKey(String? key) { + GetDelegate? nestedKey(final String? key) { return rootController.nestedKey(key); } - GetDelegate searchDelegate(String? k) { + GetDelegate searchDelegate(final String? k) { GetDelegate key; if (k == null) { key = Get.rootController.rootDelegate; @@ -1221,7 +1234,8 @@ extension GetNavigationExt on GetInterface { /// give access to current Overlay Context BuildContext? get overlayContext { BuildContext? overlay; - key.currentState?.overlay?.context.visitChildElements((element) { + key.currentState?.overlay?.context + .visitChildElements((final Element element) { overlay = element; }); return overlay; @@ -1229,7 +1243,7 @@ extension GetNavigationExt on GetInterface { /// give access to Theme.of(context) ThemeData get theme { - var theme = ThemeData.fallback(); + ThemeData theme = ThemeData.fallback(); if (context != null) { theme = Theme.of(context!); } @@ -1275,11 +1289,11 @@ extension GetNavigationExt on GetInterface { MediaQueryData get mediaQuery => MediaQuery.of(context!); /// Check if dark mode theme is enable - bool get isDarkMode => (theme.brightness == Brightness.dark); + bool get isDarkMode => theme.brightness == Brightness.dark; /// Check if dark mode theme is enable on platform on android Q+ bool get isPlatformDarkMode => - (ui.window.platformBrightness == Brightness.dark); + ui.window.platformBrightness == Brightness.dark; /// give access to Theme.of(context).iconTheme.color Color? get iconColor => theme.iconTheme.color; @@ -1322,10 +1336,10 @@ extension GetNavigationExt on GetInterface { Routing get routing => _getxController.routing; - set parameters(Map newParameters) => + set parameters(final Map newParameters) => rootController.parameters = newParameters; - set testMode(bool isTest) => rootController.testMode = isTest; + set testMode(final bool isTest) => rootController.testMode = isTest; bool get testMode => _getxController.testMode; @@ -1338,23 +1352,24 @@ extension GetNavigationExt on GetInterface { extension OverlayExt on GetInterface { Future showOverlay({ - required Future Function() asyncFunction, - Color opacityColor = Colors.black, - Widget? loadingWidget, - double opacity = .5, + required final Future Function() asyncFunction, + final Color opacityColor = Colors.black, + final Widget? loadingWidget, + final double opacity = .5, }) async { - final navigatorState = - Navigator.of(Get.overlayContext!, rootNavigator: false); - final overlayState = navigatorState.overlay!; + final NavigatorState navigatorState = Navigator.of(Get.overlayContext!); + final OverlayState overlayState = navigatorState.overlay!; - final overlayEntryOpacity = OverlayEntry(builder: (context) { + final OverlayEntry overlayEntryOpacity = + OverlayEntry(builder: (final BuildContext context) { return Opacity( opacity: opacity, child: Container( color: opacityColor, )); }); - final overlayEntryLoader = OverlayEntry(builder: (context) { + final OverlayEntry overlayEntryLoader = + OverlayEntry(builder: (final BuildContext context) { return loadingWidget ?? const Center( child: SizedBox( diff --git a/lib/get_navigation/src/root/get_cupertino_app.dart b/lib/get_navigation/src/root/get_cupertino_app.dart index 8fb3e7477..7e7e6752f 100644 --- a/lib/get_navigation/src/root/get_cupertino_app.dart +++ b/lib/get_navigation/src/root/get_cupertino_app.dart @@ -10,64 +10,9 @@ import '../../get_navigation.dart'; import 'get_root.dart'; class GetCupertinoApp extends StatelessWidget { - final GlobalKey? navigatorKey; - final Widget? home; - final Map? routes; - final String? initialRoute; - final RouteFactory? onGenerateRoute; - final InitialRouteListFactory? onGenerateInitialRoutes; - final RouteFactory? onUnknownRoute; - final List? navigatorObservers; - final TransitionBuilder? builder; - final String title; - final GenerateAppTitle? onGenerateTitle; - final CustomTransition? customTransition; - final Color? color; - final Map>? translationsKeys; - final Translations? translations; - final TextDirection? textDirection; - final Locale? locale; - final Locale? fallbackLocale; - final Iterable>? localizationsDelegates; - final LocaleListResolutionCallback? localeListResolutionCallback; - final LocaleResolutionCallback? localeResolutionCallback; - final Iterable supportedLocales; - final bool showPerformanceOverlay; - final bool checkerboardRasterCacheImages; - final bool checkerboardOffscreenLayers; - final bool showSemanticsDebugger; - final bool debugShowCheckedModeBanner; - final Map? shortcuts; - final ThemeData? highContrastTheme; - final ThemeData? highContrastDarkTheme; - final Map>? actions; - final Function(Routing?)? routingCallback; - final Transition? defaultTransition; - final bool? opaqueRoute; - final VoidCallback? onInit; - final VoidCallback? onReady; - final VoidCallback? onDispose; - final bool? enableLog; - final LogWriterCallback? logWriterCallback; - final bool? popGesture; - final SmartManagement smartManagement; - final BindingsInterface? initialBinding; - final Duration? transitionDuration; - final bool? defaultGlobalState; - final List? getPages; - final GetPage? unknownRoute; - final RouteInformationProvider? routeInformationProvider; - final RouteInformationParser? routeInformationParser; - final RouterDelegate? routerDelegate; - final RouterConfig? routerConfig; - final BackButtonDispatcher? backButtonDispatcher; - final CupertinoThemeData? theme; - final bool useInheritedMediaQuery; - final List binds; - final ScrollBehavior? scrollBehavior; const GetCupertinoApp({ - Key? key, + super.key, this.theme, this.navigatorKey, this.home, @@ -124,11 +69,10 @@ class GetCupertinoApp extends StatelessWidget { backButtonDispatcher = null, routeInformationParser = null, routerDelegate = null, - routerConfig = null, - super(key: key); + routerConfig = null; const GetCupertinoApp.router({ - Key? key, + super.key, this.theme, this.routeInformationProvider, this.routeInformationParser, @@ -183,11 +127,65 @@ class GetCupertinoApp extends StatelessWidget { onGenerateInitialRoutes = null, onUnknownRoute = null, routes = null, - initialRoute = null, - super(key: key); + initialRoute = null; + final GlobalKey? navigatorKey; + final Widget? home; + final Map? routes; + final String? initialRoute; + final RouteFactory? onGenerateRoute; + final InitialRouteListFactory? onGenerateInitialRoutes; + final RouteFactory? onUnknownRoute; + final List? navigatorObservers; + final TransitionBuilder? builder; + final String title; + final GenerateAppTitle? onGenerateTitle; + final CustomTransition? customTransition; + final Color? color; + final Map>? translationsKeys; + final Translations? translations; + final TextDirection? textDirection; + final Locale? locale; + final Locale? fallbackLocale; + final Iterable>? localizationsDelegates; + final LocaleListResolutionCallback? localeListResolutionCallback; + final LocaleResolutionCallback? localeResolutionCallback; + final Iterable supportedLocales; + final bool showPerformanceOverlay; + final bool checkerboardRasterCacheImages; + final bool checkerboardOffscreenLayers; + final bool showSemanticsDebugger; + final bool debugShowCheckedModeBanner; + final Map? shortcuts; + final ThemeData? highContrastTheme; + final ThemeData? highContrastDarkTheme; + final Map>? actions; + final Function(Routing?)? routingCallback; + final Transition? defaultTransition; + final bool? opaqueRoute; + final VoidCallback? onInit; + final VoidCallback? onReady; + final VoidCallback? onDispose; + final bool? enableLog; + final LogWriterCallback? logWriterCallback; + final bool? popGesture; + final SmartManagement smartManagement; + final BindingsInterface? initialBinding; + final Duration? transitionDuration; + final bool? defaultGlobalState; + final List? getPages; + final GetPage? unknownRoute; + final RouteInformationProvider? routeInformationProvider; + final RouteInformationParser? routeInformationParser; + final RouterDelegate? routerDelegate; + final RouterConfig? routerConfig; + final BackButtonDispatcher? backButtonDispatcher; + final CupertinoThemeData? theme; + final bool useInheritedMediaQuery; + final List binds; + final ScrollBehavior? scrollBehavior; @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return GetRoot( config: ConfigData( backButtonDispatcher: backButtonDispatcher, @@ -218,7 +216,7 @@ class GetCupertinoApp extends StatelessWidget { translationsKeys: translationsKeys, unknownRoute: unknownRoute, ), - child: Builder(builder: (context) { + child: Builder(builder: (final context) { final controller = GetRoot.of(context); return CupertinoApp.router( routerDelegate: controller.config.routerDelegate, @@ -227,7 +225,7 @@ class GetCupertinoApp extends StatelessWidget { routeInformationProvider: routeInformationProvider, routerConfig: routerConfig, key: controller.config.unikey, - builder: (context, child) => Directionality( + builder: (final context, final child) => Directionality( textDirection: textDirection ?? (rtlLanguages.contains(Get.locale?.languageCode) ? TextDirection.rtl diff --git a/lib/get_navigation/src/root/get_material_app.dart b/lib/get_navigation/src/root/get_material_app.dart index 00276f2f7..a2fbabc26 100644 --- a/lib/get_navigation/src/root/get_material_app.dart +++ b/lib/get_navigation/src/root/get_material_app.dart @@ -1,6 +1,6 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:get/instance_manager.dart'; +import '../../../instance_manager.dart'; import '../../../get_state_manager/get_state_manager.dart'; import '../../../get_utils/get_utils.dart'; @@ -8,67 +8,9 @@ import '../../get_navigation.dart'; import 'get_root.dart'; class GetMaterialApp extends StatelessWidget { - final GlobalKey? navigatorKey; - final GlobalKey? scaffoldMessengerKey; - final Widget? home; - final Map? routes; - final String? initialRoute; - final RouteFactory? onGenerateRoute; - final InitialRouteListFactory? onGenerateInitialRoutes; - final RouteFactory? onUnknownRoute; - final List? navigatorObservers; - final TransitionBuilder? builder; - final String title; - final GenerateAppTitle? onGenerateTitle; - final ThemeData? theme; - final ThemeData? darkTheme; - final ThemeMode themeMode; - final CustomTransition? customTransition; - final Color? color; - final Map>? translationsKeys; - final Translations? translations; - final TextDirection? textDirection; - final Locale? locale; - final Locale? fallbackLocale; - final Iterable>? localizationsDelegates; - final LocaleListResolutionCallback? localeListResolutionCallback; - final LocaleResolutionCallback? localeResolutionCallback; - final Iterable supportedLocales; - final bool showPerformanceOverlay; - final bool checkerboardRasterCacheImages; - final bool checkerboardOffscreenLayers; - final bool showSemanticsDebugger; - final bool debugShowCheckedModeBanner; - final Map? shortcuts; - final ScrollBehavior? scrollBehavior; - final ThemeData? highContrastTheme; - final ThemeData? highContrastDarkTheme; - final Map>? actions; - final bool debugShowMaterialGrid; - final ValueChanged? routingCallback; - final Transition? defaultTransition; - final bool? opaqueRoute; - final VoidCallback? onInit; - final VoidCallback? onReady; - final VoidCallback? onDispose; - final bool? enableLog; - final LogWriterCallback? logWriterCallback; - final bool? popGesture; - final SmartManagement smartManagement; - final List binds; - final Duration? transitionDuration; - final bool? defaultGlobalState; - final List? getPages; - final GetPage? unknownRoute; - final RouteInformationProvider? routeInformationProvider; - final RouteInformationParser? routeInformationParser; - final RouterDelegate? routerDelegate; - final RouterConfig? routerConfig; - final BackButtonDispatcher? backButtonDispatcher; - final bool useInheritedMediaQuery; const GetMaterialApp({ - Key? key, + super.key, this.navigatorKey, this.scaffoldMessengerKey, this.home, @@ -128,11 +70,10 @@ class GetMaterialApp extends StatelessWidget { backButtonDispatcher = null, routeInformationParser = null, routerDelegate = null, - routerConfig = null, - super(key: key); + routerConfig = null; const GetMaterialApp.router({ - Key? key, + super.key, this.routeInformationProvider, this.scaffoldMessengerKey, this.routeInformationParser, @@ -190,11 +131,68 @@ class GetMaterialApp extends StatelessWidget { onGenerateInitialRoutes = null, onUnknownRoute = null, routes = null, - initialRoute = null, - super(key: key); + initialRoute = null; + final GlobalKey? navigatorKey; + final GlobalKey? scaffoldMessengerKey; + final Widget? home; + final Map? routes; + final String? initialRoute; + final RouteFactory? onGenerateRoute; + final InitialRouteListFactory? onGenerateInitialRoutes; + final RouteFactory? onUnknownRoute; + final List? navigatorObservers; + final TransitionBuilder? builder; + final String title; + final GenerateAppTitle? onGenerateTitle; + final ThemeData? theme; + final ThemeData? darkTheme; + final ThemeMode themeMode; + final CustomTransition? customTransition; + final Color? color; + final Map>? translationsKeys; + final Translations? translations; + final TextDirection? textDirection; + final Locale? locale; + final Locale? fallbackLocale; + final Iterable>? localizationsDelegates; + final LocaleListResolutionCallback? localeListResolutionCallback; + final LocaleResolutionCallback? localeResolutionCallback; + final Iterable supportedLocales; + final bool showPerformanceOverlay; + final bool checkerboardRasterCacheImages; + final bool checkerboardOffscreenLayers; + final bool showSemanticsDebugger; + final bool debugShowCheckedModeBanner; + final Map? shortcuts; + final ScrollBehavior? scrollBehavior; + final ThemeData? highContrastTheme; + final ThemeData? highContrastDarkTheme; + final Map>? actions; + final bool debugShowMaterialGrid; + final ValueChanged? routingCallback; + final Transition? defaultTransition; + final bool? opaqueRoute; + final VoidCallback? onInit; + final VoidCallback? onReady; + final VoidCallback? onDispose; + final bool? enableLog; + final LogWriterCallback? logWriterCallback; + final bool? popGesture; + final SmartManagement smartManagement; + final List binds; + final Duration? transitionDuration; + final bool? defaultGlobalState; + final List? getPages; + final GetPage? unknownRoute; + final RouteInformationProvider? routeInformationProvider; + final RouteInformationParser? routeInformationParser; + final RouterDelegate? routerDelegate; + final RouterConfig? routerConfig; + final BackButtonDispatcher? backButtonDispatcher; + final bool useInheritedMediaQuery; @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return GetRoot( config: ConfigData( backButtonDispatcher: backButtonDispatcher, @@ -241,7 +239,7 @@ class GetMaterialApp extends StatelessWidget { // ), // ...binds, // ], - child: Builder(builder: (context) { + child: Builder(builder: (final context) { final controller = GetRoot.of(context); return MaterialApp.router( routerDelegate: controller.config.routerDelegate, @@ -250,7 +248,7 @@ class GetMaterialApp extends StatelessWidget { routeInformationProvider: routeInformationProvider, routerConfig: routerConfig, key: controller.config.unikey, - builder: (context, child) => Directionality( + builder: (final context, final child) => Directionality( textDirection: textDirection ?? (rtlLanguages.contains(Get.locale?.languageCode) ? TextDirection.rtl diff --git a/lib/get_navigation/src/root/get_root.dart b/lib/get_navigation/src/root/get_root.dart index c8c7489a8..7db86032c 100644 --- a/lib/get_navigation/src/root/get_root.dart +++ b/lib/get_navigation/src/root/get_root.dart @@ -5,46 +5,6 @@ import '../../../get.dart'; import '../router_report.dart'; class ConfigData { - final ValueChanged? routingCallback; - final Transition? defaultTransition; - final VoidCallback? onInit; - final VoidCallback? onReady; - final VoidCallback? onDispose; - final bool? enableLog; - final LogWriterCallback? logWriterCallback; - final SmartManagement smartManagement; - final List binds; - final Duration? transitionDuration; - final bool? defaultGlobalState; - final List? getPages; - final GetPage? unknownRoute; - final RouteInformationProvider? routeInformationProvider; - final RouteInformationParser? routeInformationParser; - final RouterDelegate? routerDelegate; - final BackButtonDispatcher? backButtonDispatcher; - final List? navigatorObservers; - final GlobalKey? navigatorKey; - final GlobalKey? scaffoldMessengerKey; - final Map>? translationsKeys; - final Translations? translations; - final Locale? locale; - final Locale? fallbackLocale; - final String? initialRoute; - final CustomTransition? customTransition; - final Widget? home; - final bool testMode; - final Key? unikey; - final ThemeData? theme; - final ThemeData? darkTheme; - final ThemeMode? themeMode; - final bool defaultPopGesture; - final bool defaultOpaqueRoute; - final Duration defaultTransitionDuration; - final Curve defaultTransitionCurve; - final Curve defaultDialogTransitionCurve; - final Duration defaultDialogTransitionDuration; - final Routing routing; - final Map parameters; ConfigData({ required this.routingCallback, @@ -85,52 +45,92 @@ class ConfigData { this.defaultDialogTransitionCurve = Curves.easeOutQuad, this.defaultDialogTransitionDuration = const Duration(milliseconds: 300), this.parameters = const {}, - Routing? routing, - bool? defaultPopGesture, + final Routing? routing, + final bool? defaultPopGesture, }) : defaultPopGesture = defaultPopGesture ?? GetPlatform.isIOS, routing = routing ?? Routing(); + final ValueChanged? routingCallback; + final Transition? defaultTransition; + final VoidCallback? onInit; + final VoidCallback? onReady; + final VoidCallback? onDispose; + final bool? enableLog; + final LogWriterCallback? logWriterCallback; + final SmartManagement smartManagement; + final List binds; + final Duration? transitionDuration; + final bool? defaultGlobalState; + final List? getPages; + final GetPage? unknownRoute; + final RouteInformationProvider? routeInformationProvider; + final RouteInformationParser? routeInformationParser; + final RouterDelegate? routerDelegate; + final BackButtonDispatcher? backButtonDispatcher; + final List? navigatorObservers; + final GlobalKey? navigatorKey; + final GlobalKey? scaffoldMessengerKey; + final Map>? translationsKeys; + final Translations? translations; + final Locale? locale; + final Locale? fallbackLocale; + final String? initialRoute; + final CustomTransition? customTransition; + final Widget? home; + final bool testMode; + final Key? unikey; + final ThemeData? theme; + final ThemeData? darkTheme; + final ThemeMode? themeMode; + final bool defaultPopGesture; + final bool defaultOpaqueRoute; + final Duration defaultTransitionDuration; + final Curve defaultTransitionCurve; + final Curve defaultDialogTransitionCurve; + final Duration defaultDialogTransitionDuration; + final Routing routing; + final Map parameters; ConfigData copyWith({ - ValueChanged? routingCallback, - Transition? defaultTransition, - VoidCallback? onInit, - VoidCallback? onReady, - VoidCallback? onDispose, - bool? enableLog, - LogWriterCallback? logWriterCallback, - SmartManagement? smartManagement, - List? binds, - Duration? transitionDuration, - bool? defaultGlobalState, - List? getPages, - GetPage? unknownRoute, - RouteInformationProvider? routeInformationProvider, - RouteInformationParser? routeInformationParser, - RouterDelegate? routerDelegate, - BackButtonDispatcher? backButtonDispatcher, - List? navigatorObservers, - GlobalKey? navigatorKey, - GlobalKey? scaffoldMessengerKey, - Map>? translationsKeys, - Translations? translations, - Locale? locale, - Locale? fallbackLocale, - String? initialRoute, - CustomTransition? customTransition, - Widget? home, - bool? testMode, - Key? unikey, - ThemeData? theme, - ThemeData? darkTheme, - ThemeMode? themeMode, - bool? defaultPopGesture, - bool? defaultOpaqueRoute, - Duration? defaultTransitionDuration, - Curve? defaultTransitionCurve, - Curve? defaultDialogTransitionCurve, - Duration? defaultDialogTransitionDuration, - Routing? routing, - Map? parameters, + final ValueChanged? routingCallback, + final Transition? defaultTransition, + final VoidCallback? onInit, + final VoidCallback? onReady, + final VoidCallback? onDispose, + final bool? enableLog, + final LogWriterCallback? logWriterCallback, + final SmartManagement? smartManagement, + final List? binds, + final Duration? transitionDuration, + final bool? defaultGlobalState, + final List? getPages, + final GetPage? unknownRoute, + final RouteInformationProvider? routeInformationProvider, + final RouteInformationParser? routeInformationParser, + final RouterDelegate? routerDelegate, + final BackButtonDispatcher? backButtonDispatcher, + final List? navigatorObservers, + final GlobalKey? navigatorKey, + final GlobalKey? scaffoldMessengerKey, + final Map>? translationsKeys, + final Translations? translations, + final Locale? locale, + final Locale? fallbackLocale, + final String? initialRoute, + final CustomTransition? customTransition, + final Widget? home, + final bool? testMode, + final Key? unikey, + final ThemeData? theme, + final ThemeData? darkTheme, + final ThemeMode? themeMode, + final bool? defaultPopGesture, + final bool? defaultOpaqueRoute, + final Duration? defaultTransitionDuration, + final Curve? defaultTransitionCurve, + final Curve? defaultDialogTransitionCurve, + final Duration? defaultDialogTransitionDuration, + final Routing? routing, + final Map? parameters, }) { return ConfigData( routingCallback: routingCallback ?? this.routingCallback, @@ -183,7 +183,7 @@ class ConfigData { } @override - bool operator ==(Object other) { + bool operator ==(final Object other) { if (identical(this, other)) return true; return other is ConfigData && @@ -277,16 +277,14 @@ class ConfigData { class GetRoot extends StatefulWidget { const GetRoot({ - Key? key, - required this.config, - required this.child, - }) : super(key: key); + required this.config, required this.child, super.key, + }); final ConfigData config; final Widget child; @override State createState() => GetRootState(); - static GetRootState of(BuildContext context) { + static GetRootState of(final BuildContext context) { // Handles the case where the input context is a navigator element. GetRootState? root; if (context is StatefulElement && context.state is GetRootState) { @@ -342,7 +340,7 @@ class GetRootState extends State with WidgetsBindingObserver { Get.clearTranslations(); RouterReportManager.instance.clearRouteKeys(); RouterReportManager.dispose(); - Get.resetInstance(clearRouteBindings: true); + Get.resetInstance(); _controller = null; ambiguate(Engine.instance)!.removeObserver(this); } @@ -363,7 +361,7 @@ class GetRootState extends State with WidgetsBindingObserver { pages: config.getPages ?? [ GetPage( - name: cleanRouteName("/${config.home.runtimeType}"), + name: cleanRouteName('/${config.home.runtimeType}'), page: () => config.home!, ), ], @@ -386,7 +384,7 @@ class GetRootState extends State with WidgetsBindingObserver { GetInformationParser.createInformationParser( initialRoute: config.initialRoute ?? config.getPages?.first.name ?? - cleanRouteName("/${config.home.runtimeType}"), + cleanRouteName('/${config.home.runtimeType}'), ); config = @@ -423,12 +421,12 @@ class GetRootState extends State with WidgetsBindingObserver { Future(() => onReady()); } - set parameters(Map newParameters) { + set parameters(final Map newParameters) { // rootController.parameters = newParameters; config = config.copyWith(parameters: newParameters); } - set testMode(bool isTest) { + set testMode(final bool isTest) { config = config.copyWith(testMode: isTest); // _getxController.testMode = isTest; } @@ -456,7 +454,7 @@ class GetRootState extends State with WidgetsBindingObserver { } @override - void didChangeLocales(List? locales) { + void didChangeLocales(final List? locales) { Get.asap(() { final locale = Get.deviceLocale; if (locale != null) { @@ -465,7 +463,7 @@ class GetRootState extends State with WidgetsBindingObserver { }); } - void setTheme(ThemeData value) { + void setTheme(final ThemeData value) { if (config.darkTheme == null) { config = config.copyWith(theme: value); } else { @@ -478,7 +476,7 @@ class GetRootState extends State with WidgetsBindingObserver { update(); } - void setThemeMode(ThemeMode value) { + void setThemeMode(final ThemeMode value) { config = config.copyWith(themeMode: value); update(); } @@ -489,7 +487,7 @@ class GetRootState extends State with WidgetsBindingObserver { } void update() { - context.visitAncestorElements((element) { + context.visitAncestorElements((final element) { element.markNeedsBuild(); return false; }); @@ -502,14 +500,14 @@ class GetRootState extends State with WidgetsBindingObserver { RouteInformationParser get informationParser => config.routeInformationParser!; - GlobalKey? addKey(GlobalKey newKey) { + GlobalKey? addKey(final GlobalKey newKey) { rootDelegate.navigatorKey = newKey; return key; } Map keys = {}; - GetDelegate? nestedKey(String? key) { + GetDelegate? nestedKey(final String? key) { if (key == null) { return rootDelegate; } @@ -525,7 +523,7 @@ class GetRootState extends State with WidgetsBindingObserver { } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return widget.child; } diff --git a/lib/get_navigation/src/router_report.dart b/lib/get_navigation/src/router_report.dart index e9c1a9848..86ad2613a 100644 --- a/lib/get_navigation/src/router_report.dart +++ b/lib/get_navigation/src/router_report.dart @@ -3,6 +3,8 @@ import 'dart:collection'; import '../../get.dart'; class RouterReportManager { + + RouterReportManager._(); /// Holds a reference to `Get.reference` when the Instance was /// created to manage the memory. final Map> _routesKey = {}; @@ -15,8 +17,6 @@ class RouterReportManager { static RouterReportManager? _instance; - RouterReportManager._(); - static RouterReportManager get instance => _instance ??= RouterReportManager._(); @@ -31,13 +31,13 @@ class RouterReportManager { T? _current; // ignore: use_setters_to_change_properties - void reportCurrentRoute(T newRoute) { + void reportCurrentRoute(final T newRoute) { _current = newRoute; } /// Links a Class instance [S] (or [tag]) to the current route. /// Requires usage of `GetMaterialApp`. - void reportDependencyLinkedToRoute(String dependencyKey) { + void reportDependencyLinkedToRoute(final String dependencyKey) { if (_current == null) return; if (_routesKey.containsKey(_current)) { _routesKey[_current!]!.add(dependencyKey); @@ -51,13 +51,13 @@ class RouterReportManager { _routesByCreate.clear(); } - void appendRouteByCreate(GetLifeCycleMixin i) { + void appendRouteByCreate(final GetLifeCycleMixin i) { _routesByCreate[_current] ??= HashSet(); // _routesByCreate[Get.reference]!.add(i.onDelete as Function); _routesByCreate[_current]!.add(i.onDelete); } - void reportRouteDispose(T disposed) { + void reportRouteDispose(final T disposed) { if (Get.smartManagement != SmartManagement.onlyBuilder) { // ambiguate(Engine.instance)!.addPostFrameCallback((_) { // Future.microtask(() { @@ -66,7 +66,7 @@ class RouterReportManager { } } - void reportRouteWillDispose(T disposed) { + void reportRouteWillDispose(final T disposed) { final keysToRemove = []; _routesKey[disposed]?.forEach(keysToRemove.add); @@ -95,7 +95,7 @@ class RouterReportManager { /// using `Get.smartManagement` as [SmartManagement.full] or /// [SmartManagement.keepFactory] /// Meant for internal usage of `GetPageRoute` and `GetDialogRoute` - void _removeDependencyByRoute(T routeName) { + void _removeDependencyByRoute(final T routeName) { final keysToRemove = []; _routesKey[routeName]?.forEach(keysToRemove.add); diff --git a/lib/get_navigation/src/routes/circular_reveal_clipper.dart b/lib/get_navigation/src/routes/circular_reveal_clipper.dart index d53be2526..479c42e6b 100644 --- a/lib/get_navigation/src/routes/circular_reveal_clipper.dart +++ b/lib/get_navigation/src/routes/circular_reveal_clipper.dart @@ -4,11 +4,6 @@ import 'dart:ui' show lerpDouble; import 'package:flutter/material.dart'; class CircularRevealClipper extends CustomClipper { - final double fraction; - final Alignment? centerAlignment; - final Offset? centerOffset; - final double? minRadius; - final double? maxRadius; CircularRevealClipper({ required this.fraction, @@ -17,9 +12,14 @@ class CircularRevealClipper extends CustomClipper { this.minRadius, this.maxRadius, }); + final double fraction; + final Alignment? centerAlignment; + final Offset? centerOffset; + final double? minRadius; + final double? maxRadius; @override - Path getClip(Size size) { + Path getClip(final Size size) { final center = centerAlignment?.alongSize(size) ?? centerOffset ?? Offset(size.width / 2, size.height / 2); @@ -36,9 +36,9 @@ class CircularRevealClipper extends CustomClipper { } @override - bool shouldReclip(CustomClipper oldClipper) => true; + bool shouldReclip(final CustomClipper oldClipper) => true; - static double calcMaxRadius(Size size, Offset center) { + static double calcMaxRadius(final Size size, final Offset center) { final w = max(center.dx, size.width - center.dx); final h = max(center.dy, size.height - center.dy); return sqrt(w * w + h * h); diff --git a/lib/get_navigation/src/routes/custom_transition.dart b/lib/get_navigation/src/routes/custom_transition.dart index c2fd22d71..aa40ea54e 100644 --- a/lib/get_navigation/src/routes/custom_transition.dart +++ b/lib/get_navigation/src/routes/custom_transition.dart @@ -3,11 +3,11 @@ import 'package:flutter/widgets.dart'; // ignore: one_member_abstracts abstract class CustomTransition { Widget buildTransition( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child, + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child, ); } diff --git a/lib/get_navigation/src/routes/default_route.dart b/lib/get_navigation/src/routes/default_route.dart index a4470cc8e..baa37f05a 100644 --- a/lib/get_navigation/src/routes/default_route.dart +++ b/lib/get_navigation/src/routes/default_route.dart @@ -39,7 +39,7 @@ class GetPageRoute extends PageRoute /// The [builder], [maintainState], and [fullscreenDialog] arguments must not /// be null. GetPageRoute({ - RouteSettings? settings, + super.settings, this.transitionDuration = const Duration(milliseconds: 300), this.reverseTransitionDuration = const Duration(milliseconds: 300), this.opaque = true, @@ -52,8 +52,8 @@ class GetPageRoute extends PageRoute this.customTransition, this.barrierDismissible = false, this.barrierColor, - BindingsInterface? binding, - List bindings = const [], + final BindingsInterface? binding, + final List bindings = const [], this.binds, this.routeName, this.page, @@ -61,13 +61,9 @@ class GetPageRoute extends PageRoute this.showCupertinoParallax = true, this.barrierLabel, this.maintainState = true, - bool fullscreenDialog = false, + super.fullscreenDialog, this.middlewares, - }) : bindings = (binding == null) ? bindings : [...bindings, binding], - super( - settings: settings, - fullscreenDialog: fullscreenDialog, - ); + }) : bindings = (binding == null) ? bindings : [...bindings, binding]; @override final Duration transitionDuration; @@ -149,7 +145,7 @@ class GetPageRoute extends PageRoute } @override - Widget buildContent(BuildContext context) { + Widget buildContent(final BuildContext context) { return _getChild(); } diff --git a/lib/get_navigation/src/routes/default_transitions.dart b/lib/get_navigation/src/routes/default_transitions.dart index e6cad4a8c..bfc20f096 100644 --- a/lib/get_navigation/src/routes/default_transitions.dart +++ b/lib/get_navigation/src/routes/default_transitions.dart @@ -5,12 +5,12 @@ import 'circular_reveal_clipper.dart'; class LeftToRightFadeTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return SlideTransition( position: Tween( begin: const Offset(-1.0, 0.0), @@ -31,12 +31,12 @@ class LeftToRightFadeTransition { class RightToLeftFadeTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return SlideTransition( position: Tween( begin: const Offset(1.0, 0.0), @@ -57,36 +57,36 @@ class RightToLeftFadeTransition { class NoTransition { Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve curve, + final Alignment alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return child; } } class FadeInTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return FadeTransition(opacity: animation, child: child); } } class SlideDownTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return SlideTransition( position: Tween( begin: const Offset(0.0, 1.0), @@ -99,12 +99,12 @@ class SlideDownTransition { class SlideLeftTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return SlideTransition( position: Tween( begin: const Offset(-1.0, 0.0), @@ -117,12 +117,12 @@ class SlideLeftTransition { class SlideRightTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return SlideTransition( position: Tween( begin: const Offset(1.0, 0.0), @@ -135,12 +135,12 @@ class SlideRightTransition { class SlideTopTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return SlideTransition( position: Tween( begin: const Offset(0.0, -1.0), @@ -153,12 +153,12 @@ class SlideTopTransition { class ZoomInTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return ScaleTransition( scale: animation, child: child, @@ -168,14 +168,13 @@ class ZoomInTransition { class SizeTransitions { Widget buildTransitions( - BuildContext context, - Curve curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return Align( - alignment: Alignment.center, child: SizeTransition( sizeFactor: CurvedAnimation( parent: animation, @@ -189,12 +188,12 @@ class SizeTransitions { class CircularRevealTransition { Widget buildTransitions( - BuildContext context, - Curve? curve, - Alignment? alignment, - Animation animation, - Animation secondaryAnimation, - Widget child) { + final BuildContext context, + final Curve? curve, + final Alignment? alignment, + final Animation animation, + final Animation secondaryAnimation, + final Widget child) { return ClipPath( clipper: CircularRevealClipper( fraction: animation.value, diff --git a/lib/get_navigation/src/routes/get_information_parser.dart b/lib/get_navigation/src/routes/get_information_parser.dart index 8679b53ad..611be6adc 100644 --- a/lib/get_navigation/src/routes/get_information_parser.dart +++ b/lib/get_navigation/src/routes/get_information_parser.dart @@ -4,30 +4,30 @@ import 'package:flutter/widgets.dart'; import '../../../get.dart'; class GetInformationParser extends RouteInformationParser { - factory GetInformationParser.createInformationParser( - {String initialRoute = '/'}) { - return GetInformationParser(initialRoute: initialRoute); - } - - final String initialRoute; GetInformationParser({ required this.initialRoute, }) { Get.log('GetInformationParser is created !'); } + factory GetInformationParser.createInformationParser( + {final String initialRoute = '/'}) { + return GetInformationParser(initialRoute: initialRoute); + } + + final String initialRoute; @override SynchronousFuture parseRouteInformation( - RouteInformation routeInformation, + final RouteInformation routeInformation, ) { final uri = routeInformation.uri; var location = uri.toString(); if (location == '/') { //check if there is a corresponding page //if not, relocate to initialRoute - if (!(Get.rootController.rootDelegate) + if (!Get.rootController.rootDelegate .registeredRoutes - .any((element) => element.name == '/')) { + .any((final element) => element.name == '/')) { location = initialRoute; } } else if (location.isEmpty) { @@ -40,10 +40,9 @@ class GetInformationParser extends RouteInformationParser { } @override - RouteInformation restoreRouteInformation(RouteDecoder configuration) { + RouteInformation restoreRouteInformation(final RouteDecoder configuration) { return RouteInformation( uri: Uri.tryParse(configuration.pageSettings?.name ?? ''), - state: null, ); } } diff --git a/lib/get_navigation/src/routes/get_navigation_interface.dart b/lib/get_navigation/src/routes/get_navigation_interface.dart index 3e2290801..eb1c0513b 100644 --- a/lib/get_navigation/src/routes/get_navigation_interface.dart +++ b/lib/get_navigation/src/routes/get_navigation_interface.dart @@ -49,111 +49,111 @@ enum PreventDuplicateHandlingMode { mixin IGetNavigation { Future to( - Widget Function() page, { - bool? opaque, - Transition? transition, - Curve? curve, - Duration? duration, - String? id, - String? routeName, - bool fullscreenDialog = false, - dynamic arguments, - List bindings = const [], - bool preventDuplicates = true, - bool? popGesture, - bool showCupertinoParallax = true, - double Function(BuildContext context)? gestureWidth, + final Widget Function() page, { + final bool? opaque, + final Transition? transition, + final Curve? curve, + final Duration? duration, + final String? id, + final String? routeName, + final bool fullscreenDialog = false, + final dynamic arguments, + final List bindings = const [], + final bool preventDuplicates = true, + final bool? popGesture, + final bool showCupertinoParallax = true, + final double Function(BuildContext context)? gestureWidth, }); Future popModeUntil( - String fullRoute, { - PopMode popMode = PopMode.history, + final String fullRoute, { + final PopMode popMode = PopMode.history, }); Future off( - Widget Function() page, { - bool? opaque, - Transition? transition, - Curve? curve, - Duration? duration, - String? id, - String? routeName, - bool fullscreenDialog = false, - dynamic arguments, - List bindings = const [], - bool preventDuplicates = true, - bool? popGesture, - bool showCupertinoParallax = true, - double Function(BuildContext context)? gestureWidth, + final Widget Function() page, { + final bool? opaque, + final Transition? transition, + final Curve? curve, + final Duration? duration, + final String? id, + final String? routeName, + final bool fullscreenDialog = false, + final dynamic arguments, + final List bindings = const [], + final bool preventDuplicates = true, + final bool? popGesture, + final bool showCupertinoParallax = true, + final double Function(BuildContext context)? gestureWidth, }); Future? offAll( - Widget Function() page, { - bool Function(GetPage route)? predicate, - bool opaque = true, - bool? popGesture, - String? id, - String? routeName, - dynamic arguments, - List bindings = const [], - bool fullscreenDialog = false, - Transition? transition, - Curve? curve, - Duration? duration, - bool showCupertinoParallax = true, - double Function(BuildContext context)? gestureWidth, + final Widget Function() page, { + final bool Function(GetPage route)? predicate, + final bool opaque = true, + final bool? popGesture, + final String? id, + final String? routeName, + final dynamic arguments, + final List bindings = const [], + final bool fullscreenDialog = false, + final Transition? transition, + final Curve? curve, + final Duration? duration, + final bool showCupertinoParallax = true, + final double Function(BuildContext context)? gestureWidth, }); Future toNamed( - String page, { - dynamic arguments, - String? id, - bool preventDuplicates = true, - Map? parameters, + final String page, { + final dynamic arguments, + final String? id, + final bool preventDuplicates = true, + final Map? parameters, }); Future offNamed( - String page, { - dynamic arguments, - String? id, - Map? parameters, + final String page, { + final dynamic arguments, + final String? id, + final Map? parameters, }); Future? offAllNamed( - String newRouteName, { + final String newRouteName, { // bool Function(GetPage route)? predicate, - dynamic arguments, - String? id, - Map? parameters, + final dynamic arguments, + final String? id, + final Map? parameters, }); Future? offNamedUntil( - String page, { - bool Function(GetPage route)? predicate, - dynamic arguments, - String? id, - Map? parameters, + final String page, { + final bool Function(GetPage route)? predicate, + final dynamic arguments, + final String? id, + final Map? parameters, }); Future toNamedAndOffUntil( - String page, - bool Function(GetPage) predicate, [ - Object? data, + final String page, + final bool Function(GetPage) predicate, [ + final Object? data, ]); Future offUntil( - Widget Function() page, - bool Function(GetPage) predicate, [ - Object? arguments, + final Widget Function() page, + final bool Function(GetPage) predicate, [ + final Object? arguments, ]); - void removeRoute(String name); + void removeRoute(final String name); - void back([T? result]); + void back([final T? result]); - Future backAndtoNamed(String page, {T? result, Object? arguments}); + Future backAndtoNamed(final String page, {final T? result, final Object? arguments}); - void backUntil(bool Function(GetPage) predicate); + void backUntil(final bool Function(GetPage) predicate); - void goToUnknownPage([bool clearPages = true]); + void goToUnknownPage([final bool clearPages = true]); } diff --git a/lib/get_navigation/src/routes/get_navigator.dart b/lib/get_navigation/src/routes/get_navigator.dart index a907c4e69..cbeb8ba4a 100644 --- a/lib/get_navigation/src/routes/get_navigator.dart +++ b/lib/get_navigation/src/routes/get_navigator.dart @@ -3,77 +3,65 @@ import 'package:flutter/widgets.dart'; import '../../../get.dart'; class GetNavigator extends Navigator { - GetNavigator.onGenerateRoute({ - GlobalKey? key, - bool Function(Route, dynamic)? onPopPage, - required List pages, - List? observers, - bool reportsRouteUpdateToEngine = false, - TransitionDelegate? transitionDelegate, - String? initialRoute, - String? restorationScopeId, + + GetNavigator({ + required List super.pages, super.key, + final bool Function(Route, dynamic)? onPopPage, + final List? observers, + super.reportsRouteUpdateToEngine, + final TransitionDelegate? transitionDelegate, + super.initialRoute, + super.restorationScopeId, }) : super( //keys should be optional - key: key, - initialRoute: initialRoute, onPopPage: onPopPage ?? - (route, result) { + (final route, final result) { final didPop = route.didPop(result); if (!didPop) { return false; } return true; }, - onGenerateRoute: (settings) { - final selectedPageList = - pages.where((element) => element.name == settings.name); - if (selectedPageList.isNotEmpty) { - final selectedPage = selectedPageList.first; - return GetPageRoute( - page: selectedPage.page, - settings: settings, - ); - } - return null; - }, - reportsRouteUpdateToEngine: reportsRouteUpdateToEngine, - restorationScopeId: restorationScopeId, - pages: pages, observers: [ - // GetObserver(), + // GetObserver(null, Get.routing), + HeroController(), ...?observers, ], transitionDelegate: transitionDelegate ?? const DefaultTransitionDelegate(), ); - - GetNavigator({ - Key? key, - bool Function(Route, dynamic)? onPopPage, - required List pages, - List? observers, - bool reportsRouteUpdateToEngine = false, - TransitionDelegate? transitionDelegate, - String? initialRoute, - String? restorationScopeId, + GetNavigator.onGenerateRoute({ + required List super.pages, GlobalKey? super.key, + final bool Function(Route, dynamic)? onPopPage, + final List? observers, + super.reportsRouteUpdateToEngine, + final TransitionDelegate? transitionDelegate, + super.initialRoute, + super.restorationScopeId, }) : super( //keys should be optional - key: key, - initialRoute: initialRoute, onPopPage: onPopPage ?? - (route, result) { + (final route, final result) { final didPop = route.didPop(result); if (!didPop) { return false; } return true; }, - reportsRouteUpdateToEngine: reportsRouteUpdateToEngine, - restorationScopeId: restorationScopeId, - pages: pages, + onGenerateRoute: (final settings) { + final selectedPageList = + pages.where((final element) => element.name == settings.name); + if (selectedPageList.isNotEmpty) { + final selectedPage = selectedPageList.first; + return GetPageRoute( + page: selectedPage.page, + settings: settings, + ); + } + return null; + }, observers: [ - // GetObserver(null, Get.routing), - HeroController(), + // GetObserver(), ...?observers, ], transitionDelegate: diff --git a/lib/get_navigation/src/routes/get_route.dart b/lib/get_navigation/src/routes/get_route.dart index 334c50088..f1920eab6 100644 --- a/lib/get_navigation/src/routes/get_route.dart +++ b/lib/get_navigation/src/routes/get_route.dart @@ -11,6 +11,47 @@ import '../../../get_state_manager/src/simple/get_state.dart'; import '../../get_navigation.dart'; class GetPage extends Page { + + GetPage({ + required this.name, + required this.page, + this.title, + this.participatesInRootNavigator, + this.gestureWidth, + // RouteSettings settings, + this.maintainState = true, + this.curve = Curves.linear, + this.alignment, + this.parameters, + this.opaque = true, + this.transitionDuration, + this.reverseTransitionDuration, + this.popGesture, + this.binding, + this.bindings = const [], + this.binds = const [], + this.transition, + this.customTransition, + this.fullscreenDialog = false, + this.children = const [], + this.middlewares = const [], + this.unknownRoute, + this.arguments, + this.showCupertinoParallax = true, + this.preventDuplicates = true, + this.preventDuplicateHandlingMode = + PreventDuplicateHandlingMode.reorderRoutes, + this.completer, + this.inheritParentPath = true, + final LocalKey? key, + }) : path = _nameToRegex(name), + assert(name.startsWith('/'), + 'It is necessary to start route name [$name] with a slash: /$name'), + super( + key: key ?? ValueKey(name), + name: name, + // arguments: Get.arguments, + ); final GetPageBuilder page; final bool? popGesture; final Map? parameters; @@ -52,79 +93,38 @@ class GetPage extends Page { final bool showCupertinoParallax; final PreventDuplicateHandlingMode preventDuplicateHandlingMode; - - GetPage({ - required this.name, - required this.page, - this.title, - this.participatesInRootNavigator, - this.gestureWidth, - // RouteSettings settings, - this.maintainState = true, - this.curve = Curves.linear, - this.alignment, - this.parameters, - this.opaque = true, - this.transitionDuration, - this.reverseTransitionDuration, - this.popGesture, - this.binding, - this.bindings = const [], - this.binds = const [], - this.transition, - this.customTransition, - this.fullscreenDialog = false, - this.children = const [], - this.middlewares = const [], - this.unknownRoute, - this.arguments, - this.showCupertinoParallax = true, - this.preventDuplicates = true, - this.preventDuplicateHandlingMode = - PreventDuplicateHandlingMode.reorderRoutes, - this.completer, - this.inheritParentPath = true, - LocalKey? key, - }) : path = _nameToRegex(name), - assert(name.startsWith('/'), - 'It is necessary to start route name [$name] with a slash: /$name'), - super( - key: key ?? ValueKey(name), - name: name, - // arguments: Get.arguments, - ); // settings = RouteSettings(name: name, arguments: Get.arguments); GetPage copyWith({ - LocalKey? key, - String? name, - GetPageBuilder? page, - bool? popGesture, - Map? parameters, - String? title, - Transition? transition, - Curve? curve, - Alignment? alignment, - bool? maintainState, - bool? opaque, - List? bindings, - BindingsInterface? binding, - List? binds, - CustomTransition? customTransition, - Duration? transitionDuration, - Duration? reverseTransitionDuration, - bool? fullscreenDialog, - RouteSettings? settings, - List>? children, - GetPage? unknownRoute, - List? middlewares, - bool? preventDuplicates, + final LocalKey? key, + final String? name, + final GetPageBuilder? page, + final bool? popGesture, + final Map? parameters, + final String? title, + final Transition? transition, + final Curve? curve, + final Alignment? alignment, + final bool? maintainState, + final bool? opaque, + final List? bindings, + final BindingsInterface? binding, + final List? binds, + final CustomTransition? customTransition, + final Duration? transitionDuration, + final Duration? reverseTransitionDuration, + final bool? fullscreenDialog, + final RouteSettings? settings, + final List>? children, + final GetPage? unknownRoute, + final List? middlewares, + final bool? preventDuplicates, final double Function(BuildContext context)? gestureWidth, - bool? participatesInRootNavigator, - Object? arguments, - bool? showCupertinoParallax, - Completer? completer, - bool? inheritParentPath, + final bool? participatesInRootNavigator, + final Object? arguments, + final bool? showCupertinoParallax, + final Completer? completer, + final bool? inheritParentPath, }) { return GetPage( key: key ?? this.key, @@ -162,7 +162,7 @@ class GetPage extends Page { } @override - Route createRoute(BuildContext context) { + Route createRoute(final BuildContext context) { // return GetPageRoute(settings: this, page: page); final page = PageRedirect( route: this, @@ -173,21 +173,21 @@ class GetPage extends Page { return page; } - static PathDecoded _nameToRegex(String path) { - var keys = []; + static PathDecoded _nameToRegex(final String path) { + final keys = []; - String recursiveReplace(Match pattern) { - var buffer = StringBuffer('(?:'); + String recursiveReplace(final Match pattern) { + final buffer = StringBuffer('(?:'); if (pattern[1] != null) buffer.write('.'); - buffer.write('([\\w%+-._~!\$&\'()*,;=:@]+))'); + buffer.write("([\\w%+-._~!\$&'()*,;=:@]+))"); if (pattern[3] != null) buffer.write('?'); keys.add(pattern[2]); - return "$buffer"; + return '$buffer'; } - var stringPath = '$path/?' + final stringPath = '$path/?' .replaceAllMapped(RegExp(r'(\.)?:(\w+)(\?)?'), recursiveReplace) .replaceAll('//', '/'); @@ -195,7 +195,7 @@ class GetPage extends Page { } @override - bool operator ==(Object other) { + bool operator ==(final Object other) { if (identical(this, other)) return true; return other is GetPage && other.key == key; } @@ -212,15 +212,15 @@ class GetPage extends Page { @immutable class PathDecoded { + const PathDecoded(this.regex, this.keys); final RegExp regex; final List keys; - const PathDecoded(this.regex, this.keys); @override int get hashCode => regex.hashCode; @override - bool operator ==(Object other) { + bool operator ==(final Object other) { if (identical(this, other)) return true; return other is PathDecoded && diff --git a/lib/get_navigation/src/routes/get_router_delegate.dart b/lib/get_navigation/src/routes/get_router_delegate.dart index 754688a30..e32eae5fe 100644 --- a/lib/get_navigation/src/routes/get_router_delegate.dart +++ b/lib/get_navigation/src/routes/get_router_delegate.dart @@ -12,15 +12,39 @@ class GetDelegate extends RouterDelegate ChangeNotifier, PopNavigatorRouterDelegateMixin, IGetNavigation { + GetDelegate({ + required final List pages, + GetPage? notFoundRoute, + this.navigatorObservers, + this.transitionDelegate, + this.backButtonPopMode = PopMode.history, + this.preventDuplicateHandlingMode = + PreventDuplicateHandlingMode.reorderRoutes, + this.pickPagesForRootNavigator, + this.restorationScopeId, + final bool showHashOnUrl = false, + final GlobalKey? navigatorKey, + }) : navigatorKey = navigatorKey ?? GlobalKey(), + notFoundRoute = notFoundRoute ??= GetPage( + name: '/404', + page: () => const Scaffold( + body: Center(child: Text('Route not found')), + ), + ) { + if (!showHashOnUrl && GetPlatform.isWeb) setUrlStrategy(); + addPages(pages); + addPage(notFoundRoute); + Get.log('GetDelegate is created !'); + } factory GetDelegate.createDelegate({ - GetPage? notFoundRoute, - List pages = const [], - List? navigatorObservers, - TransitionDelegate? transitionDelegate, - PopMode backButtonPopMode = PopMode.history, - PreventDuplicateHandlingMode preventDuplicateHandlingMode = + final GetPage? notFoundRoute, + final List pages = const [], + final List? navigatorObservers, + final TransitionDelegate? transitionDelegate, + final PopMode backButtonPopMode = PopMode.history, + final PreventDuplicateHandlingMode preventDuplicateHandlingMode = PreventDuplicateHandlingMode.reorderRoutes, - GlobalKey? navigatorKey, + final GlobalKey? navigatorKey, }) { return GetDelegate( notFoundRoute: notFoundRoute, @@ -47,11 +71,11 @@ class GetDelegate extends RouterDelegate List get activePages => _activePages; - final _routeTree = ParseRouteTree(routes: []); + final ParseRouteTree _routeTree = ParseRouteTree(routes: []); List get registeredRoutes => _routeTree.routes; - void addPages(List getPages) { + void addPages(final List getPages) { _routeTree.addRoutes(getPages); } @@ -59,15 +83,15 @@ class GetDelegate extends RouterDelegate _routeTree.routes.clear(); } - void addPage(GetPage getPage) { + void addPage(final GetPage getPage) { _routeTree.addRoute(getPage); } - void removePage(GetPage getPage) { + void removePage(final GetPage getPage) { _routeTree.removeRoute(getPage); } - RouteDecoder matchRoute(String name, {PageSettings? arguments}) { + RouteDecoder matchRoute(final String name, {final PageSettings? arguments}) { return _routeTree.matchRoute(name, arguments: arguments); } @@ -78,39 +102,15 @@ class GetDelegate extends RouterDelegate final String? restorationScopeId; - GetDelegate({ - GetPage? notFoundRoute, - this.navigatorObservers, - this.transitionDelegate, - this.backButtonPopMode = PopMode.history, - this.preventDuplicateHandlingMode = - PreventDuplicateHandlingMode.reorderRoutes, - this.pickPagesForRootNavigator, - this.restorationScopeId, - bool showHashOnUrl = false, - GlobalKey? navigatorKey, - required List pages, - }) : navigatorKey = navigatorKey ?? GlobalKey(), - notFoundRoute = notFoundRoute ??= GetPage( - name: '/404', - page: () => const Scaffold( - body: Center(child: Text('Route not found')), - ), - ) { - if (!showHashOnUrl && GetPlatform.isWeb) setUrlStrategy(); - addPages(pages); - addPage(notFoundRoute); - Get.log('GetDelegate is created !'); - } - - Future runMiddleware(RouteDecoder config) async { - final middlewares = config.currentTreeBranch.last.middlewares; + Future runMiddleware(final RouteDecoder config) async { + final List middlewares = + config.currentTreeBranch.last.middlewares; if (middlewares.isEmpty) { return config; } - var iterator = config; - for (var item in middlewares) { - var redirectRes = await item.redirectDelegate(iterator); + RouteDecoder iterator = config; + for (final GetMiddleware item in middlewares) { + final RouteDecoder? redirectRes = await item.redirectDelegate(iterator); if (redirectRes == null) return null; iterator = redirectRes; // Stop the iteration over the middleware if we changed page @@ -127,8 +127,8 @@ class GetDelegate extends RouterDelegate return iterator; } - Future _unsafeHistoryAdd(RouteDecoder config) async { - final res = await runMiddleware(config); + Future _unsafeHistoryAdd(final RouteDecoder config) async { + final RouteDecoder? res = await runMiddleware(config); if (res == null) return; _activePages.add(res); } @@ -139,16 +139,16 @@ class GetDelegate extends RouterDelegate // return null; // } - Future _unsafeHistoryRemoveAt(int index, T result) async { + Future _unsafeHistoryRemoveAt(final int index, final T result) async { if (index == _activePages.length - 1 && _activePages.length > 1) { //removing WILL update the current route - final toCheck = _activePages[_activePages.length - 2]; - final resMiddleware = await runMiddleware(toCheck); + final RouteDecoder toCheck = _activePages[_activePages.length - 2]; + final RouteDecoder? resMiddleware = await runMiddleware(toCheck); if (resMiddleware == null) return null; _activePages[_activePages.length - 2] = resMiddleware; } - final completer = _activePages.removeAt(index).route?.completer; + final Completer? completer = _activePages.removeAt(index).route?.completer; if (completer?.isCompleted == false) completer!.complete(result); return completer?.future as T?; @@ -159,17 +159,18 @@ class GetDelegate extends RouterDelegate } Map get parameters { - return currentConfiguration?.pageSettings?.params ?? {}; + return currentConfiguration?.pageSettings?.params ?? {}; } PageSettings? get pageSettings { return currentConfiguration?.pageSettings; } - Future _pushHistory(RouteDecoder config) async { + Future _pushHistory(final RouteDecoder config) async { if (config.route!.preventDuplicates) { - final originalEntryIndex = _activePages.indexWhere( - (element) => element.pageSettings?.name == config.pageSettings?.name); + final int originalEntryIndex = _activePages.indexWhere( + (final RouteDecoder element) => + element.pageSettings?.name == config.pageSettings?.name); if (originalEntryIndex >= 0) { switch (preventDuplicateHandlingMode) { case PreventDuplicateHandlingMode.popUntilOriginalRoute: @@ -189,35 +190,37 @@ class GetDelegate extends RouterDelegate await _unsafeHistoryAdd(config); } - Future _popHistory(T result) async { + Future _popHistory(final T result) async { if (!_canPopHistory()) return null; return await _doPopHistory(result); } - Future _doPopHistory(T result) async { + Future _doPopHistory(final T result) async { return _unsafeHistoryRemoveAt(_activePages.length - 1, result); } - Future _popPage(T result) async { + Future _popPage(final T result) async { if (!_canPopPage()) return null; return await _doPopPage(result); } // returns the popped page - Future _doPopPage(T result) async { - final currentBranch = currentConfiguration?.currentTreeBranch; + Future _doPopPage(final T result) async { + final List? currentBranch = + currentConfiguration?.currentTreeBranch; if (currentBranch != null && currentBranch.length > 1) { //remove last part only - final remaining = currentBranch.take(currentBranch.length - 1); - final prevHistoryEntry = _activePages.length > 1 + final Iterable remaining = + currentBranch.take(currentBranch.length - 1); + final RouteDecoder? prevHistoryEntry = _activePages.length > 1 ? _activePages[_activePages.length - 2] : null; //check if current route is the same as the previous route if (prevHistoryEntry != null) { //if so, pop the entire _activePages entry - final newLocation = remaining.last.name; - final prevLocation = prevHistoryEntry.pageSettings?.name; + final String newLocation = remaining.last.name; + final String? prevLocation = prevHistoryEntry.pageSettings?.name; if (newLocation == prevLocation) { //pop the entire _activePages entry return await _popHistory(result); @@ -240,7 +243,7 @@ class GetDelegate extends RouterDelegate } } - Future _pop(PopMode mode, T result) async { + Future _pop(final PopMode mode, final T result) async { switch (mode) { case PopMode.history: return await _popHistory(result); @@ -251,7 +254,7 @@ class GetDelegate extends RouterDelegate } } - Future popHistory(T result) async { + Future popHistory(final T result) async { return await _popHistory(result); } @@ -264,7 +267,8 @@ class GetDelegate extends RouterDelegate } bool _canPopPage() { - final currentTreeBranch = currentConfiguration?.currentTreeBranch; + final List? currentTreeBranch = + currentConfiguration?.currentTreeBranch; if (currentTreeBranch == null) return false; return currentTreeBranch.length > 1 ? true : _canPopHistory(); } @@ -273,7 +277,7 @@ class GetDelegate extends RouterDelegate return SynchronousFuture(_canPopPage()); } - bool _canPop(mode) { + bool _canPop(final mode) { switch (mode) { case PopMode.history: return _canPopHistory(); @@ -286,23 +290,23 @@ class GetDelegate extends RouterDelegate /// gets the visual pages from the current _activePages entry /// /// visual pages must have [GetPage.participatesInRootNavigator] set to true - Iterable getVisualPages(RouteDecoder? currentHistory) { - final res = currentHistory!.currentTreeBranch - .where((r) => r.participatesInRootNavigator != null); + Iterable getVisualPages(final RouteDecoder? currentHistory) { + final Iterable res = currentHistory!.currentTreeBranch + .where((final GetPage r) => r.participatesInRootNavigator != null); if (res.isEmpty) { //default behavior, all routes participate in root navigator - return _activePages.map((e) => e.route!); + return _activePages.map((final RouteDecoder e) => e.route!); } else { //user specified at least one participatesInRootNavigator - return res - .where((element) => element.participatesInRootNavigator == true); + return res.where((final GetPage element) => + element.participatesInRootNavigator == true); } } @override - Widget build(BuildContext context) { - final currentHistory = currentConfiguration; - final pages = currentHistory == null + Widget build(final BuildContext context) { + final RouteDecoder? currentHistory = currentConfiguration; + final List pages = currentHistory == null ? [] : pickPagesForRootNavigator?.call(currentHistory).toList() ?? getVisualPages(currentHistory).toList(); @@ -322,31 +326,31 @@ class GetDelegate extends RouterDelegate } @override - Future goToUnknownPage([bool clearPages = false]) async { + Future goToUnknownPage([final bool clearPages = false]) async { if (clearPages) _activePages.clear(); - final pageSettings = _buildPageSettings(notFoundRoute.name); - final routeDecoder = _getRouteDecoder(pageSettings); + final PageSettings pageSettings = _buildPageSettings(notFoundRoute.name); + final RouteDecoder? routeDecoder = _getRouteDecoder(pageSettings); _push(routeDecoder!); } @protected - void _popWithResult([T? result]) { - final completer = _activePages.removeLast().route?.completer; + void _popWithResult([final T? result]) { + final Completer? completer = _activePages.removeLast().route?.completer; if (completer?.isCompleted == false) completer!.complete(result); } @override Future toNamed( - String page, { - dynamic arguments, - dynamic id, - bool preventDuplicates = true, - Map? parameters, + final String page, { + final dynamic arguments, + final dynamic id, + final bool preventDuplicates = true, + final Map? parameters, }) async { - final args = _buildPageSettings(page, arguments); - final route = _getRouteDecoder(args); + final PageSettings args = _buildPageSettings(page, arguments); + final RouteDecoder? route = _getRouteDecoder(args); if (route != null) { return _push(route); } else { @@ -357,31 +361,31 @@ class GetDelegate extends RouterDelegate @override Future to( - Widget Function() page, { - bool? opaque, - Transition? transition, - Curve? curve, - Duration? duration, - String? id, + final Widget Function() page, { + final bool? opaque, + final Transition? transition, + final Curve? curve, + final Duration? duration, + final String? id, String? routeName, - bool fullscreenDialog = false, - dynamic arguments, - List bindings = const [], - bool preventDuplicates = true, - bool? popGesture, - bool showCupertinoParallax = true, - double Function(BuildContext context)? gestureWidth, - bool rebuildStack = true, - PreventDuplicateHandlingMode preventDuplicateHandlingMode = + final bool fullscreenDialog = false, + final dynamic arguments, + final List bindings = const [], + final bool preventDuplicates = true, + final bool? popGesture, + final bool showCupertinoParallax = true, + final double Function(BuildContext context)? gestureWidth, + final bool rebuildStack = true, + final PreventDuplicateHandlingMode preventDuplicateHandlingMode = PreventDuplicateHandlingMode.reorderRoutes, }) async { - routeName = _cleanRouteName("/${page.runtimeType}"); + routeName = _cleanRouteName('/${page.runtimeType}'); // if (preventDuplicateHandlingMode == //PreventDuplicateHandlingMode.Recreate) { // routeName = routeName + page.hashCode.toString(); // } - final getPage = GetPage( + final GetPage getPage = GetPage( name: routeName, opaque: opaque ?? true, page: page, @@ -397,8 +401,8 @@ class GetDelegate extends RouterDelegate ); _routeTree.addRoute(getPage); - final args = _buildPageSettings(routeName, arguments); - final route = _getRouteDecoder(args); + final PageSettings args = _buildPageSettings(routeName, arguments); + final RouteDecoder? route = _getRouteDecoder(args); final result = await _push( route!, rebuildStack: rebuildStack, @@ -409,23 +413,23 @@ class GetDelegate extends RouterDelegate @override Future off( - Widget Function() page, { - bool? opaque, - Transition? transition, - Curve? curve, - Duration? duration, - String? id, + final Widget Function() page, { + final bool? opaque, + final Transition? transition, + final Curve? curve, + final Duration? duration, + final String? id, String? routeName, - bool fullscreenDialog = false, - dynamic arguments, - List bindings = const [], - bool preventDuplicates = true, - bool? popGesture, - bool showCupertinoParallax = true, - double Function(BuildContext context)? gestureWidth, + final bool fullscreenDialog = false, + final dynamic arguments, + final List bindings = const [], + final bool preventDuplicates = true, + final bool? popGesture, + final bool showCupertinoParallax = true, + final double Function(BuildContext context)? gestureWidth, }) async { - routeName = _cleanRouteName("/${page.runtimeType}"); - final route = GetPage( + routeName = _cleanRouteName('/${page.runtimeType}'); + final GetPage route = GetPage( name: routeName, opaque: opaque ?? true, page: page, @@ -439,29 +443,29 @@ class GetDelegate extends RouterDelegate transitionDuration: duration ?? Get.defaultTransitionDuration, ); - final args = _buildPageSettings(routeName, arguments); + final PageSettings args = _buildPageSettings(routeName, arguments); return _replace(args, route); } @override Future? offAll( - Widget Function() page, { - bool Function(GetPage route)? predicate, - bool opaque = true, - bool? popGesture, - String? id, + final Widget Function() page, { + final bool Function(GetPage route)? predicate, + final bool opaque = true, + final bool? popGesture, + final String? id, String? routeName, - dynamic arguments, - List bindings = const [], - bool fullscreenDialog = false, - Transition? transition, - Curve? curve, - Duration? duration, - bool showCupertinoParallax = true, - double Function(BuildContext context)? gestureWidth, + final dynamic arguments, + final List bindings = const [], + final bool fullscreenDialog = false, + final Transition? transition, + final Curve? curve, + final Duration? duration, + final bool showCupertinoParallax = true, + final double Function(BuildContext context)? gestureWidth, }) async { - routeName = _cleanRouteName("/${page.runtimeType}"); - final route = GetPage( + routeName = _cleanRouteName('/${page.runtimeType}'); + final GetPage route = GetPage( name: routeName, opaque: opaque, page: page, @@ -475,9 +479,10 @@ class GetDelegate extends RouterDelegate transitionDuration: duration ?? Get.defaultTransitionDuration, ); - final args = _buildPageSettings(routeName, arguments); + final PageSettings args = _buildPageSettings(routeName, arguments); - final newPredicate = predicate ?? (route) => false; + final bool Function(GetPage route) newPredicate = + predicate ?? (final GetPage route) => false; while (_activePages.length > 1 && !newPredicate(_activePages.last.route!)) { _popWithResult(); @@ -488,14 +493,14 @@ class GetDelegate extends RouterDelegate @override Future? offAllNamed( - String newRouteName, { + final String newRouteName, { // bool Function(GetPage route)? predicate, - dynamic arguments, - String? id, - Map? parameters, + final dynamic arguments, + final String? id, + final Map? parameters, }) async { - final args = _buildPageSettings(newRouteName, arguments); - final route = _getRouteDecoder(args); + final PageSettings args = _buildPageSettings(newRouteName, arguments); + final RouteDecoder? route = _getRouteDecoder(args); if (route == null) return null; while (_activePages.length > 1) { @@ -507,17 +512,18 @@ class GetDelegate extends RouterDelegate @override Future? offNamedUntil( - String page, { - bool Function(GetPage route)? predicate, - dynamic arguments, - String? id, - Map? parameters, + final String page, { + final bool Function(GetPage route)? predicate, + final dynamic arguments, + final String? id, + final Map? parameters, }) async { - final args = _buildPageSettings(page, arguments); - final route = _getRouteDecoder(args); + final PageSettings args = _buildPageSettings(page, arguments); + final RouteDecoder? route = _getRouteDecoder(args); if (route == null) return null; - final newPredicate = predicate ?? (route) => false; + final bool Function(GetPage route) newPredicate = + predicate ?? (final GetPage route) => false; while (_activePages.length > 1 && newPredicate(_activePages.last.route!)) { _activePages.removeLast(); @@ -528,13 +534,13 @@ class GetDelegate extends RouterDelegate @override Future offNamed( - String page, { - dynamic arguments, - String? id, - Map? parameters, + final String page, { + final dynamic arguments, + final String? id, + final Map? parameters, }) async { - final args = _buildPageSettings(page, arguments); - final route = _getRouteDecoder(args); + final PageSettings args = _buildPageSettings(page, arguments); + final RouteDecoder? route = _getRouteDecoder(args); if (route == null) return null; _popWithResult(); return _push(route); @@ -542,13 +548,13 @@ class GetDelegate extends RouterDelegate @override Future toNamedAndOffUntil( - String page, - bool Function(GetPage) predicate, [ - Object? data, + final String page, + final bool Function(GetPage) predicate, [ + final Object? data, ]) async { - final arguments = _buildPageSettings(page, data); + final PageSettings arguments = _buildPageSettings(page, data); - final route = _getRouteDecoder(arguments); + final RouteDecoder? route = _getRouteDecoder(arguments); if (route == null) return null; @@ -561,9 +567,9 @@ class GetDelegate extends RouterDelegate @override Future offUntil( - Widget Function() page, - bool Function(GetPage) predicate, [ - Object? arguments, + final Widget Function() page, + final bool Function(GetPage) predicate, [ + final Object? arguments, ]) async { while (_activePages.isNotEmpty && !predicate(_activePages.last.route!)) { _popWithResult(); @@ -573,7 +579,7 @@ class GetDelegate extends RouterDelegate } @override - void removeRoute(String name) { + void removeRoute(final String name) { _activePages.remove(RouteDecoder.fromRoute(name)); } @@ -584,8 +590,8 @@ class GetDelegate extends RouterDelegate void _checkIfCanBack() { assert(() { if (!canBack) { - final last = _activePages.last; - final name = last.route?.name; + final RouteDecoder last = _activePages.last; + final String? name = last.route?.name; throw 'The page $name cannot be popped'; } return true; @@ -593,10 +599,10 @@ class GetDelegate extends RouterDelegate } @override - Future backAndtoNamed(String page, - {T? result, Object? arguments}) async { - final args = _buildPageSettings(page, arguments); - final route = _getRouteDecoder(args); + Future backAndtoNamed(final String page, + {final T? result, final Object? arguments}) async { + final PageSettings args = _buildPageSettings(page, arguments); + final RouteDecoder? route = _getRouteDecoder(args); if (route == null) return null; _popWithResult(result); return _push(route); @@ -607,11 +613,11 @@ class GetDelegate extends RouterDelegate /// DOES NOT remove the [fullRoute] @override Future popModeUntil( - String fullRoute, { - PopMode popMode = PopMode.history, + final String fullRoute, { + final PopMode popMode = PopMode.history, }) async { // remove history or page entries until you meet route - var iterator = currentConfiguration; + RouteDecoder? iterator = currentConfiguration; while (_canPop(popMode) && iterator != null && iterator.pageSettings?.name != fullRoute) { @@ -623,7 +629,7 @@ class GetDelegate extends RouterDelegate } @override - void backUntil(bool Function(GetPage) predicate) { + void backUntil(final bool Function(GetPage) predicate) { while (_activePages.length <= 1 && !predicate(_activePages.last.route!)) { _popWithResult(); } @@ -631,30 +637,33 @@ class GetDelegate extends RouterDelegate notifyListeners(); } - Future _replace(PageSettings arguments, GetPage page) async { - final index = _activePages.length > 1 ? _activePages.length - 1 : 0; + Future _replace( + final PageSettings arguments, final GetPage page) async { + final int index = _activePages.length > 1 ? _activePages.length - 1 : 0; _routeTree.addRoute(page); - final activePage = _getRouteDecoder(arguments); + final RouteDecoder? activePage = _getRouteDecoder(arguments); // final activePage = _configureRouterDecoder(route!, arguments); _activePages[index] = activePage!; notifyListeners(); - final result = await activePage.route?.completer?.future as Future?; + final Future? result = + await activePage.route?.completer?.future as Future?; _routeTree.removeRoute(page); return result; } - Future _replaceNamed(RouteDecoder activePage) async { - final index = _activePages.length > 1 ? _activePages.length - 1 : 0; + Future _replaceNamed(final RouteDecoder activePage) async { + final int index = _activePages.length > 1 ? _activePages.length - 1 : 0; // final activePage = _configureRouterDecoder(page, arguments); _activePages[index] = activePage; notifyListeners(); - final result = await activePage.route?.completer?.future as Future?; + final Future? result = + await activePage.route?.completer?.future as Future?; return result; } @@ -674,22 +683,23 @@ class GetDelegate extends RouterDelegate return Uri.tryParse(name)?.toString() ?? name; } - PageSettings _buildPageSettings(String page, [Object? data]) { - var uri = Uri.parse(page); + PageSettings _buildPageSettings(final String page, [final Object? data]) { + final Uri uri = Uri.parse(page); return PageSettings(uri, data); } @protected - RouteDecoder? _getRouteDecoder(PageSettings arguments) { - var page = arguments.uri.path; - final parameters = arguments.params; + RouteDecoder? _getRouteDecoder(final PageSettings arguments) { + String page = arguments.uri.path; + final Map parameters = arguments.params; if (parameters.isNotEmpty) { - final uri = Uri(path: page, queryParameters: parameters); + final Uri uri = Uri(path: page, queryParameters: parameters); page = uri.toString(); } - final decoder = _routeTree.matchRoute(page, arguments: arguments); - final route = decoder.route; + final RouteDecoder decoder = + _routeTree.matchRoute(page, arguments: arguments); + final GetPage? route = decoder.route; if (route == null) return null; return _configureRouterDecoder(decoder, arguments); @@ -697,8 +707,8 @@ class GetDelegate extends RouterDelegate @protected RouteDecoder _configureRouterDecoder( - RouteDecoder decoder, PageSettings arguments) { - final parameters = + final RouteDecoder decoder, final PageSettings arguments) { + final Map parameters = arguments.params.isEmpty ? arguments.query : arguments.params; arguments.params.addAll(arguments.query); if (decoder.parameters.isEmpty) { @@ -715,17 +725,18 @@ class GetDelegate extends RouterDelegate return decoder; } - Future _push(RouteDecoder decoder, {bool rebuildStack = true}) async { - var mid = await runMiddleware(decoder); - final res = mid ?? decoder; + Future _push(final RouteDecoder decoder, + {final bool rebuildStack = true}) async { + final RouteDecoder? mid = await runMiddleware(decoder); + final RouteDecoder res = mid ?? decoder; // if (res == null) res = decoder; - final preventDuplicateHandlingMode = + final PreventDuplicateHandlingMode preventDuplicateHandlingMode = res.route?.preventDuplicateHandlingMode ?? PreventDuplicateHandlingMode.reorderRoutes; - final onStackPage = _activePages - .firstWhereOrNull((element) => element.route?.key == res.route?.key); + final RouteDecoder? onStackPage = _activePages.firstWhereOrNull( + (final RouteDecoder element) => element.route?.key == res.route?.key); /// There are no duplicate routes in the stack if (onStackPage == null) { @@ -759,8 +770,8 @@ class GetDelegate extends RouterDelegate } @override - Future setNewRoutePath(RouteDecoder configuration) async { - final page = configuration.route; + Future setNewRoutePath(final RouteDecoder configuration) async { + final GetPage? page = configuration.route; if (page == null) { goToUnknownPage(); return; @@ -772,15 +783,15 @@ class GetDelegate extends RouterDelegate @override RouteDecoder? get currentConfiguration { if (_activePages.isEmpty) return null; - final route = _activePages.last; + final RouteDecoder route = _activePages.last; return route; } Future handlePopupRoutes({ - Object? result, + final Object? result, }) async { Route? currentRoute; - navigatorKey.currentState!.popUntil((route) { + navigatorKey.currentState!.popUntil((final Route route) { currentRoute = route; return true; }); @@ -792,11 +803,11 @@ class GetDelegate extends RouterDelegate @override Future popRoute({ - Object? result, - PopMode? popMode, + final Object? result, + final PopMode? popMode, }) async { //Returning false will cause the entire app to be popped. - final wasPopup = await handlePopupRoutes(result: result); + final bool wasPopup = await handlePopupRoutes(result: result); if (wasPopup) return true; if (_canPop(popMode ?? backButtonPopMode)) { @@ -809,14 +820,14 @@ class GetDelegate extends RouterDelegate } @override - void back([T? result]) { + void back([final T? result]) { _checkIfCanBack(); _popWithResult(result); notifyListeners(); } - bool _onPopVisualRoute(Route route, dynamic result) { - final didPop = route.didPop(result); + bool _onPopVisualRoute(final Route route, final dynamic result) { + final bool didPop = route.didPop(result); if (!didPop) { return false; } diff --git a/lib/get_navigation/src/routes/get_transition_mixin.dart b/lib/get_navigation/src/routes/get_transition_mixin.dart index 3af79f9ee..1eb92e138 100644 --- a/lib/get_navigation/src/routes/get_transition_mixin.dart +++ b/lib/get_navigation/src/routes/get_transition_mixin.dart @@ -23,14 +23,8 @@ const int _kMaxPageBackAnimationTime = 300; // Milliseconds. class GetBackGestureDetector extends StatefulWidget { const GetBackGestureDetector({ - Key? key, - required this.limitedSwipe, - required this.gestureWidth, - required this.initialOffset, - required this.popGestureEnable, - required this.onStartPopGesture, - required this.child, - }) : super(key: key); + required this.limitedSwipe, required this.gestureWidth, required this.initialOffset, required this.popGestureEnable, required this.onStartPopGesture, required this.child, super.key, + }); final bool limitedSwipe; final double gestureWidth; @@ -48,13 +42,13 @@ class GetBackGestureDetector extends StatefulWidget { class GetBackGestureDetectorState extends State> { GetBackGestureController? _backGestureController; - void _handleDragStart(DragStartDetails details) { + void _handleDragStart(final DragStartDetails details) { assert(mounted); assert(_backGestureController == null); _backGestureController = widget.onStartPopGesture(); } - void _handleDragUpdate(DragUpdateDetails details) { + void _handleDragUpdate(final DragUpdateDetails details) { assert(mounted); assert(_backGestureController != null); _backGestureController!.dragUpdate( @@ -62,7 +56,7 @@ class GetBackGestureDetectorState extends State> { ); } - void _handleDragEnd(DragEndDetails details) { + void _handleDragEnd(final DragEndDetails details) { assert(mounted); assert(_backGestureController != null); _backGestureController!.dragEnd(_convertToLogical( @@ -79,7 +73,7 @@ class GetBackGestureDetectorState extends State> { _backGestureController = null; } - double _convertToLogical(double value) { + double _convertToLogical(final double value) { switch (Directionality.of(context)) { case TextDirection.rtl: return -value; @@ -89,7 +83,7 @@ class GetBackGestureDetectorState extends State> { } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { assert(debugCheckHasDirectionality(context)); final gestureDetector = RawGestureDetector( @@ -108,7 +102,7 @@ class GetBackGestureDetectorState extends State> { popGestureEnable: widget.popGestureEnable, ); }, - (directionalityDragGesture) => directionalityDragGesture + (final directionalityDragGesture) => directionalityDragGesture ..onStart = _handleDragStart ..onUpdate = _handleDragUpdate ..onEnd = _handleDragEnd @@ -135,7 +129,7 @@ class GetBackGestureDetectorState extends State> { ); } - double _dragAreaWidth(BuildContext context) { + double _dragAreaWidth(final BuildContext context) { // For devices with notches, the drag area needs to be larger on the side // that has the notch. final dragAreaWidth = Directionality.of(context) == TextDirection.ltr @@ -158,13 +152,13 @@ class GetBackGestureController { /// The drag gesture has changed by [delta]. The total range of the /// drag should be 0.0 to 1.0. - void dragUpdate(double delta) { + void dragUpdate(final double delta) { controller.value -= delta; } /// The drag gesture has ended with a horizontal motion of [velocity] as a /// fraction of screen width per second. - void dragEnd(double velocity) { + void dragEnd(final double velocity) { // Fling in the appropriate direction. // AnimationController.fling is guaranteed to // take at least one frame. @@ -217,7 +211,7 @@ class GetBackGestureController { // curve of the page transition mid-flight since CupertinoPageTransition // depends on userGestureInProgress. late AnimationStatusListener animationStatusCallback; - animationStatusCallback = (status) { + animationStatusCallback = (final status) { navigator.didStopUserGesture(); controller.removeStatusListener(animationStatusCallback); }; @@ -293,11 +287,11 @@ Cannot read the previousTitle for a route that has not yet been installed''', /// Builds the primary contents of the route. @protected - Widget buildContent(BuildContext context); + Widget buildContent(final BuildContext context); @override - Widget buildPage(BuildContext context, Animation animation, - Animation secondaryAnimation) { + Widget buildPage(final BuildContext context, final Animation animation, + final Animation secondaryAnimation) { final child = buildContent(context); final Widget result = Semantics( scopesRoute: true, @@ -308,14 +302,14 @@ Cannot read the previousTitle for a route that has not yet been installed''', } @override - Widget buildTransitions(BuildContext context, Animation animation, - Animation secondaryAnimation, Widget child) { + Widget buildTransitions(final BuildContext context, final Animation animation, + final Animation secondaryAnimation, final Widget child) { return buildPageTransitions( this, context, animation, secondaryAnimation, child); } @override - bool canTransitionTo(TransitionRoute nextRoute) { + bool canTransitionTo(final TransitionRoute nextRoute) { // Don't perform outgoing animation if the next route is a // fullscreen dialog. return (nextRoute is GetPageRouteTransitionMixin && @@ -326,7 +320,7 @@ Cannot read the previousTitle for a route that has not yet been installed''', } @override - void didChangePrevious(Route? previousRoute) { + void didChangePrevious(final Route? previousRoute) { final previousTitleString = previousRoute is CupertinoRouteTransitionMixin ? previousRoute.title : null; @@ -338,7 +332,7 @@ Cannot read the previousTitle for a route that has not yet been installed''', super.didChangePrevious(previousRoute); } - static bool canSwipe(GetPageRoute route) => + static bool canSwipe(final GetPageRoute route) => route.popGesture ?? Get.defaultPopGesture; /// Returns a [CupertinoFullscreenDialogTransition] if [route] is a full @@ -356,13 +350,13 @@ Cannot read the previousTitle for a route that has not yet been installed''', /// * [CupertinoPageTransitionsBuilder], which uses this method to define a /// [PageTransitionsBuilder] for the [PageTransitionsTheme]. static Widget buildPageTransitions( - PageRoute rawRoute, - BuildContext context, + final PageRoute rawRoute, + final BuildContext context, Animation animation, - Animation secondaryAnimation, - Widget child, { - bool limitedSwipe = false, - double initialOffset = 0, + final Animation secondaryAnimation, + final Widget child, { + final bool limitedSwipe = false, + final double initialOffset = 0, }) { // Check if the route has an animation that's currently participating // in a back swipe gesture. @@ -724,7 +718,7 @@ Cannot read the previousTitle for a route that has not yet been installed''', route.alignment, animation, secondaryAnimation, child); } - PageTransitionsTheme pageTransitionsTheme = + final PageTransitionsTheme pageTransitionsTheme = Theme.of(context).pageTransitionsTheme; return pageTransitionsTheme.buildTransitions( @@ -763,13 +757,13 @@ Cannot read the previousTitle for a route that has not yet been installed''', /// /// * [popGestureEnabled], which returns true if a user-triggered pop gesture /// would be allowed. - static bool isPopGestureInProgress(BuildContext context) { + static bool isPopGestureInProgress(final BuildContext context) { final route = ModalRoute.of(context)!; return route.navigator!.userGestureInProgress; } static bool _isPopGestureEnabled( - PageRoute route, bool canSwipe, BuildContext context) { + final PageRoute route, final bool canSwipe, final BuildContext context) { // If there's nothing to go back to, then obviously we don't support // the back gesture. if (route.isFirst) return false; @@ -803,7 +797,7 @@ Cannot read the previousTitle for a route that has not yet been installed''', } static GetBackGestureController _startPopGesture( - PageRoute route, + final PageRoute route, ) { return GetBackGestureController( navigator: route.navigator!, @@ -814,21 +808,21 @@ Cannot read the previousTitle for a route that has not yet been installed''', class _DirectionalityDragGestureRecognizer extends HorizontalDragGestureRecognizer { - final ValueGetter popGestureEnable; - final ValueGetter hasbackGestureController; - final bool isRTL; - final bool isLTR; _DirectionalityDragGestureRecognizer({ required this.isRTL, required this.isLTR, required this.popGestureEnable, required this.hasbackGestureController, - Object? debugOwner, - }) : super(debugOwner: debugOwner); + super.debugOwner, + }); + final ValueGetter popGestureEnable; + final ValueGetter hasbackGestureController; + final bool isRTL; + final bool isLTR; @override - void handleEvent(PointerEvent event) { + void handleEvent(final PointerEvent event) { final dx = event.delta.dx; if (hasbackGestureController() || popGestureEnable() && (isRTL && dx < 0 || isLTR && dx > 0 || dx == 0)) { diff --git a/lib/get_navigation/src/routes/modules.dart b/lib/get_navigation/src/routes/modules.dart index 522a6aac1..6a9166d0f 100644 --- a/lib/get_navigation/src/routes/modules.dart +++ b/lib/get_navigation/src/routes/modules.dart @@ -4,8 +4,8 @@ import '../../../instance_manager.dart'; import '../router_report.dart'; class Dependencies { - void lazyPut(InstanceBuilderCallback builder, - {String? tag, bool fenix = false}) { + void lazyPut(final InstanceBuilderCallback builder, + {final String? tag, final bool fenix = false}) { Get.lazyPut(builder, tag: tag, fenix: fenix); } @@ -13,55 +13,55 @@ class Dependencies { return find(); } - void spawn(InstanceBuilderCallback builder, - {String? tag, bool permanent = true}) => + void spawn(final InstanceBuilderCallback builder, + {final String? tag, final bool permanent = true}) => Get.spawn(builder, tag: tag, permanent: permanent); - S find({String? tag}) => Get.find(tag: tag); + S find({final String? tag}) => Get.find(tag: tag); - S put(S dependency, - {String? tag, - bool permanent = false, - InstanceBuilderCallback? builder}) => + S put(final S dependency, + {final String? tag, + final bool permanent = false, + final InstanceBuilderCallback? builder}) => Get.put(dependency, tag: tag, permanent: permanent); - Future delete({String? tag, bool force = false}) async => + Future delete({final String? tag, final bool force = false}) async => Get.delete(tag: tag, force: force); - Future deleteAll({bool force = false}) async => + Future deleteAll({final bool force = false}) async => Get.deleteAll(force: force); - void reloadAll({bool force = false}) => Get.reloadAll(force: force); + void reloadAll({final bool force = false}) => Get.reloadAll(force: force); - void reload({String? tag, String? key, bool force = false}) => + void reload({final String? tag, final String? key, final bool force = false}) => Get.reload(tag: tag, key: key, force: force); - bool isRegistered({String? tag}) => Get.isRegistered(tag: tag); + bool isRegistered({final String? tag}) => Get.isRegistered(tag: tag); - bool isPrepared({String? tag}) => Get.isPrepared(tag: tag); + bool isPrepared({final String? tag}) => Get.isPrepared(tag: tag); - void replace

(P child, {String? tag}) { + void replace

(final P child, {final String? tag}) { final info = Get.getInstanceInfo

(tag: tag); - final permanent = (info.isPermanent ?? false); + final permanent = info.isPermanent ?? false; delete

(tag: tag, force: permanent); put(child, tag: tag, permanent: permanent); } - void lazyReplace

(InstanceBuilderCallback

builder, - {String? tag, bool? fenix}) { + void lazyReplace

(final InstanceBuilderCallback

builder, + {final String? tag, final bool? fenix}) { final info = Get.getInstanceInfo

(tag: tag); - final permanent = (info.isPermanent ?? false); + final permanent = info.isPermanent ?? false; delete

(tag: tag, force: permanent); lazyPut(builder, tag: tag, fenix: fenix ?? permanent); } } abstract class Module extends StatefulWidget { - const Module({Key? key}) : super(key: key); + const Module({super.key}); - Widget view(BuildContext context); + Widget view(final BuildContext context); - void dependencies(Dependencies i); + void dependencies(final Dependencies i); @override ModuleState createState() => ModuleState(); @@ -82,7 +82,7 @@ class ModuleState extends State { } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return widget.view(context); } } diff --git a/lib/get_navigation/src/routes/new_path_route.dart b/lib/get_navigation/src/routes/new_path_route.dart index 8c1b4912a..bf06dbdcc 100644 --- a/lib/get_navigation/src/routes/new_path_route.dart +++ b/lib/get_navigation/src/routes/new_path_route.dart @@ -7,7 +7,7 @@ import 'get_route.dart'; class RouteMatcher { final RouteNode _root = RouteNode('/', '/'); - RouteNode addRoute(String path) { + RouteNode addRoute(final String path) { final segments = _parsePath(path); var currentNode = _root; @@ -24,7 +24,7 @@ class RouteMatcher { return currentNode; } - void removeRoute(String path) { + void removeRoute(final String path) { final segments = _parsePath(path); var currentNode = _root; RouteNode? nodeToDelete; @@ -50,12 +50,12 @@ class RouteMatcher { parent.nodeSegments.remove(nodeToDelete); } - RouteNode? _findChild(RouteNode currentNode, String segment) { + RouteNode? _findChild(final RouteNode currentNode, final String segment) { return currentNode.nodeSegments - .firstWhereOrNull((node) => node.matches(segment)); + .firstWhereOrNull((final node) => node.matches(segment)); } - MatchResult? matchRoute(String path) { + MatchResult? matchRoute(final String path) { final uri = Uri.parse(path); final segments = _parsePath(uri.path); var currentNode = _root; @@ -88,26 +88,26 @@ class RouteMatcher { ); } - List _parsePath(String path) { - return path.split('/').where((segment) => segment.isNotEmpty).toList(); + List _parsePath(final String path) { + return path.split('/').where((final segment) => segment.isNotEmpty).toList(); } } class RouteTreeResult { - final GetPage? route; - final MatchResult matchResult; RouteTreeResult({ required this.route, required this.matchResult, }); + final GetPage? route; + final MatchResult matchResult; @override String toString() { return 'RouteTreeResult(route: $route, matchResult: $matchResult)'; } - RouteTreeResult configure(String page, Object? arguments) { + RouteTreeResult configure(final String page, final Object? arguments) { return copyWith( route: route?.copyWith( key: ValueKey(page), @@ -118,8 +118,8 @@ class RouteTreeResult { } RouteTreeResult copyWith({ - GetPage? route, - MatchResult? matchResult, + final GetPage? route, + final MatchResult? matchResult, }) { return RouteTreeResult( route: route ?? this.route, @@ -133,19 +133,19 @@ class RouteTree { final Map tree = {}; final RouteMatcher matcher = RouteMatcher(); - void addRoute(GetPage route) { + void addRoute(final GetPage route) { matcher.addRoute(route.name); tree[route.name] = route; handleChild(route); } - void addRoutes(List routes) { - for (var route in routes) { + void addRoutes(final List routes) { + for (final route in routes) { addRoute(route); } } - void handleChild(GetPage route) { + void handleChild(final GetPage route) { final children = route.children; for (var child in children) { final middlewares = List.of(route.middlewares); @@ -155,24 +155,24 @@ class RouteTree { child = child.copyWith(middlewares: middlewares, bindings: bindings); if (child.inheritParentPath) { child = child.copyWith( - name: ('${route.path}/${child.path}').replaceAll(r'//', '/')); + name: '${route.path}/${child.path}'.replaceAll(r'//', '/')); } addRoute(child); } } - void removeRoute(GetPage route) { + void removeRoute(final GetPage route) { matcher.removeRoute(route.name); tree.remove(route.path); } - void removeRoutes(List routes) { - for (var route in routes) { + void removeRoutes(final List routes) { + for (final route in routes) { removeRoute(route); } } - RouteTreeResult? matchRoute(String path) { + RouteTreeResult? matchRoute(final String path) { final matchResult = matcher.matchRoute(path); if (matchResult != null) { final route = tree[matchResult.node.originalPath]; @@ -187,6 +187,9 @@ class RouteTree { /// A class representing the result of a route matching operation. class MatchResult { + + MatchResult(this.node, this.parameters, this.currentPath, + {this.urlParameters = const {}}); /// The route found that matches the result final RouteNode node; @@ -199,9 +202,6 @@ class MatchResult { /// Route url parameters eg: adding 'user' the match result for 'user?foo=bar' will be: {foo: bar} final Map urlParameters; - MatchResult(this.node, this.parameters, this.currentPath, - {this.urlParameters = const {}}); - @override String toString() => 'MatchResult(node: $node, currentPath: $currentPath, parameters: $parameters, urlParameters: $urlParameters)'; @@ -209,13 +209,13 @@ class MatchResult { // A class representing a node in a routing tree. class RouteNode { + + RouteNode(this.path, this.originalPath, {this.parent}); String path; String originalPath; RouteNode? parent; List nodeSegments = []; - RouteNode(this.path, this.originalPath, {this.parent}); - bool get isRoot => parent == null; String get fullPath { @@ -229,16 +229,16 @@ class RouteNode { bool get hasChildren => nodeSegments.isNotEmpty; - void addChild(RouteNode child) { + void addChild(final RouteNode child) { nodeSegments.add(child); child.parent = this; } - RouteNode? findChild(String name) { - return nodeSegments.firstWhereOrNull((node) => node.path == name); + RouteNode? findChild(final String name) { + return nodeSegments.firstWhereOrNull((final node) => node.path == name); } - bool matches(String name) { + bool matches(final String name) { return name == path || path == '*' || path.startsWith(':'); } @@ -248,8 +248,8 @@ class RouteNode { } extension Foo on Iterable { - T? firstWhereOrNull(bool Function(T element) test) { - for (var element in this) { + T? firstWhereOrNull(final bool Function(T element) test) { + for (final element in this) { if (test(element)) return element; } return null; diff --git a/lib/get_navigation/src/routes/observers/route_observer.dart b/lib/get_navigation/src/routes/observers/route_observer.dart index 205cd2e83..852d51b83 100644 --- a/lib/get_navigation/src/routes/observers/route_observer.dart +++ b/lib/get_navigation/src/routes/observers/route_observer.dart @@ -8,7 +8,7 @@ import '../../router_report.dart'; /// Extracts the name of a route based on it's instance type /// or null if not possible. -String? _extractRouteName(Route? route) { +String? _extractRouteName(final Route? route) { if (route?.settings.name != null) { return route!.settings.name; } @@ -29,14 +29,14 @@ String? _extractRouteName(Route? route) { } class GetObserver extends NavigatorObserver { + + GetObserver([this.routing, this._routeSend]); final Function(Routing?)? routing; final Routing? _routeSend; - GetObserver([this.routing, this._routeSend]); - @override - void didPop(Route route, Route? previousRoute) { + void didPop(final Route route, final Route? previousRoute) { super.didPop(route, previousRoute); final currentRoute = _RouteData.ofRoute(route); final newRoute = _RouteData.ofRoute(previousRoute); @@ -47,9 +47,9 @@ class GetObserver extends NavigatorObserver { // } else if (currentRoute.isBottomSheet || currentRoute.isDialog) { - Get.log("CLOSE ${currentRoute.name}"); + Get.log('CLOSE ${currentRoute.name}'); } else if (currentRoute.isGetPageRoute) { - Get.log("CLOSE TO ROUTE ${currentRoute.name}"); + Get.log('CLOSE TO ROUTE ${currentRoute.name}'); } if (previousRoute != null) { RouterReportManager.instance.reportCurrentRoute(previousRoute); @@ -58,7 +58,7 @@ class GetObserver extends NavigatorObserver { // Here we use a 'inverse didPush set', meaning that we use // previous route instead of 'route' because this is // a 'inverse push' - _routeSend?.update((value) { + _routeSend?.update((final value) { // Only PageRoute is allowed to change current value if (previousRoute is PageRoute) { value.current = _extractRouteName(previousRoute) ?? ''; @@ -82,7 +82,7 @@ class GetObserver extends NavigatorObserver { } @override - void didPush(Route route, Route? previousRoute) { + void didPush(final Route route, final Route? previousRoute) { super.didPush(route, previousRoute); final newRoute = _RouteData.ofRoute(route); @@ -92,13 +92,13 @@ class GetObserver extends NavigatorObserver { // } else if (newRoute.isBottomSheet || newRoute.isDialog) { - Get.log("OPEN ${newRoute.name}"); + Get.log('OPEN ${newRoute.name}'); } else if (newRoute.isGetPageRoute) { - Get.log("GOING TO ROUTE ${newRoute.name}"); + Get.log('GOING TO ROUTE ${newRoute.name}'); } RouterReportManager.instance.reportCurrentRoute(route); - _routeSend!.update((value) { + _routeSend!.update((final value) { // Only PageRoute is allowed to change current value if (route is PageRoute) { value.current = newRoute.name ?? ''; @@ -123,14 +123,14 @@ class GetObserver extends NavigatorObserver { } @override - void didRemove(Route route, Route? previousRoute) { + void didRemove(final Route route, final Route? previousRoute) { super.didRemove(route, previousRoute); final routeName = _extractRouteName(route); final currentRoute = _RouteData.ofRoute(route); - Get.log("REMOVING ROUTE $routeName"); + Get.log('REMOVING ROUTE $routeName'); - _routeSend?.update((value) { + _routeSend?.update((final value) { value.route = previousRoute; value.isBack = false; value.removed = routeName ?? ''; @@ -148,20 +148,20 @@ class GetObserver extends NavigatorObserver { } @override - void didReplace({Route? newRoute, Route? oldRoute}) { + void didReplace({final Route? newRoute, final Route? oldRoute}) { super.didReplace(newRoute: newRoute, oldRoute: oldRoute); final newName = _extractRouteName(newRoute); final oldName = _extractRouteName(oldRoute); final currentRoute = _RouteData.ofRoute(oldRoute); - Get.log("REPLACE ROUTE $oldName"); - Get.log("NEW ROUTE $newName"); + Get.log('REPLACE ROUTE $oldName'); + Get.log('NEW ROUTE $newName'); if (newRoute != null) { RouterReportManager.instance.reportCurrentRoute(newRoute); } - _routeSend?.update((value) { + _routeSend?.update((final value) { // Only PageRoute is allowed to change current value if (newRoute is PageRoute) { value.current = newName ?? ''; @@ -187,15 +187,6 @@ class GetObserver extends NavigatorObserver { //TODO: Use copyWith, and remove mutate variables class Routing { - String current; - String previous; - dynamic args; - String removed; - Route? route; - bool? isBack; - // bool? isSnackbar; - bool? isBottomSheet; - bool? isDialog; Routing({ this.current = '', @@ -208,18 +199,23 @@ class Routing { this.isBottomSheet, this.isDialog, }); + String current; + String previous; + dynamic args; + String removed; + Route? route; + bool? isBack; + // bool? isSnackbar; + bool? isBottomSheet; + bool? isDialog; - void update(void Function(Routing value) fn) { + void update(final void Function(Routing value) fn) { fn(this); } } /// This is basically a util for rules about 'what a route is' class _RouteData { - final bool isGetPageRoute; - final bool isBottomSheet; - final bool isDialog; - final String? name; _RouteData({ required this.name, @@ -228,7 +224,7 @@ class _RouteData { required this.isDialog, }); - factory _RouteData.ofRoute(Route? route) { + factory _RouteData.ofRoute(final Route? route) { return _RouteData( name: _extractRouteName(route), isGetPageRoute: route is GetPageRoute, @@ -236,4 +232,8 @@ class _RouteData { isBottomSheet: route is GetModalBottomSheetRoute, ); } + final bool isGetPageRoute; + final bool isBottomSheet; + final bool isDialog; + final String? name; } diff --git a/lib/get_navigation/src/routes/page_settings.dart b/lib/get_navigation/src/routes/page_settings.dart index 80a5ae472..02eab915d 100644 --- a/lib/get_navigation/src/routes/page_settings.dart +++ b/lib/get_navigation/src/routes/page_settings.dart @@ -51,7 +51,7 @@ extension PageArgExt on BuildContext { class PageSettings extends RouteSettings { PageSettings( this.uri, [ - Object? arguments, + final Object? arguments, ]) : super(arguments: arguments); @override @@ -73,8 +73,8 @@ class PageSettings extends RouteSettings { String toString() => name; PageSettings copy({ - Uri? uri, - Object? arguments, + final Uri? uri, + final Object? arguments, }) { return PageSettings( uri ?? this.uri, @@ -83,7 +83,7 @@ class PageSettings extends RouteSettings { } @override - bool operator ==(Object other) { + bool operator ==(final Object other) { if (identical(this, other)) return true; return other is PageSettings && diff --git a/lib/get_navigation/src/routes/parse_route.dart b/lib/get_navigation/src/routes/parse_route.dart index 7c28103af..3adf32a6e 100644 --- a/lib/get_navigation/src/routes/parse_route.dart +++ b/lib/get_navigation/src/routes/parse_route.dart @@ -8,14 +8,12 @@ class RouteDecoder { this.currentTreeBranch, this.pageSettings, ); - final List currentTreeBranch; - final PageSettings? pageSettings; - factory RouteDecoder.fromRoute(String location) { - var uri = Uri.parse(location); + factory RouteDecoder.fromRoute(final String location) { + final uri = Uri.parse(location); final args = PageSettings(uri); final decoder = - (Get.rootController.rootDelegate).matchRoute(location, arguments: args); + Get.rootController.rootDelegate.matchRoute(location, arguments: args); decoder.route = decoder.route?.copyWith( completer: null, arguments: args, @@ -23,14 +21,16 @@ class RouteDecoder { ); return decoder; } + final List currentTreeBranch; + final PageSettings? pageSettings; GetPage? get route => currentTreeBranch.isEmpty ? null : currentTreeBranch.last; - GetPage routeOrUnknown(GetPage onUnknow) => + GetPage routeOrUnknown(final GetPage onUnknow) => currentTreeBranch.isEmpty ? onUnknow : currentTreeBranch.last; - set route(GetPage? getPage) { + set route(final GetPage? getPage) { if (getPage == null) return; if (currentTreeBranch.isEmpty) { currentTreeBranch.add(getPage); @@ -56,7 +56,7 @@ class RouteDecoder { } } - void replaceArguments(Object? arguments) { + void replaceArguments(final Object? arguments) { final newRoute = route; if (newRoute != null) { final index = currentTreeBranch.indexOf(newRoute); @@ -65,7 +65,7 @@ class RouteDecoder { } @override - bool operator ==(Object other) { + bool operator ==(final Object other) { if (identical(this, other)) return true; return other is RouteDecoder && @@ -88,14 +88,14 @@ class ParseRouteTree { final List routes; - RouteDecoder matchRoute(String name, {PageSettings? arguments}) { + RouteDecoder matchRoute(final String name, {final PageSettings? arguments}) { final uri = Uri.parse(name); - final split = uri.path.split('/').where((element) => element.isNotEmpty); + final split = uri.path.split('/').where((final element) => element.isNotEmpty); var curPath = '/'; final cumulativePaths = [ '/', ]; - for (var item in split) { + for (final item in split) { if (curPath.endsWith('/')) { curPath += item; } else { @@ -105,11 +105,11 @@ class ParseRouteTree { } final treeBranch = cumulativePaths - .map((e) => MapEntry(e, _findRoute(e))) - .where((element) => element.value != null) + .map((final e) => MapEntry(e, _findRoute(e))) + .where((final element) => element.value != null) ///Prevent page be disposed - .map((e) => MapEntry(e.key, e.value!.copyWith(key: ValueKey(e.key)))) + .map((final e) => MapEntry(e.key, e.value!.copyWith(key: ValueKey(e.key)))) .toList(); final params = Map.from(uri.queryParameters); @@ -123,7 +123,7 @@ class ParseRouteTree { //copy parameters to all pages. final mappedTreeBranch = treeBranch .map( - (e) => e.value.copyWith( + (final e) => e.value.copyWith( parameters: { if (e.value.parameters != null) ...e.value.parameters!, ...params, @@ -145,47 +145,47 @@ class ParseRouteTree { //route not found return RouteDecoder( - treeBranch.map((e) => e.value).toList(), + treeBranch.map((final e) => e.value).toList(), arguments, ); } - void addRoutes(List> getPages) { + void addRoutes(final List> getPages) { for (final route in getPages) { addRoute(route); } } - void removeRoutes(List> getPages) { + void removeRoutes(final List> getPages) { for (final route in getPages) { removeRoute(route); } } - void removeRoute(GetPage route) { + void removeRoute(final GetPage route) { routes.remove(route); - for (var page in _flattenPage(route)) { + for (final page in _flattenPage(route)) { removeRoute(page); } } - void addRoute(GetPage route) { + void addRoute(final GetPage route) { routes.add(route); // Add Page children. - for (var page in _flattenPage(route)) { + for (final page in _flattenPage(route)) { addRoute(page); } } - List _flattenPage(GetPage route) { + List _flattenPage(final GetPage route) { final result = []; if (route.children.isEmpty) { return result; } final parentPath = route.name; - for (var page in route.children) { + for (final page in route.children) { // Add Parent middlewares to children final parentMiddlewares = [ if (page.middlewares.isNotEmpty) ...page.middlewares, @@ -214,7 +214,7 @@ class ParseRouteTree { ); final children = _flattenPage(page); - for (var child in children) { + for (final child in children) { result.add(_addChild( child, parentPath, @@ -239,11 +239,11 @@ class ParseRouteTree { /// Change the Path for a [GetPage] GetPage _addChild( - GetPage origin, - String parentPath, - List middlewares, - List bindings, - List binds, + final GetPage origin, + final String parentPath, + final List middlewares, + final List bindings, + final List binds, ) { return origin.copyWith( middlewares: middlewares, @@ -256,17 +256,17 @@ class ParseRouteTree { ); } - GetPage? _findRoute(String name) { + GetPage? _findRoute(final String name) { final value = routes.firstWhereOrNull( - (route) => route.path.regex.hasMatch(name), + (final route) => route.path.regex.hasMatch(name), ); return value; } - Map _parseParams(String path, PathDecoded routePath) { + Map _parseParams(String path, final PathDecoded routePath) { final params = {}; - var idx = path.indexOf('?'); + final idx = path.indexOf('?'); if (idx > -1) { path = path.substring(0, idx); final uri = Uri.tryParse(path); @@ -274,10 +274,10 @@ class ParseRouteTree { params.addAll(uri.queryParameters); } } - var paramsMatch = routePath.regex.firstMatch(path); + final paramsMatch = routePath.regex.firstMatch(path); for (var i = 0; i < routePath.keys.length; i++) { - var param = Uri.decodeQueryComponent(paramsMatch![i + 1]!); + final param = Uri.decodeQueryComponent(paramsMatch![i + 1]!); params[routePath.keys[i]!] = param; } return params; @@ -286,8 +286,8 @@ class ParseRouteTree { extension FirstWhereOrNullExt on List { /// The first element satisfying [test], or `null` if there are none. - T? firstWhereOrNull(bool Function(T element) test) { - for (var element in this) { + T? firstWhereOrNull(final bool Function(T element) test) { + for (final element in this) { if (test(element)) return element; } return null; diff --git a/lib/get_navigation/src/routes/route_middleware.dart b/lib/get_navigation/src/routes/route_middleware.dart index 24294cbbc..d963ff2a5 100644 --- a/lib/get_navigation/src/routes/route_middleware.dart +++ b/lib/get_navigation/src/routes/route_middleware.dart @@ -33,7 +33,7 @@ abstract class _RouteMiddleware { /// } /// ``` /// {@end-tool} - RouteSettings? redirect(String route); + RouteSettings? redirect(final String route); /// Similar to [redirect], /// This function will be called when the router delegate changes the @@ -52,7 +52,7 @@ abstract class _RouteMiddleware { /// } /// ``` /// {@end-tool} - FutureOr redirectDelegate(RouteDecoder route); + FutureOr redirectDelegate(final RouteDecoder route); /// This function will be called when this Page is called /// you can use it to change something about the page or give it new page @@ -64,7 +64,7 @@ abstract class _RouteMiddleware { /// } /// ``` /// {@end-tool} - GetPage? onPageCalled(GetPage page); + GetPage? onPageCalled(final GetPage page); /// This function will be called right before the [BindingsInterface] are initialize. /// Here you can change [BindingsInterface] for this page @@ -79,15 +79,15 @@ abstract class _RouteMiddleware { /// } /// ``` /// {@end-tool} - List? onBindingsStart(List bindings); + List? onBindingsStart(final List bindings); /// This function will be called right after the [BindingsInterface] are initialize. - GetPageBuilder? onPageBuildStart(GetPageBuilder page); + GetPageBuilder? onPageBuildStart(final GetPageBuilder page); /// This function will be called right after the /// GetPage.page function is called and will give you the result /// of the function. and take the widget that will be showed. - Widget onPageBuilt(Widget page); + Widget onPageBuilt(final Widget page); void onPageDispose(); } @@ -97,31 +97,31 @@ abstract class _RouteMiddleware { /// (( [redirect] -> [onPageCalled] -> [onBindingsStart] -> /// [onPageBuildStart] -> [onPageBuilt] -> [onPageDispose] )) class GetMiddleware implements _RouteMiddleware { - @override - int? priority = 0; GetMiddleware({this.priority}); + @override + int? priority = 0; @override - RouteSettings? redirect(String? route) => null; + RouteSettings? redirect(final String? route) => null; @override - GetPage? onPageCalled(GetPage? page) => page; + GetPage? onPageCalled(final GetPage? page) => page; @override - List? onBindingsStart(List? bindings) => bindings; + List? onBindingsStart(final List? bindings) => bindings; @override - GetPageBuilder? onPageBuildStart(GetPageBuilder? page) => page; + GetPageBuilder? onPageBuildStart(final GetPageBuilder? page) => page; @override - Widget onPageBuilt(Widget page) => page; + Widget onPageBuilt(final Widget page) => page; @override void onPageDispose() {} @override - FutureOr redirectDelegate(RouteDecoder route) => (route); + FutureOr redirectDelegate(final RouteDecoder route) => route; } class MiddlewareRunner { @@ -133,18 +133,18 @@ class MiddlewareRunner { final newMiddleware = _middlewares ?? []; return List.of(newMiddleware) ..sort( - (a, b) => (a.priority ?? 0).compareTo(b.priority ?? 0), + (final a, final b) => (a.priority ?? 0).compareTo(b.priority ?? 0), ); } GetPage? runOnPageCalled(GetPage? page) { - _getMiddlewares().forEach((element) { + _getMiddlewares().forEach((final element) { page = element.onPageCalled(page); }); return page; } - RouteSettings? runRedirect(String? route) { + RouteSettings? runRedirect(final String? route) { RouteSettings? to; for (final element in _getMiddlewares()) { to = element.redirect(route); @@ -157,36 +157,32 @@ class MiddlewareRunner { } List? runOnBindingsStart(List? bindings) { - _getMiddlewares().forEach((element) { + _getMiddlewares().forEach((final element) { bindings = element.onBindingsStart(bindings); }); return bindings; } GetPageBuilder? runOnPageBuildStart(GetPageBuilder? page) { - _getMiddlewares().forEach((element) { + _getMiddlewares().forEach((final element) { page = element.onPageBuildStart(page); }); return page; } Widget runOnPageBuilt(Widget page) { - _getMiddlewares().forEach((element) { + _getMiddlewares().forEach((final element) { page = element.onPageBuilt(page); }); return page; } void runOnPageDispose() { - _getMiddlewares().forEach((element) => element.onPageDispose()); + _getMiddlewares().forEach((final element) => element.onPageDispose()); } } class PageRedirect { - GetPage? route; - GetPage? unknownRoute; - RouteSettings? settings; - bool isUnknown; PageRedirect({ this.route, @@ -194,10 +190,14 @@ class PageRedirect { this.isUnknown = false, this.settings, }); + GetPage? route; + GetPage? unknownRoute; + RouteSettings? settings; + bool isUnknown; // redirect all pages that needes redirecting GetPageRoute getPageToRoute( - GetPage rou, GetPage? unk, BuildContext context) { + final GetPage rou, final GetPage? unk, final BuildContext context) { while (needRecheck(context)) {} final r = (isUnknown ? unk : rou)!; @@ -230,7 +230,7 @@ class PageRedirect { } /// check if redirect is needed - bool needRecheck(BuildContext context) { + bool needRecheck(final BuildContext context) { if (settings == null && route != null) { settings = route; } @@ -259,7 +259,7 @@ class PageRedirect { return true; } - void addPageParameter(GetPage route) { + void addPageParameter(final GetPage route) { if (route.parameters == null) return; final parameters = Map.from(Get.parameters); diff --git a/lib/get_navigation/src/routes/route_report.dart b/lib/get_navigation/src/routes/route_report.dart index c0007929a..d245f0efb 100644 --- a/lib/get_navigation/src/routes/route_report.dart +++ b/lib/get_navigation/src/routes/route_report.dart @@ -4,7 +4,7 @@ import '../router_report.dart'; import 'default_route.dart'; class RouteReport extends StatefulWidget { - const RouteReport({Key? key, required this.builder}) : super(key: key); + const RouteReport({required this.builder, super.key}); final WidgetBuilder builder; @override @@ -25,7 +25,7 @@ class RouteReportState extends State with RouteReportMixin { } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return widget.builder(context); } } diff --git a/lib/get_navigation/src/routes/router_outlet.dart b/lib/get_navigation/src/routes/router_outlet.dart index f0fa96a2c..9b056f2fb 100644 --- a/lib/get_navigation/src/routes/router_outlet.dart +++ b/lib/get_navigation/src/routes/router_outlet.dart @@ -4,26 +4,16 @@ import '../../../get.dart'; class RouterOutlet, T extends Object> extends StatefulWidget { - final TDelegate routerDelegate; - final Widget Function(BuildContext context) builder; - - RouterOutlet.builder({ - super.key, - TDelegate? delegate, - required this.builder, - }) : routerDelegate = delegate ?? Get.delegate()!; RouterOutlet({ - Key? key, - TDelegate? delegate, - required Iterable Function(T currentNavStack) pickPages, - required Widget Function( + required final Iterable Function(T currentNavStack) pickPages, required final Widget Function( BuildContext context, TDelegate, Iterable? page, - ) pageBuilder, + ) pageBuilder, final Key? key, + final TDelegate? delegate, }) : this.builder( - builder: (context) { + builder: (final context) { final currentConfig = context.delegate.currentConfiguration as T?; final rDelegate = context.delegate as TDelegate; var picked = @@ -35,6 +25,13 @@ class RouterOutlet, T extends Object> }, delegate: delegate, key: key); + + RouterOutlet.builder({ + required this.builder, super.key, + final TDelegate? delegate, + }) : routerDelegate = delegate ?? Get.delegate()!; + final TDelegate routerDelegate; + final Widget Function(BuildContext context) builder; @override RouterOutletState createState() => RouterOutletState(); @@ -71,7 +68,7 @@ class RouterOutletState, T extends Object> } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { _backButtonDispatcher.takePriority(); return widget.builder(context); } @@ -79,15 +76,14 @@ class RouterOutletState, T extends Object> class GetRouterOutlet extends RouterOutlet { GetRouterOutlet({ - Key? key, - String? anchorRoute, - required String initialRoute, - Iterable Function(Iterable afterAnchor)? filterPages, - GetDelegate? delegate, - String? restorationScopeId, + required final String initialRoute, final Key? key, + final String? anchorRoute, + final Iterable Function(Iterable afterAnchor)? filterPages, + final GetDelegate? delegate, + final String? restorationScopeId, }) : this.pickPages( restorationScopeId: restorationScopeId, - pickPages: (config) { + pickPages: (final config) { Iterable> ret; if (anchorRoute == null) { // jump the ancestor path @@ -105,22 +101,21 @@ class GetRouterOutlet extends RouterOutlet { return ret; }, key: key, - emptyPage: (delegate) => + emptyPage: (final delegate) => delegate.matchRoute(initialRoute).route ?? delegate.notFoundRoute, navigatorKey: Get.nestedKey(anchorRoute)?.navigatorKey, delegate: delegate, ); GetRouterOutlet.pickPages({ - super.key, - Widget Function(GetDelegate delegate)? emptyWidget, - GetPage Function(GetDelegate delegate)? emptyPage, - required Iterable Function(RouteDecoder currentNavStack) pickPages, - bool Function(Route, dynamic)? onPopPage, - String? restorationScopeId, - GlobalKey? navigatorKey, - GetDelegate? delegate, + required super.pickPages, super.key, + final Widget Function(GetDelegate delegate)? emptyWidget, + final GetPage Function(GetDelegate delegate)? emptyPage, + final bool Function(Route, dynamic)? onPopPage, + final String? restorationScopeId, + final GlobalKey? navigatorKey, + final GetDelegate? delegate, }) : super( - pageBuilder: (context, rDelegate, pages) { + pageBuilder: (final context, final rDelegate, final pages) { final pageRes = [ ...?pages, if (pages == null || pages.isEmpty) emptyPage?.call(rDelegate), @@ -133,7 +128,7 @@ class GetRouterOutlet extends RouterOutlet { child: GetNavigator( restorationScopeId: restorationScopeId, onPopPage: onPopPage ?? - (route, result) { + (final route, final result) { final didPop = route.didPop(result); if (!didPop) { return false; @@ -145,21 +140,16 @@ class GetRouterOutlet extends RouterOutlet { ), ); } - return (emptyWidget?.call(rDelegate) ?? const SizedBox.shrink()); + return emptyWidget?.call(rDelegate) ?? const SizedBox.shrink(); }, - pickPages: pickPages, delegate: delegate ?? Get.rootController.rootDelegate, ); GetRouterOutlet.builder({ - super.key, - required Widget Function( - BuildContext context, - ) builder, - String? route, - GetDelegate? routerDelegate, + required super.builder, super.key, + final String? route, + final GetDelegate? routerDelegate, }) : super.builder( - builder: builder, delegate: routerDelegate ?? (route != null ? Get.nestedKey(route) @@ -169,18 +159,16 @@ class GetRouterOutlet extends RouterOutlet { class InheritedNavigator extends InheritedWidget { const InheritedNavigator({ - super.key, - required super.child, - required this.navigatorKey, + required super.child, required this.navigatorKey, super.key, }); final GlobalKey navigatorKey; - static InheritedNavigator? of(BuildContext context) { + static InheritedNavigator? of(final BuildContext context) { return context.dependOnInheritedWidgetOfExactType(); } @override - bool updateShouldNotify(InheritedNavigator oldWidget) { + bool updateShouldNotify(final InheritedNavigator oldWidget) { return true; } } @@ -193,12 +181,12 @@ extension NavKeyExt on BuildContext { extension PagesListExt on List { /// Returns the route and all following routes after the given route. - Iterable pickFromRoute(String route) { - return skipWhile((value) => value.name != route); + Iterable pickFromRoute(final String route) { + return skipWhile((final value) => value.name != route); } /// Returns the routes after the given route. - Iterable pickAfterRoute(String route) { + Iterable pickAfterRoute(final String route) { // If the provided route is root, we take the first route after root. if (route == '/') { return pickFromRoute(route).skip(1).take(1); @@ -213,15 +201,13 @@ typedef NavigatorItemBuilderBuilder = Widget Function( class IndexedRouteBuilder extends StatelessWidget { const IndexedRouteBuilder({ - Key? key, - required this.builder, - required this.routes, - }) : super(key: key); + required this.builder, required this.routes, super.key, + }); final List routes; final NavigatorItemBuilderBuilder builder; // Method to get the current index based on the route - int _getCurrentIndex(String currentLocation) { + int _getCurrentIndex(final String currentLocation) { for (int i = 0; i < routes.length; i++) { if (currentLocation.startsWith(routes[i])) { return i; @@ -231,7 +217,7 @@ class IndexedRouteBuilder extends StatelessWidget { } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { final location = context.location; final index = _getCurrentIndex(location); @@ -268,26 +254,24 @@ mixin RouterListenerMixin on State { class RouterListenerInherited extends InheritedWidget { const RouterListenerInherited({ - super.key, - required Widget child, - }) : super(child: child); + required super.child, super.key, + }); - static RouterListenerInherited? of(BuildContext context) { + static RouterListenerInherited? of(final BuildContext context) { return context .dependOnInheritedWidgetOfExactType(); } @override - bool updateShouldNotify(covariant InheritedWidget oldWidget) { + bool updateShouldNotify(covariant final InheritedWidget oldWidget) { return true; } } class RouterListener extends StatefulWidget { const RouterListener({ - Key? key, - required this.builder, - }) : super(key: key); + required this.builder, super.key, + }); final WidgetBuilder builder; @override @@ -297,13 +281,13 @@ class RouterListener extends StatefulWidget { class RouteListenerState extends State with RouterListenerMixin { @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return RouterListenerInherited(child: Builder(builder: widget.builder)); } } class BackButtonCallback extends StatefulWidget { - const BackButtonCallback({Key? key, required this.builder}) : super(key: key); + const BackButtonCallback({required this.builder, super.key}); final WidgetBuilder builder; @override @@ -323,7 +307,7 @@ class RouterListenerState extends State } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { backButtonDispatcher.takePriority(); return widget.builder(context); } diff --git a/lib/get_navigation/src/routes/url_strategy/url_strategy.dart b/lib/get_navigation/src/routes/url_strategy/url_strategy.dart index 544b15a99..4a6cb958b 100644 --- a/lib/get_navigation/src/routes/url_strategy/url_strategy.dart +++ b/lib/get_navigation/src/routes/url_strategy/url_strategy.dart @@ -4,6 +4,6 @@ void setUrlStrategy() { removeHash(); } -void removeLastHistory(String? url) { +void removeLastHistory(final String? url) { removeLastHistory(url); } diff --git a/lib/get_navigation/src/snackbar/snackbar.dart b/lib/get_navigation/src/snackbar/snackbar.dart index d51c775e9..c9d7acb7e 100644 --- a/lib/get_navigation/src/snackbar/snackbar.dart +++ b/lib/get_navigation/src/snackbar/snackbar.dart @@ -13,6 +13,46 @@ typedef OnHover = void Function( typedef SnackbarStatusCallback = void Function(SnackbarStatus? status); class GetSnackBar extends StatefulWidget { + + const GetSnackBar({ + super.key, + this.title, + this.message, + this.titleText, + this.messageText, + this.icon, + this.shouldIconPulse = true, + this.maxWidth, + this.margin = const EdgeInsets.all(0.0), + this.padding = const EdgeInsets.all(16), + this.borderRadius = 0.0, + this.borderColor, + this.borderWidth = 1.0, + this.backgroundColor = const Color(0xFF303030), + this.leftBarIndicatorColor, + this.boxShadows, + this.backgroundGradient, + this.mainButton, + this.onTap, + this.onHover, + this.duration, + this.isDismissible = true, + this.dismissDirection, + this.showProgressIndicator = false, + this.progressIndicatorController, + this.progressIndicatorBackgroundColor, + this.progressIndicatorValueColor, + this.snackPosition = SnackPosition.bottom, + this.snackStyle = SnackStyle.floating, + this.forwardAnimationCurve = Curves.easeOutCirc, + this.reverseAnimationCurve = Curves.easeOutCirc, + this.animationDuration = const Duration(seconds: 1), + this.barBlur = 0.0, + this.overlayBlur = 0.0, + this.overlayColor = Colors.transparent, + this.userInputForm, + this.snackbarStatus, + }); /// A callback for you to listen to the different Snack status final SnackbarStatusCallback? snackbarStatus; @@ -165,46 +205,6 @@ class GetSnackBar extends StatefulWidget { /// Every other widget is ignored if this is not null. final Form? userInputForm; - const GetSnackBar({ - Key? key, - this.title, - this.message, - this.titleText, - this.messageText, - this.icon, - this.shouldIconPulse = true, - this.maxWidth, - this.margin = const EdgeInsets.all(0.0), - this.padding = const EdgeInsets.all(16), - this.borderRadius = 0.0, - this.borderColor, - this.borderWidth = 1.0, - this.backgroundColor = const Color(0xFF303030), - this.leftBarIndicatorColor, - this.boxShadows, - this.backgroundGradient, - this.mainButton, - this.onTap, - this.onHover, - this.duration, - this.isDismissible = true, - this.dismissDirection, - this.showProgressIndicator = false, - this.progressIndicatorController, - this.progressIndicatorBackgroundColor, - this.progressIndicatorValueColor, - this.snackPosition = SnackPosition.bottom, - this.snackStyle = SnackStyle.floating, - this.forwardAnimationCurve = Curves.easeOutCirc, - this.reverseAnimationCurve = Curves.easeOutCirc, - this.animationDuration = const Duration(seconds: 1), - this.barBlur = 0.0, - this.overlayBlur = 0.0, - this.overlayColor = Colors.transparent, - this.userInputForm, - this.snackbarStatus, - }) : super(key: key); - @override State createState() => GetSnackBarState(); @@ -259,7 +259,7 @@ class GetSnackBarState extends State } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return Align( heightFactor: 1.0, child: Material( @@ -279,7 +279,7 @@ class GetSnackBarState extends State children: [ FutureBuilder( future: _boxHeightCompleter.future, - builder: (context, snapshot) { + builder: (final context, final snapshot) { if (snapshot.hasData) { if (widget.barBlur == 0) { return _emptyWidget; @@ -338,7 +338,7 @@ class GetSnackBarState extends State ''' You need to either use message[String], or messageText[Widget] or define a userInputForm[Form] in GetSnackbar'''); - _isTitlePresent = (widget.title != null || widget.titleText != null); + _isTitlePresent = widget.title != null || widget.titleText != null; _messageTopMargin = _isTitlePresent ? 6.0 : widget.padding.top; _configureLeftBarFuture(); @@ -357,7 +357,7 @@ You need to either use message[String], or messageText[Widget] or define a userI if (widget.leftBarIndicatorColor != null) { return FutureBuilder( future: _boxHeightCompleter.future, - builder: (buildContext, snapshot) { + builder: (final buildContext, final snapshot) { if (snapshot.hasData) { return Container( color: widget.leftBarIndicatorColor, @@ -376,7 +376,7 @@ You need to either use message[String], or messageText[Widget] or define a userI void _configureLeftBarFuture() { ambiguate(Engine.instance)!.addPostFrameCallback( - (_) { + (final _) { final keyContext = _backgroundBoxKey.currentContext; if (keyContext != null) { final box = keyContext.findRenderObject() as RenderBox; @@ -406,7 +406,7 @@ You need to either use message[String], or messageText[Widget] or define a userI ), ); - _fadeController!.addStatusListener((status) { + _fadeController!.addStatusListener((final status) { if (status == AnimationStatus.completed) { _fadeController!.reverse(); } @@ -473,17 +473,14 @@ You need to either use message[String], or messageText[Widget] or define a userI child: Column( mainAxisSize: MainAxisSize.min, children: [ - widget.showProgressIndicator - ? LinearProgressIndicator( + if (widget.showProgressIndicator) LinearProgressIndicator( value: widget.progressIndicatorController != null ? _progressAnimation.value : null, backgroundColor: widget.progressIndicatorBackgroundColor, valueColor: widget.progressIndicatorValueColor, - ) - : _emptyWidget, + ) else _emptyWidget, Row( - mainAxisSize: MainAxisSize.max, children: [ _buildLeftBarIndicator(), if (_rowStyle == RowStyle.icon || _rowStyle == RowStyle.all) @@ -493,7 +490,6 @@ You need to either use message[String], or messageText[Widget] or define a userI child: _getIcon(), ), Expanded( - flex: 1, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, @@ -507,7 +503,7 @@ You need to either use message[String], or messageText[Widget] or define a userI ), child: widget.titleText ?? Text( - widget.title ?? "", + widget.title ?? '', style: const TextStyle( fontSize: 16.0, color: Colors.white, @@ -526,7 +522,7 @@ You need to either use message[String], or messageText[Widget] or define a userI ), child: widget.messageText ?? Text( - widget.message ?? "", + widget.message ?? '', style: const TextStyle( fontSize: 14.0, color: Colors.white), ), diff --git a/lib/get_navigation/src/snackbar/snackbar_controller.dart b/lib/get_navigation/src/snackbar/snackbar_controller.dart index 54a4c54ac..479d414e6 100644 --- a/lib/get_navigation/src/snackbar/snackbar_controller.dart +++ b/lib/get_navigation/src/snackbar/snackbar_controller.dart @@ -7,6 +7,8 @@ import 'package:flutter/material.dart'; import '../../../get.dart'; class SnackbarController { + + SnackbarController(this.snackbar); static final _snackBarQueue = _SnackBarQueue(); static bool get isSnackbarBeingShown => _snackBarQueue._isJobInProgress; final key = GlobalKey(); @@ -42,12 +44,10 @@ class SnackbarController { OverlayState? _overlayState; - SnackbarController(this.snackbar); - Future get future => _transitionCompleter.future; /// Close the snackbar with animation - Future close({bool withAnimations = true}) async { + Future close({final bool withAnimations = true}) async { if (!withAnimations) { _removeOverlay(); return; @@ -70,7 +70,7 @@ class SnackbarController { } // ignore: avoid_returning_this - void _configureAlignment(SnackPosition snackPosition) { + void _configureAlignment(final SnackPosition snackPosition) { switch (snackbar.snackPosition) { case SnackPosition.top: { @@ -187,11 +187,11 @@ class SnackbarController { ); } - Iterable _createOverlayEntries(Widget child) { + Iterable _createOverlayEntries(final Widget child) { return [ if (snackbar.overlayBlur > 0.0) ...[ OverlayEntry( - builder: (context) => GestureDetector( + builder: (final context) => GestureDetector( onTap: () { if (snackbar.isDismissible && !_onTappedDismiss) { _onTappedDismiss = true; @@ -200,7 +200,7 @@ class SnackbarController { }, child: AnimatedBuilder( animation: _filterBlurAnimation, - builder: (context, child) { + builder: (final context, final child) { return BackdropFilter( filter: ImageFilter.blur( sigmaX: max(0.001, _filterBlurAnimation.value), @@ -214,12 +214,10 @@ class SnackbarController { }, ), ), - maintainState: false, - opaque: false, ), ], OverlayEntry( - builder: (context) => Semantics( + builder: (final context) => Semantics( focused: false, container: true, explicitChildNodes: true, @@ -230,18 +228,16 @@ class SnackbarController { : _getSnackbarContainer(child), ), ), - maintainState: false, - opaque: false, ), ]; } Widget _getBodyWidget() { - return Builder(builder: (_) { + return Builder(builder: (final _) { return MouseRegion( - onEnter: (_) => + onEnter: (final _) => snackbar.onHover?.call(snackbar, SnackHoverState.entered), - onExit: (_) => snackbar.onHover?.call(snackbar, SnackHoverState.exited), + onExit: (final _) => snackbar.onHover?.call(snackbar, SnackHoverState.exited), child: GestureDetector( onTap: snackbar.onTap != null ? () => snackbar.onTap?.call(snackbar) @@ -259,11 +255,11 @@ class SnackbarController { return DismissDirection.down; } - Widget _getDismissibleSnack(Widget child) { + Widget _getDismissibleSnack(final Widget child) { return Dismissible( direction: snackbar.dismissDirection ?? _getDefaultDismissDirection(), resizeDuration: null, - confirmDismiss: (_) { + confirmDismiss: (final _) { if (_currentStatus == SnackbarStatus.opening || _currentStatus == SnackbarStatus.closing) { return Future.value(false); @@ -271,7 +267,7 @@ class SnackbarController { return Future.value(true); }, key: const Key('dismissible'), - onDismissed: (_) { + onDismissed: (final _) { _wasDismissedBySwipe = true; _removeEntry(); }, @@ -279,14 +275,14 @@ class SnackbarController { ); } - Widget _getSnackbarContainer(Widget child) { + Widget _getSnackbarContainer(final Widget child) { return Container( margin: snackbar.margin, child: child, ); } - void _handleStatusChanged(AnimationStatus status) { + void _handleStatusChanged(final AnimationStatus status) { switch (status) { case AnimationStatus.completed: _currentStatus = SnackbarStatus.open; @@ -330,7 +326,7 @@ class SnackbarController { void _removeOverlay() { if (!_isTesting) { - for (var element in _overlayEntries) { + for (final element in _overlayEntries) { element.remove(); } } @@ -367,7 +363,7 @@ class _SnackBarQueue { bool get _isJobInProgress => _snackbarList.isNotEmpty; - Future _addJob(SnackbarController job) async { + Future _addJob(final SnackbarController job) async { _snackbarList.add(job); final data = await _queue.add(job._show); _snackbarList.remove(job); diff --git a/lib/get_rx/src/rx_workers/rx_workers.dart b/lib/get_rx/src/rx_workers/rx_workers.dart index b7b02fbb6..592ad8c65 100644 --- a/lib/get_rx/src/rx_workers/rx_workers.dart +++ b/lib/get_rx/src/rx_workers/rx_workers.dart @@ -5,7 +5,7 @@ import '../../../get_state_manager/src/rx_flutter/rx_notifier.dart'; import '../rx_types/rx_types.dart'; import 'utils/debouncer.dart'; -bool _conditional(dynamic condition) { +bool _conditional(final dynamic condition) { if (condition == null) return true; if (condition is bool) return condition; if (condition is bool Function()) return condition(); @@ -58,15 +58,15 @@ class Workers { /// } /// ``` Worker ever( - GetListenable listener, - WorkerCallback callback, { - dynamic condition = true, - Function? onError, - void Function()? onDone, - bool? cancelOnError, + final GetListenable listener, + final WorkerCallback callback, { + final dynamic condition = true, + final Function? onError, + final void Function()? onDone, + final bool? cancelOnError, }) { - StreamSubscription sub = listener.listen( - (event) { + final StreamSubscription sub = listener.listen( + (final event) { if (_conditional(condition)) callback(event); }, onError: onError, @@ -81,17 +81,17 @@ Worker ever( /// and the [callback] is executed to each one of them. The [Worker] is /// common to all, so `worker.dispose()` will cancel all streams. Worker everAll( - List listeners, - WorkerCallback callback, { - dynamic condition = true, - Function? onError, - void Function()? onDone, - bool? cancelOnError, + final List listeners, + final WorkerCallback callback, { + final dynamic condition = true, + final Function? onError, + final void Function()? onDone, + final bool? cancelOnError, }) { final evers = []; - for (var i in listeners) { + for (final i in listeners) { final sub = i.listen( - (event) { + (final event) { if (_conditional(condition)) callback(event); }, onError: onError, @@ -102,7 +102,7 @@ Worker everAll( } Future cancel() async { - for (var i in evers) { + for (final i in evers) { i.cancel(); } } @@ -132,17 +132,17 @@ Worker everAll( /// } ///``` Worker once( - GetListenable listener, - WorkerCallback callback, { - dynamic condition = true, - Function? onError, - void Function()? onDone, - bool? cancelOnError, + final GetListenable listener, + final WorkerCallback callback, { + final dynamic condition = true, + final Function? onError, + final void Function()? onDone, + final bool? cancelOnError, }) { late Worker ref; StreamSubscription? sub; sub = listener.listen( - (event) { + (final event) { if (!_conditional(condition)) return; ref._disposed = true; ref._log('called'); @@ -175,17 +175,17 @@ Worker once( /// ); /// ``` Worker interval( - GetListenable listener, - WorkerCallback callback, { - Duration time = const Duration(seconds: 1), - dynamic condition = true, - Function? onError, - void Function()? onDone, - bool? cancelOnError, + final GetListenable listener, + final WorkerCallback callback, { + final Duration time = const Duration(seconds: 1), + final dynamic condition = true, + final Function? onError, + final void Function()? onDone, + final bool? cancelOnError, }) { var debounceActive = false; - StreamSubscription sub = listener.listen( - (event) async { + final StreamSubscription sub = listener.listen( + (final event) async { if (debounceActive || !_conditional(condition)) return; debounceActive = true; await Future.delayed(time); @@ -219,17 +219,17 @@ Worker interval( /// } /// ``` Worker debounce( - GetListenable listener, - WorkerCallback callback, { - Duration? time, - Function? onError, - void Function()? onDone, - bool? cancelOnError, + final GetListenable listener, + final WorkerCallback callback, { + final Duration? time, + final Function? onError, + final void Function()? onDone, + final bool? cancelOnError, }) { final newDebouncer = Debouncer(delay: time ?? const Duration(milliseconds: 800)); - StreamSubscription sub = listener.listen( - (event) { + final StreamSubscription sub = listener.listen( + (final event) { newDebouncer(() { callback(event); }); @@ -254,7 +254,7 @@ class Worker { bool get disposed => _disposed; //final bool _verbose = true; - void _log(String msg) { + void _log(final String msg) { // if (!_verbose) return; Get.log('$runtimeType $type $msg'); } diff --git a/lib/get_rx/src/rx_workers/utils/debouncer.dart b/lib/get_rx/src/rx_workers/utils/debouncer.dart index c1d3778fb..4152c62bb 100644 --- a/lib/get_rx/src/rx_workers/utils/debouncer.dart +++ b/lib/get_rx/src/rx_workers/utils/debouncer.dart @@ -9,12 +9,12 @@ import 'dart:async'; /// delayed( () => print( 'called after 1 sec' )); /// ``` class Debouncer { - final Duration delay; - Timer? _timer; Debouncer({required this.delay}); + final Duration delay; + Timer? _timer; - void call(void Function() action) { + void call(final void Function() action) { _timer?.cancel(); _timer = Timer(delay, action); } diff --git a/lib/get_state_manager/src/rx_flutter/rx_getx_widget.dart b/lib/get_state_manager/src/rx_flutter/rx_getx_widget.dart index f66610ee3..44281f935 100644 --- a/lib/get_state_manager/src/rx_flutter/rx_getx_widget.dart +++ b/lib/get_state_manager/src/rx_flutter/rx_getx_widget.dart @@ -10,21 +10,10 @@ typedef GetXControllerBuilder = Widget Function( T controller); class GetX extends StatefulWidget { - final GetXControllerBuilder builder; - final bool global; - final bool autoRemove; - final bool assignId; - final void Function(GetXState state)? initState, - dispose, - didChangeDependencies; - final void Function(GetX oldWidget, GetXState state)? didUpdateWidget; - final T? init; - final String? tag; - const GetX({ + required this.builder, super.key, this.tag, - required this.builder, this.global = true, this.autoRemove = true, this.initState, @@ -36,12 +25,22 @@ class GetX extends StatefulWidget { this.init, // this.streamController }); + final GetXControllerBuilder builder; + final bool global; + final bool autoRemove; + final bool assignId; + final void Function(GetXState state)? initState, + dispose, + didChangeDependencies; + final void Function(GetX oldWidget, GetXState state)? didUpdateWidget; + final T? init; + final String? tag; @override StatefulElement createElement() => StatefulElement(this); @override - void debugFillProperties(DiagnosticPropertiesBuilder properties) { + void debugFillProperties(final DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties ..add( @@ -63,7 +62,7 @@ class GetXState extends State> { @override void initState() { // var isPrepared = Get.isPrepared(tag: widget.tag); - final isRegistered = Get.isRegistered(tag: widget.tag); + final bool isRegistered = Get.isRegistered(tag: widget.tag); if (widget.global) { if (isRegistered) { @@ -96,21 +95,23 @@ class GetXState extends State> { } @override - void didUpdateWidget(GetX oldWidget) { - super.didUpdateWidget(oldWidget as GetX); + void didUpdateWidget(final GetX oldWidget) { + super.didUpdateWidget(oldWidget); widget.didUpdateWidget?.call(oldWidget, this); } @override void dispose() { - if (widget.dispose != null) widget.dispose!(this); + if (widget.dispose != null) { + widget.dispose!(this); + } if (_isCreator! || widget.assignId) { if (widget.autoRemove && Get.isRegistered(tag: widget.tag)) { Get.delete(tag: widget.tag); } } - for (final disposer in disposers) { + for (final Disposer disposer in disposers) { disposer(); } @@ -127,15 +128,15 @@ class GetXState extends State> { } } - final disposers = []; + final List disposers = []; @override - Widget build(BuildContext context) => Notifier.instance.append( + Widget build(final BuildContext context) => Notifier.instance.append( NotifyData(disposers: disposers, updater: _update), () => widget.builder(controller!)); @override - void debugFillProperties(DiagnosticPropertiesBuilder properties) { + void debugFillProperties(final DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('controller', controller)); } diff --git a/lib/get_state_manager/src/rx_flutter/rx_notifier.dart b/lib/get_state_manager/src/rx_flutter/rx_notifier.dart index 928111454..c3a994469 100644 --- a/lib/get_state_manager/src/rx_flutter/rx_notifier.dart +++ b/lib/get_state_manager/src/rx_flutter/rx_notifier.dart @@ -2,7 +2,7 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; -import 'package:get/utils.dart'; +import '../../../utils.dart'; import '../../../get_rx/src/rx_types/rx_types.dart'; import '../../../instance_manager.dart'; @@ -42,11 +42,11 @@ mixin StateMixin on ListNotifier { T get state => value; - set status(GetStatus newStatus) { + set status(final GetStatus newStatus) { if (newStatus == status) return; _status = newStatus; if (newStatus is SuccessStatus) { - _value = newStatus.data!; + _value = newStatus.data; } refresh(); } @@ -58,24 +58,24 @@ mixin StateMixin on ListNotifier { } @protected - set value(T newValue) { + set value(final T newValue) { if (_value == newValue) return; _value = newValue; refresh(); } @protected - void change(GetStatus status) { + void change(final GetStatus status) { if (status != this.status) { this.status = status; } } - void futurize(Future Function() body, - {T? initialData, String? errorMessage, bool useEmpty = true}) { + void futurize(final Future Function() body, + {final T? initialData, final String? errorMessage, final bool useEmpty = true}) { final compute = body; _value ??= initialData; - compute().then((newValue) { + compute().then((final newValue) { if ((newValue == null || newValue._isEmpty()) && useEmpty) { status = GetStatus.loading(); } else { @@ -83,7 +83,7 @@ mixin StateMixin on ListNotifier { } refresh(); - }, onError: (err) { + }, onError: (final err) { status = GetStatus.error(errorMessage ?? err.toString()); refresh(); }); @@ -95,7 +95,7 @@ typedef FuturizeCallback = Future Function(VoidCallback fn); typedef VoidCallback = void Function(); class GetListenable extends ListNotifierSingle implements RxInterface { - GetListenable(T val) : _value = val; + GetListenable(final T val) : _value = val; StreamController? _controller; @@ -138,13 +138,13 @@ class GetListenable extends ListNotifierSingle implements RxInterface { refresh(); } - set value(T newValue) { + set value(final T newValue) { if (_value == newValue) return; _value = newValue; _notify(); } - T? call([T? v]) { + T? call([final T? v]) { if (v != null) { value = v; } @@ -153,10 +153,10 @@ class GetListenable extends ListNotifierSingle implements RxInterface { @override StreamSubscription listen( - void Function(T)? onData, { - Function? onError, - void Function()? onDone, - bool? cancelOnError, + final void Function(T)? onData, { + final Function? onError, + final void Function()? onDone, + final bool? cancelOnError, }) => stream.listen( onData, @@ -172,7 +172,7 @@ class GetListenable extends ListNotifierSingle implements RxInterface { class Value extends ListNotifier with StateMixin implements ValueListenable { - Value(T val) { + Value(final T val) { _value = val; _fillInitialStatus(); } @@ -184,20 +184,20 @@ class Value extends ListNotifier } @override - set value(T newValue) { + set value(final T newValue) { if (_value == newValue) return; _value = newValue; refresh(); } - T? call([T? v]) { + T? call([final T? v]) { if (v != null) { value = v; } return value; } - void update(T Function(T? value) fn) { + void update(final T Function(T? value) fn) { value = fn(value); // refresh(); } @@ -211,18 +211,18 @@ class Value extends ListNotifier /// GetNotifier has a native status and state implementation, with the /// Get Lifecycle abstract class GetNotifier extends Value with GetLifeCycleMixin { - GetNotifier(T initial) : super(initial); + GetNotifier(super.initial); } extension StateExt on StateMixin { Widget obx( - NotifierBuilder widget, { - Widget Function(String? error)? onError, - Widget? onLoading, - Widget? onEmpty, - WidgetBuilder? onCustom, + final NotifierBuilder widget, { + final Widget Function(String? error)? onError, + final Widget? onLoading, + final Widget? onEmpty, + final WidgetBuilder? onCustom, }) { - return Observer(builder: (_) { + return Observer(builder: (final _) { if (status.isLoading) { return onLoading ?? const Center(child: CircularProgressIndicator()); } else if (status.isError) { @@ -250,11 +250,11 @@ abstract class GetStatus with Equality { factory GetStatus.loading() => LoadingStatus(); - factory GetStatus.error(String message) => ErrorStatus(message); + factory GetStatus.error(final String message) => ErrorStatus(message); factory GetStatus.empty() => EmptyStatus(); - factory GetStatus.success(T data) => SuccessStatus(data); + factory GetStatus.success(final T data) => SuccessStatus(data); factory GetStatus.custom() => CustomStatus(); } @@ -270,18 +270,18 @@ class LoadingStatus extends GetStatus { } class SuccessStatus extends GetStatus { - final T data; const SuccessStatus(this.data); + final T data; @override List get props => [data]; } class ErrorStatus extends GetStatus { - final S? error; const ErrorStatus([this.error]); + final S? error; @override List get props => [error]; diff --git a/lib/get_state_manager/src/rx_flutter/rx_obx_widget.dart b/lib/get_state_manager/src/rx_flutter/rx_obx_widget.dart index ed553a598..bddcec6b4 100644 --- a/lib/get_state_manager/src/rx_flutter/rx_obx_widget.dart +++ b/lib/get_state_manager/src/rx_flutter/rx_obx_widget.dart @@ -11,7 +11,7 @@ typedef WidgetCallback = Widget Function(); /// - [Obx] /// - [ObxValue] abstract class ObxWidget extends ObxStatelessWidget { - const ObxWidget({Key? key}) : super(key: key); + const ObxWidget({super.key}); } /// The simplest reactive widget in GetX. @@ -22,12 +22,12 @@ abstract class ObxWidget extends ObxStatelessWidget { /// final _name = "GetX".obs; /// Obx(() => Text( _name.value )),... ; class Obx extends ObxWidget { - final WidgetCallback builder; const Obx(this.builder, {super.key}); + final WidgetCallback builder; @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return builder(); } } @@ -44,11 +44,11 @@ class Obx extends ObxWidget { /// false.obs, /// ), class ObxValue extends ObxWidget { + + const ObxValue(this.builder, this.data, {super.key}); final Widget Function(T) builder; final T data; - const ObxValue(this.builder, this.data, {Key? key}) : super(key: key); - @override - Widget build(BuildContext context) => builder(data); + Widget build(final BuildContext context) => builder(data); } diff --git a/lib/get_state_manager/src/rx_flutter/rx_ticket_provider_mixin.dart b/lib/get_state_manager/src/rx_flutter/rx_ticket_provider_mixin.dart index 9f94c2d16..43989b884 100644 --- a/lib/get_state_manager/src/rx_flutter/rx_ticket_provider_mixin.dart +++ b/lib/get_state_manager/src/rx_flutter/rx_ticket_provider_mixin.dart @@ -32,7 +32,7 @@ mixin GetSingleTickerProviderStateMixin on GetxController Ticker? _ticker; @override - Ticker createTicker(TickerCallback onTick) { + Ticker createTicker(final TickerCallback onTick) { assert(() { if (_ticker == null) return true; throw FlutterError.fromParts([ @@ -56,7 +56,7 @@ mixin GetSingleTickerProviderStateMixin on GetxController return _ticker!; } - void didChangeDependencies(BuildContext context) { + void didChangeDependencies(final BuildContext context) { if (_ticker != null) _ticker!.muted = !TickerMode.of(context); } @@ -112,7 +112,7 @@ mixin GetTickerProviderStateMixin on GetxController implements TickerProvider { Set? _tickers; @override - Ticker createTicker(TickerCallback onTick) { + Ticker createTicker(final TickerCallback onTick) { _tickers ??= <_WidgetTicker>{}; final result = _WidgetTicker(onTick, this, debugLabel: kDebugMode ? 'created by ${describeIdentity(this)}' : null); @@ -120,13 +120,13 @@ mixin GetTickerProviderStateMixin on GetxController implements TickerProvider { return result; } - void _removeTicker(_WidgetTicker ticker) { + void _removeTicker(final _WidgetTicker ticker) { assert(_tickers != null); assert(_tickers!.contains(ticker)); _tickers!.remove(ticker); } - void didChangeDependencies(BuildContext context) { + void didChangeDependencies(final BuildContext context) { final muted = !TickerMode.of(context); if (_tickers != null) { for (final ticker in _tickers!) { @@ -165,8 +165,7 @@ mixin GetTickerProviderStateMixin on GetxController implements TickerProvider { } class _WidgetTicker extends Ticker { - _WidgetTicker(TickerCallback onTick, this._creator, {String? debugLabel}) - : super(onTick, debugLabel: debugLabel); + _WidgetTicker(super.onTick, this._creator, {super.debugLabel}); final GetTickerProviderStateMixin _creator; @@ -200,5 +199,5 @@ class _WidgetTicker extends Ticker { mixin SingleGetTickerProviderMixin on GetLifeCycleMixin implements TickerProvider { @override - Ticker createTicker(TickerCallback onTick) => Ticker(onTick); + Ticker createTicker(final TickerCallback onTick) => Ticker(onTick); } diff --git a/lib/get_state_manager/src/simple/get_controllers.dart b/lib/get_state_manager/src/simple/get_controllers.dart index 593012f43..f1529b01e 100644 --- a/lib/get_state_manager/src/simple/get_controllers.dart +++ b/lib/get_state_manager/src/simple/get_controllers.dart @@ -12,7 +12,7 @@ abstract class GetxController extends ListNotifier with GetLifeCycleMixin { /// `GetBuilder( id: )`, /// [ids] can be reused among `GetBuilders` like group tags. /// The update will only notify the Widgets, if [condition] is true. - void update([List? ids, bool condition = true]) { + void update([final List? ids, final bool condition = true]) { if (!condition) { return; } @@ -108,7 +108,7 @@ mixin FullLifeCycleMixin on FullLifeCycleController { @mustCallSuper @override - void didChangeAppLifecycleState(AppLifecycleState state) { + void didChangeAppLifecycleState(final AppLifecycleState state) { switch (state) { case AppLifecycleState.resumed: onResumed(); diff --git a/lib/get_state_manager/src/simple/get_responsive.dart b/lib/get_state_manager/src/simple/get_responsive.dart index 5feec069d..746cad161 100644 --- a/lib/get_state_manager/src/simple/get_responsive.dart +++ b/lib/get_state_manager/src/simple/get_responsive.dart @@ -7,7 +7,7 @@ mixin GetResponsiveMixin on Widget { bool get alwaysUseBuilder; @protected - Widget build(BuildContext context) { + Widget build(final BuildContext context) { screen.context = context; Widget? widget; if (alwaysUseBuilder) { @@ -53,37 +53,40 @@ mixin GetResponsiveMixin on Widget { /// property `alwaysUseBuilder` to false /// With `settings` property you can set the width limit for the screen types. class GetResponsiveView extends GetView with GetResponsiveMixin { + + GetResponsiveView({ + this.alwaysUseBuilder = false, + final ResponsiveScreenSettings settings = const ResponsiveScreenSettings(), + super.key, + }) : screen = ResponsiveScreen(settings); @override final bool alwaysUseBuilder; @override final ResponsiveScreen screen; - - GetResponsiveView({ - this.alwaysUseBuilder = false, - ResponsiveScreenSettings settings = const ResponsiveScreenSettings(), - Key? key, - }) : screen = ResponsiveScreen(settings), - super(key: key); } class GetResponsiveWidget extends GetWidget with GetResponsiveMixin { + + GetResponsiveWidget({ + this.alwaysUseBuilder = false, + final ResponsiveScreenSettings settings = const ResponsiveScreenSettings(), + super.key, + }) : screen = ResponsiveScreen(settings); @override final bool alwaysUseBuilder; @override final ResponsiveScreen screen; - - GetResponsiveWidget({ - this.alwaysUseBuilder = false, - ResponsiveScreenSettings settings = const ResponsiveScreenSettings(), - Key? key, - }) : screen = ResponsiveScreen(settings), - super(key: key); } class ResponsiveScreenSettings { + + const ResponsiveScreenSettings( + {this.desktopChangePoint = 1200, + this.tabletChangePoint = 600, + this.watchChangePoint = 300}); /// When the width is greater als this value /// the display will be set as [ScreenType.Desktop] final double desktopChangePoint; @@ -99,36 +102,31 @@ class ResponsiveScreenSettings { /// or when width greater als this value and smaller als [tabletChangePoint] /// the display will be [ScreenType.Phone] final double watchChangePoint; - - const ResponsiveScreenSettings( - {this.desktopChangePoint = 1200, - this.tabletChangePoint = 600, - this.watchChangePoint = 300}); } class ResponsiveScreen { + ResponsiveScreen(this.settings) { + _isPlatformDesktop = GetPlatform.isDesktop; + } late BuildContext context; final ResponsiveScreenSettings settings; late bool _isPlatformDesktop; - ResponsiveScreen(this.settings) { - _isPlatformDesktop = GetPlatform.isDesktop; - } double get height => context.height; double get width => context.width; /// Is [screenType] [ScreenType.Desktop] - bool get isDesktop => (screenType == ScreenType.desktop); + bool get isDesktop => screenType == ScreenType.desktop; /// Is [screenType] [ScreenType.Tablet] - bool get isTablet => (screenType == ScreenType.tablet); + bool get isTablet => screenType == ScreenType.tablet; /// Is [screenType] [ScreenType.Phone] - bool get isPhone => (screenType == ScreenType.phone); + bool get isPhone => screenType == ScreenType.phone; /// Is [screenType] [ScreenType.Watch] - bool get isWatch => (screenType == ScreenType.watch); + bool get isWatch => screenType == ScreenType.watch; double get _getDeviceWidth { if (_isPlatformDesktop) { @@ -152,10 +150,10 @@ class ResponsiveScreen { /// and if `mobile` object is null the `watch` object will be returned /// also when it is null. T? responsiveValue({ - T? mobile, - T? tablet, - T? desktop, - T? watch, + final T? mobile, + final T? tablet, + final T? desktop, + final T? watch, }) { if (isDesktop && desktop != null) return desktop; if (isTablet && tablet != null) return tablet; diff --git a/lib/get_state_manager/src/simple/get_state.dart b/lib/get_state_manager/src/simple/get_state.dart index cdc4fc6ce..dbcee3e8d 100644 --- a/lib/get_state_manager/src/simple/get_state.dart +++ b/lib/get_state_manager/src/simple/get_state.dart @@ -32,6 +32,21 @@ extension ReadExt on BuildContext { // } class GetBuilder extends StatelessWidget { + const GetBuilder({ + required this.builder, + super.key, + this.init, + this.global = true, + this.autoRemove = true, + this.assignId = false, + this.initState, + this.filter, + this.tag, + this.dispose, + this.id, + this.didChangeDependencies, + this.didUpdateWidget, + }); final GetControllerBuilder builder; final bool global; final Object? id; @@ -46,24 +61,8 @@ class GetBuilder extends StatelessWidget { didUpdateWidget; final T? init; - const GetBuilder({ - Key? key, - this.init, - this.global = true, - required this.builder, - this.autoRemove = true, - this.assignId = false, - this.initState, - this.filter, - this.tag, - this.dispose, - this.id, - this.didChangeDependencies, - this.didUpdateWidget, - }) : super(key: key); - @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return Binder( init: init == null ? null : () => init!, global: global, @@ -77,8 +76,8 @@ class GetBuilder extends StatelessWidget { lazy: false, didChangeDependencies: didChangeDependencies, didUpdateWidget: didUpdateWidget, - child: Builder(builder: (context) { - final controller = Bind.of(context, rebuild: true); + child: Builder(builder: (final BuildContext context) { + final T controller = Bind.of(context, rebuild: true); return builder(controller); }), ); @@ -88,8 +87,8 @@ class GetBuilder extends StatelessWidget { abstract class Bind extends StatelessWidget { const Bind({ - Key? key, required this.child, + super.key, this.init, this.global = true, this.autoRemove = true, @@ -101,7 +100,39 @@ abstract class Bind extends StatelessWidget { this.id, this.didChangeDependencies, this.didUpdateWidget, - }) : super(key: key); + }); + factory Bind.builder({ + final Widget? child, + final InitBuilder? init, + final InstanceCreateBuilderCallback? create, + final bool global = true, + final bool autoRemove = true, + final bool assignId = false, + final Object Function(T value)? filter, + final String? tag, + final Object? id, + final void Function(BindElement state)? initState, + final void Function(BindElement state)? dispose, + final void Function(BindElement state)? didChangeDependencies, + final void Function(Binder oldWidget, BindElement state)? + didUpdateWidget, + }) => + _FactoryBind( + // key: key, + init: init, + create: create, + global: global, + autoRemove: autoRemove, + assignId: assignId, + initState: initState, + filter: filter, + tag: tag, + dispose: dispose, + id: id, + didChangeDependencies: didChangeDependencies, + didUpdateWidget: didUpdateWidget, + child: child, + ); final InitBuilder? init; @@ -120,9 +151,9 @@ abstract class Bind extends StatelessWidget { final Widget? child; static Bind put( - S dependency, { - String? tag, - bool permanent = false, + final S dependency, { + final String? tag, + final bool permanent = false, }) { Get.put(dependency, tag: tag, permanent: permanent); return _FactoryBind( @@ -133,11 +164,11 @@ abstract class Bind extends StatelessWidget { } static Bind lazyPut( - InstanceBuilderCallback builder, { - String? tag, - bool fenix = true, + final InstanceBuilderCallback builder, { + final String? tag, + final bool fenix = true, // VoidCallback? onInit, - VoidCallback? onClose, + final VoidCallback? onClose, }) { Get.lazyPut(builder, tag: tag, fenix: fenix); return _FactoryBind( @@ -145,14 +176,14 @@ abstract class Bind extends StatelessWidget { // initState: (_) { // onInit?.call(); // }, - dispose: (_) { + dispose: (final _) { onClose?.call(); }, ); } - static Bind create(InstanceCreateBuilderCallback builder, - {String? tag, bool permanent = true}) { + static Bind create(final InstanceCreateBuilderCallback builder, + {final String? tag, final bool permanent = true}) { return _FactoryBind( create: builder, tag: tag, @@ -160,8 +191,8 @@ abstract class Bind extends StatelessWidget { ); } - static Bind spawn(InstanceBuilderCallback builder, - {String? tag, bool permanent = true}) { + static Bind spawn(final InstanceBuilderCallback builder, + {final String? tag, final bool permanent = true}) { Get.spawn(builder, tag: tag, permanent: permanent); return _FactoryBind( tag: tag, @@ -170,76 +201,48 @@ abstract class Bind extends StatelessWidget { ); } - static S find({String? tag}) => Get.find(tag: tag); + static S find({final String? tag}) => Get.find(tag: tag); - static Future delete({String? tag, bool force = false}) async => + static Future delete( + {final String? tag, final bool force = false}) async => Get.delete(tag: tag, force: force); - static Future deleteAll({bool force = false}) async => + static Future deleteAll({final bool force = false}) async => Get.deleteAll(force: force); - static void reloadAll({bool force = false}) => Get.reloadAll(force: force); + static void reloadAll({final bool force = false}) => + Get.reloadAll(force: force); - static void reload({String? tag, String? key, bool force = false}) => + static void reload( + {final String? tag, final String? key, final bool force = false}) => Get.reload(tag: tag, key: key, force: force); - static bool isRegistered({String? tag}) => Get.isRegistered(tag: tag); + static bool isRegistered({final String? tag}) => + Get.isRegistered(tag: tag); - static bool isPrepared({String? tag}) => Get.isPrepared(tag: tag); + static bool isPrepared({final String? tag}) => Get.isPrepared(tag: tag); - static void replace

(P child, {String? tag}) { - final info = Get.getInstanceInfo

(tag: tag); - final permanent = (info.isPermanent ?? false); + static void replace

(final P child, {final String? tag}) { + final InstanceInfo info = Get.getInstanceInfo

(tag: tag); + final bool permanent = info.isPermanent ?? false; delete

(tag: tag, force: permanent); Get.put(child, tag: tag, permanent: permanent); } - static void lazyReplace

(InstanceBuilderCallback

builder, - {String? tag, bool? fenix}) { - final info = Get.getInstanceInfo

(tag: tag); - final permanent = (info.isPermanent ?? false); + static void lazyReplace

(final InstanceBuilderCallback

builder, + {final String? tag, final bool? fenix}) { + final InstanceInfo info = Get.getInstanceInfo

(tag: tag); + final bool permanent = info.isPermanent ?? false; delete

(tag: tag, force: permanent); Get.lazyPut(builder, tag: tag, fenix: fenix ?? permanent); } - factory Bind.builder({ - Widget? child, - InitBuilder? init, - InstanceCreateBuilderCallback? create, - bool global = true, - bool autoRemove = true, - bool assignId = false, - Object Function(T value)? filter, - String? tag, - Object? id, - void Function(BindElement state)? initState, - void Function(BindElement state)? dispose, - void Function(BindElement state)? didChangeDependencies, - void Function(Binder oldWidget, BindElement state)? didUpdateWidget, - }) => - _FactoryBind( - // key: key, - init: init, - create: create, - global: global, - autoRemove: autoRemove, - assignId: assignId, - initState: initState, - filter: filter, - tag: tag, - dispose: dispose, - id: id, - didChangeDependencies: didChangeDependencies, - didUpdateWidget: didUpdateWidget, - child: child, - ); - static T of( - BuildContext context, { - bool rebuild = false, + final BuildContext context, { + final bool rebuild = false, // Object Function(T value)? filter, }) { - final inheritedElement = + final BindElement? inheritedElement = context.getElementForInheritedWidgetOfExactType>() as BindElement?; @@ -262,10 +265,26 @@ abstract class Bind extends StatelessWidget { } @factory - Bind _copyWithChild(Widget child); + Bind _copyWithChild(final Widget child); } class _FactoryBind extends Bind { + const _FactoryBind({ + super.key, + this.child, + this.init, + this.create, + this.global = true, + this.autoRemove = true, + this.assignId = false, + this.initState, + this.filter, + this.tag, + this.dispose, + this.id, + this.didChangeDependencies, + this.didUpdateWidget, + }) : super(child: child); @override final InitBuilder? init; @@ -295,25 +314,8 @@ class _FactoryBind extends Bind { @override final Widget? child; - const _FactoryBind({ - Key? key, - this.child, - this.init, - this.create, - this.global = true, - this.autoRemove = true, - this.assignId = false, - this.initState, - this.filter, - this.tag, - this.dispose, - this.id, - this.didChangeDependencies, - this.didUpdateWidget, - }) : super(key: key, child: child); - @override - Bind _copyWithChild(Widget child) { + Bind _copyWithChild(final Widget child) { return Bind.builder( init: init, create: create, @@ -332,7 +334,7 @@ class _FactoryBind extends Bind { } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return Binder( create: create, global: global, @@ -351,19 +353,17 @@ class _FactoryBind extends Bind { } class Binds extends StatelessWidget { - final List> binds; - final Widget child; - Binds({ - Key? key, required this.binds, required this.child, - }) : assert(binds.isNotEmpty), - super(key: key); + super.key, + }) : assert(binds.isNotEmpty); + final List> binds; + final Widget child; @override - Widget build(BuildContext context) => - binds.reversed.fold(child, (widget, e) => e._copyWithChild(widget)); + Widget build(final BuildContext context) => binds.reversed.fold( + child, (final Widget widget, final Bind e) => e._copyWithChild(widget)); } class Binder extends InheritedWidget { @@ -372,8 +372,8 @@ class Binder extends InheritedWidget { /// /// The [child] argument is required const Binder({ - Key? key, - required Widget child, + required super.child, + super.key, this.init, this.global = true, this.autoRemove = true, @@ -387,7 +387,7 @@ class Binder extends InheritedWidget { this.didChangeDependencies, this.didUpdateWidget, this.create, - }) : super(key: key, child: child); + }); final InitBuilder? init; final InstanceCreateBuilderCallback? create; @@ -405,7 +405,7 @@ class Binder extends InheritedWidget { didUpdateWidget; @override - bool updateShouldNotify(Binder oldWidget) { + bool updateShouldNotify(final Binder oldWidget) { return oldWidget.id != id || oldWidget.global != global || oldWidget.autoRemove != autoRemove || @@ -419,11 +419,11 @@ class Binder extends InheritedWidget { /// The BindElement is responsible for injecting dependencies into the widget /// tree so that they can be observed class BindElement extends InheritedElement { - BindElement(Binder widget) : super(widget) { + BindElement(Binder super.widget) { initState(); } - final disposers = []; + final List disposers = []; InitBuilder? _controllerBuilder; @@ -451,7 +451,7 @@ class BindElement extends InheritedElement { void initState() { widget.initState?.call(this); - var isRegistered = Get.isRegistered(tag: widget.tag); + final bool isRegistered = Get.isRegistered(tag: widget.tag); if (widget.global) { if (isRegistered) { @@ -464,7 +464,7 @@ class BindElement extends InheritedElement { _controllerBuilder = () => Get.find(tag: widget.tag); } else { _controllerBuilder = - () => (widget.create?.call(this) ?? widget.init?.call()); + () => (widget.create?.call(this) ?? widget.init?.call()) as T; _isCreator = true; if (widget.lazy) { Get.lazyPut(_controllerBuilder!, tag: widget.tag); @@ -474,14 +474,15 @@ class BindElement extends InheritedElement { } } else { if (widget.create != null) { - _controllerBuilder = () => widget.create!.call(this); + _controllerBuilder = () => widget.create!.call(this) as T; Get.spawn(_controllerBuilder!, tag: widget.tag, permanent: false); } else { _controllerBuilder = widget.init; } - _controllerBuilder = - (widget.create != null ? () => widget.create!.call(this) : null) ?? - widget.init; + _controllerBuilder = (widget.create != null + ? () => widget.create!.call(this) as T + : null) ?? + widget.init; _isCreator = true; _needStart = true; } @@ -494,7 +495,7 @@ class BindElement extends InheritedElement { if (widget.filter != null) { _filter = widget.filter!(_controller as T); } - final filter = _filter != null ? _filterUpdate : getUpdate; + final void Function() filter = _filter != null ? _filterUpdate : getUpdate; final localController = _controller; if (_needStart == true && localController is GetLifeCycleMixin) { @@ -514,13 +515,14 @@ class BindElement extends InheritedElement { _remove = () => localController.removeListener(filter); } else if (localController is StreamController) { _remove?.call(); - final stream = localController.stream.listen((_) => filter()); + final StreamSubscription stream = + localController.stream.listen((final _) => filter()); _remove = () => stream.cancel(); } } void _filterUpdate() { - var newFilter = widget.filter!(_controller as T); + final Object newFilter = widget.filter!(_controller as T); if (newFilter != _filter) { _filter = newFilter; getUpdate(); @@ -535,7 +537,7 @@ class BindElement extends InheritedElement { } } - for (final disposer in disposers) { + for (final Disposer disposer in disposers) { disposer(); } @@ -554,12 +556,12 @@ class BindElement extends InheritedElement { @override Binder get widget => super.widget as Binder; - var _dirty = false; + bool _dirty = false; @override - void update(Binder newWidget) { - final oldNotifier = widget.id; - final newNotifier = newWidget.id; + void update(final Binder newWidget) { + final Object? oldNotifier = widget.id; + final Object? newNotifier = newWidget.id; if (oldNotifier != newNotifier && _wasStarted) { _subscribeToController(); } @@ -591,7 +593,7 @@ class BindElement extends InheritedElement { } @override - void notifyClients(Binder oldWidget) { + void notifyClients(final Binder oldWidget) { super.notifyClients(oldWidget); _dirty = false; } @@ -604,13 +606,13 @@ class BindElement extends InheritedElement { } class BindError extends Error { + /// Creates a [BindError] + BindError({required this.controller, required this.tag}); + /// The type of the class the user tried to retrieve final T controller; final String? tag; - /// Creates a [BindError] - BindError({required this.controller, required this.tag}); - @override String toString() { if (controller == 'dynamic') { diff --git a/lib/get_state_manager/src/simple/get_view.dart b/lib/get_state_manager/src/simple/get_view.dart index 8399c024f..afb406873 100644 --- a/lib/get_state_manager/src/simple/get_view.dart +++ b/lib/get_state_manager/src/simple/get_view.dart @@ -32,14 +32,14 @@ import 'get_widget_cache.dart'; /// } ///`` abstract class GetView extends StatelessWidget { - const GetView({Key? key}) : super(key: key); + const GetView({super.key}); final String? tag = null; T get controller => Get.find(tag: tag)!; @override - Widget build(BuildContext context); + Widget build(final BuildContext context); } /// GetWidget is a great way of quickly access your individual Controller @@ -49,7 +49,7 @@ abstract class GetView extends StatelessWidget { /// GetWidget will have your own controller, and will be call events as `onInit` /// and `onClose` when the controller get in/get out on memory. abstract class GetWidget extends GetWidgetCache { - const GetWidget({Key? key}) : super(key: key); + const GetWidget({super.key}); @protected final String? tag = null; @@ -61,7 +61,7 @@ abstract class GetWidget extends GetWidgetCache { static final _cache = Expando(); @protected - Widget build(BuildContext context); + Widget build(final BuildContext context); @override WidgetCache createWidgetCache() => _GetCache(); @@ -101,7 +101,7 @@ class _GetCache extends WidgetCache> { } @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return Binder( init: () => _controller, child: widget!.build(context), diff --git a/lib/get_state_manager/src/simple/get_widget_cache.dart b/lib/get_state_manager/src/simple/get_widget_cache.dart index 9d60c1711..f26b19d53 100644 --- a/lib/get_state_manager/src/simple/get_widget_cache.dart +++ b/lib/get_state_manager/src/simple/get_widget_cache.dart @@ -1,7 +1,7 @@ import 'package:flutter/widgets.dart'; abstract class GetWidgetCache extends Widget { - const GetWidgetCache({Key? key}) : super(key: key); + const GetWidgetCache({super.key}); @override GetWidgetCacheElement createElement() => GetWidgetCacheElement(this); @@ -12,7 +12,7 @@ abstract class GetWidgetCache extends Widget { } class GetWidgetCacheElement extends ComponentElement { - GetWidgetCacheElement(GetWidgetCache widget) + GetWidgetCacheElement(final GetWidgetCache widget) : cache = widget.createWidgetCache(), super(widget) { cache._element = this; @@ -20,7 +20,7 @@ class GetWidgetCacheElement extends ComponentElement { } @override - void mount(Element? parent, dynamic newSlot) { + void mount(final Element? parent, final dynamic newSlot) { cache.onInit(); super.mount(parent, newSlot); } @@ -62,5 +62,5 @@ abstract class WidgetCache { void onClose() {} @protected - Widget build(BuildContext context); + Widget build(final BuildContext context); } diff --git a/lib/get_state_manager/src/simple/list_notifier.dart b/lib/get_state_manager/src/simple/list_notifier.dart index 13a920a07..d34593c1d 100644 --- a/lib/get_state_manager/src/simple/list_notifier.dart +++ b/lib/get_state_manager/src/simple/list_notifier.dart @@ -27,18 +27,18 @@ mixin ListNotifierSingleMixin on Listenable { // final int _microtaskVersion = 0; @override - Disposer addListener(GetStateUpdate listener) { + Disposer addListener(final GetStateUpdate listener) { assert(_debugAssertNotDisposed()); _updaters!.add(listener); return () => _updaters!.remove(listener); } - bool containsListener(GetStateUpdate listener) { + bool containsListener(final GetStateUpdate listener) { return _updaters?.contains(listener) ?? false; } @override - void removeListener(VoidCallback listener) { + void removeListener(final VoidCallback listener) { assert(_debugAssertNotDisposed()); _updaters!.remove(listener); } @@ -55,7 +55,7 @@ mixin ListNotifierSingleMixin on Listenable { } @protected - void reportAdd(VoidCallback disposer) { + void reportAdd(final VoidCallback disposer) { Notifier.instance.add(disposer); } @@ -67,7 +67,7 @@ mixin ListNotifierSingleMixin on Listenable { // _microtaskVersion = _version; final list = _updaters?.toList() ?? []; - for (var element in list) { + for (final element in list) { element(); } // }); @@ -103,24 +103,24 @@ mixin ListNotifierGroupMixin on Listenable { HashMap? _updatersGroupIds = HashMap(); - void _notifyGroupUpdate(Object id) { + void _notifyGroupUpdate(final Object id) { if (_updatersGroupIds!.containsKey(id)) { _updatersGroupIds![id]!._notifyUpdate(); } } @protected - void notifyGroupChildrens(Object id) { + void notifyGroupChildrens(final Object id) { assert(_debugAssertNotDisposed()); Notifier.instance.read(_updatersGroupIds![id]!); } - bool containsId(Object id) { + bool containsId(final Object id) { return _updatersGroupIds?.containsKey(id) ?? false; } @protected - void refreshGroup(Object id) { + void refreshGroup(final Object id) { assert(_debugAssertNotDisposed()); _notifyGroupUpdate(id); } @@ -136,7 +136,7 @@ mixin ListNotifierGroupMixin on Listenable { return true; } - void removeListenerId(Object id, VoidCallback listener) { + void removeListenerId(final Object id, final VoidCallback listener) { assert(_debugAssertNotDisposed()); if (_updatersGroupIds!.containsKey(id)) { _updatersGroupIds![id]!.removeListener(listener); @@ -146,11 +146,11 @@ mixin ListNotifierGroupMixin on Listenable { @mustCallSuper void dispose() { assert(_debugAssertNotDisposed()); - _updatersGroupIds?.forEach((key, value) => value.dispose()); + _updatersGroupIds?.forEach((final key, final value) => value.dispose()); _updatersGroupIds = null; } - Disposer addListenerId(Object? key, GetStateUpdate listener) { + Disposer addListenerId(final Object? key, final GetStateUpdate listener) { _updatersGroupIds![key] ??= ListNotifierSingle(); return _updatersGroupIds![key]!.addListener(listener); } @@ -158,7 +158,7 @@ mixin ListNotifierGroupMixin on Listenable { /// To dispose an [id] from future updates(), this ids are registered /// by `GetBuilder()` or similar, so is a way to unlink the state change with /// the Widget from the Controller. - void disposeId(Object id) { + void disposeId(final Object id) { _updatersGroupIds?[id]?.dispose(); _updatersGroupIds!.remove(id); } @@ -172,11 +172,11 @@ class Notifier { NotifyData? _notifyData; - void add(VoidCallback listener) { + void add(final VoidCallback listener) { _notifyData?.disposers.add(listener); } - void read(ListNotifierSingleMixin updaters) { + void read(final ListNotifierSingleMixin updaters) { final listener = _notifyData?.updater; if (listener != null && !updaters.containsListener(listener)) { updaters.addListener(listener); @@ -184,7 +184,7 @@ class Notifier { } } - T append(NotifyData data, T Function() builder) { + T append(final NotifyData data, final T Function() builder) { _notifyData = data; final result = builder(); if (data.disposers.isEmpty && data.throwException) { @@ -209,13 +209,13 @@ class ObxError { const ObxError(); @override String toString() { - return """ + return ''' [Get] the improper use of a GetX has been detected. You should only use GetX or Obx for the specific widget that will be updated. If you are seeing this error, you probably did not insert any observable variables into GetX/Obx or insert them outside the scope that GetX considers suitable for an update (example: GetX => HeavyWidget => variableObservable). If you need to update a parent widget and a child widget, wrap each one in an Obx/GetX. - """; + '''; } } diff --git a/lib/get_state_manager/src/simple/mixin_builder.dart b/lib/get_state_manager/src/simple/mixin_builder.dart index adfcf4ba7..3a6338d21 100644 --- a/lib/get_state_manager/src/simple/mixin_builder.dart +++ b/lib/get_state_manager/src/simple/mixin_builder.dart @@ -5,6 +5,18 @@ import 'get_controllers.dart'; import 'get_state.dart'; class MixinBuilder extends StatelessWidget { + + const MixinBuilder({ + required this.builder, super.key, + this.init, + this.global = true, + this.autoRemove = true, + this.initState, + this.dispose, + this.id, + this.didChangeDependencies, + this.didUpdateWidget, + }); @required final Widget Function(T) builder; final bool global; @@ -17,21 +29,8 @@ class MixinBuilder extends StatelessWidget { didUpdateWidget; final T? init; - const MixinBuilder({ - Key? key, - this.init, - this.global = true, - required this.builder, - this.autoRemove = true, - this.initState, - this.dispose, - this.id, - this.didChangeDependencies, - this.didUpdateWidget, - }) : super(key: key); - @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return GetBuilder( init: init, global: global, @@ -41,6 +40,6 @@ class MixinBuilder extends StatelessWidget { id: id, didChangeDependencies: didChangeDependencies, didUpdateWidget: didUpdateWidget, - builder: (controller) => Obx(() => builder.call(controller))); + builder: (final controller) => Obx(() => builder.call(controller))); } } diff --git a/lib/get_state_manager/src/simple/simple_builder.dart b/lib/get_state_manager/src/simple/simple_builder.dart index aed1f488f..78ee527e6 100644 --- a/lib/get_state_manager/src/simple/simple_builder.dart +++ b/lib/get_state_manager/src/simple/simple_builder.dart @@ -24,18 +24,16 @@ typedef ValueBuilderBuilder = Widget Function( /// ), /// ``` class ValueBuilder extends StatefulWidget { - final T initialValue; - final ValueBuilderBuilder builder; - final void Function()? onDispose; - final void Function(T)? onUpdate; const ValueBuilder({ - Key? key, - required this.initialValue, + required this.initialValue, required this.builder, super.key, this.onDispose, this.onUpdate, - required this.builder, - }) : super(key: key); + }); + final T initialValue; + final ValueBuilderBuilder builder; + final void Function()? onDispose; + final void Function(T)? onUpdate; @override ValueBuilderState createState() => ValueBuilderState(); @@ -50,9 +48,9 @@ class ValueBuilderState extends State> { } @override - Widget build(BuildContext context) => widget.builder(value, updater); + Widget build(final BuildContext context) => widget.builder(value, updater); - void updater(T newValue) { + void updater(final T newValue) { if (widget.onUpdate != null) { widget.onUpdate!(newValue); } @@ -77,18 +75,18 @@ class ObxElement = StatelessElement with StatelessObserverComponent; // It's a experimental feature class Observer extends ObxStatelessWidget { - final WidgetBuilder builder; - const Observer({Key? key, required this.builder}) : super(key: key); + const Observer({required this.builder, super.key}); + final WidgetBuilder builder; @override - Widget build(BuildContext context) => builder(context); + Widget build(final BuildContext context) => builder(context); } /// A StatelessWidget than can listen reactive changes. abstract class ObxStatelessWidget extends StatelessWidget { /// Initializes [key] for subclasses. - const ObxStatelessWidget({Key? key}) : super(key: key); + const ObxStatelessWidget({super.key}); @override StatelessElement createElement() => ObxElement(this); } diff --git a/lib/get_utils/src/equality/equality.dart b/lib/get_utils/src/equality/equality.dart index e54c1b103..95c79d9fb 100644 --- a/lib/get_utils/src/equality/equality.dart +++ b/lib/get_utils/src/equality/equality.dart @@ -6,7 +6,7 @@ mixin Equality { List get props; @override - bool operator ==(dynamic other) { + bool operator ==(final dynamic other) { return identical(this, other) || runtimeType == other.runtimeType && const DeepCollectionEquality().equals(props, other.props); @@ -27,49 +27,49 @@ abstract class IEquality { /// Compare two elements for being equal. /// /// This should be a proper equality relation. - bool equals(E e1, E e2); + bool equals(final E e1, final E e2); /// Get a hashcode of an element. /// /// The hashcode should be compatible with [equals], so that if /// `equals(a, b)` then `hash(a) == hash(b)`. - int hash(E e); + int hash(final E e); /// Test whether an object is a valid argument to [equals] and [hash]. /// /// Some implementations may be restricted to only work on specific types /// of objects. - bool isValidKey(Object? o); + bool isValidKey(final Object? o); } class DefaultEquality implements IEquality { const DefaultEquality(); @override - bool equals(Object? e1, Object? e2) => e1 == e2; + bool equals(final Object? e1, final Object? e2) => e1 == e2; @override - int hash(Object? e) => e.hashCode; + int hash(final Object? e) => e.hashCode; @override - bool isValidKey(Object? o) => true; + bool isValidKey(final Object? o) => true; } /// Equality of objects that compares only the identity of the objects. class IdentityEquality implements IEquality { const IdentityEquality(); @override - bool equals(E e1, E e2) => identical(e1, e2); + bool equals(final E e1, final E e2) => identical(e1, e2); @override - int hash(E e) => identityHashCode(e); + int hash(final E e) => identityHashCode(e); @override - bool isValidKey(Object? o) => true; + bool isValidKey(final Object? o) => true; } class DeepCollectionEquality implements IEquality { + const DeepCollectionEquality(); final IEquality _base = const DefaultEquality(); final bool _unordered = false; - const DeepCollectionEquality(); @override - bool equals(e1, e2) { + bool equals(final e1, final e2) { if (e1 is Set) { return e2 is Set && SetEquality(this).equals(e1, e2); } @@ -88,7 +88,7 @@ class DeepCollectionEquality implements IEquality { } @override - int hash(Object? o) { + int hash(final Object? o) { if (o is Set) return SetEquality(this).hash(o); if (o is Map) return MapEquality(keys: this, values: this).hash(o); if (!_unordered) { @@ -101,7 +101,7 @@ class DeepCollectionEquality implements IEquality { } @override - bool isValidKey(Object? o) => + bool isValidKey(final Object? o) => o is Iterable || o is Map || _base.isValidKey(o); } @@ -110,16 +110,16 @@ class DeepCollectionEquality implements IEquality { /// Two lists are equal if they have the same length and their elements /// at each index are equal. class ListEquality implements IEquality> { - final IEquality _elementEquality; const ListEquality( - [IEquality elementEquality = const DefaultEquality()]) + [final IEquality elementEquality = const DefaultEquality()]) : _elementEquality = elementEquality; + final IEquality _elementEquality; @override - bool equals(List? list1, List? list2) { + bool equals(final List? list1, final List? list2) { if (identical(list1, list2)) return true; if (list1 == null || list2 == null) return false; - var length = list1.length; + final length = list1.length; if (length != list2.length) return false; for (var i = 0; i < length; i++) { if (!_elementEquality.equals(list1[i], list2[i])) return false; @@ -128,26 +128,26 @@ class ListEquality implements IEquality> { } @override - int hash(List? list) { + int hash(final List? list) { if (list == null) return null.hashCode; // Jenkins's one-at-a-time hash function. // This code is almost identical to the one in IterableEquality, except // that it uses indexing instead of iterating to get the elements. var hash = 0; for (var i = 0; i < list.length; i++) { - var c = _elementEquality.hash(list[i]); + final c = _elementEquality.hash(list[i]); hash = (hash + c) & _hashMask; hash = (hash + (hash << 10)) & _hashMask; - hash ^= (hash >> 6); + hash ^= hash >> 6; } hash = (hash + (hash << 3)) & _hashMask; - hash ^= (hash >> 11); + hash ^= hash >> 11; hash = (hash + (hash << 15)) & _hashMask; return hash; } @override - bool isValidKey(Object? o) => o is List; + bool isValidKey(final Object? o) => o is List; } /// Equality on maps. @@ -155,29 +155,29 @@ class ListEquality implements IEquality> { /// Two maps are equal if they have the same number of entries, and if the /// entries of the two maps are pairwise equal on both key and value. class MapEquality implements IEquality> { - final IEquality _keyEquality; - final IEquality _valueEquality; const MapEquality( - {IEquality keys = const DefaultEquality(), - IEquality values = const DefaultEquality()}) + {final IEquality keys = const DefaultEquality(), + final IEquality values = const DefaultEquality()}) : _keyEquality = keys, _valueEquality = values; + final IEquality _keyEquality; + final IEquality _valueEquality; @override - bool equals(Map? map1, Map? map2) { + bool equals(final Map? map1, final Map? map2) { if (identical(map1, map2)) return true; if (map1 == null || map2 == null) return false; - var length = map1.length; + final length = map1.length; if (length != map2.length) return false; - Map<_MapEntry, int> equalElementCounts = HashMap(); - for (var key in map1.keys) { - var entry = _MapEntry(this, key, map1[key]); - var count = equalElementCounts[entry] ?? 0; + final Map<_MapEntry, int> equalElementCounts = HashMap(); + for (final key in map1.keys) { + final entry = _MapEntry(this, key, map1[key]); + final count = equalElementCounts[entry] ?? 0; equalElementCounts[entry] = count + 1; } - for (var key in map2.keys) { - var entry = _MapEntry(this, key, map2[key]); - var count = equalElementCounts[entry]; + for (final key in map2.keys) { + final entry = _MapEntry(this, key, map2[key]); + final count = equalElementCounts[entry]; if (count == null || count == 0) return false; equalElementCounts[entry] = count - 1; } @@ -185,29 +185,29 @@ class MapEquality implements IEquality> { } @override - int hash(Map? map) { + int hash(final Map? map) { if (map == null) return null.hashCode; var hash = 0; - for (var key in map.keys) { - var keyHash = _keyEquality.hash(key); - var valueHash = _valueEquality.hash(map[key] as V); + for (final key in map.keys) { + final keyHash = _keyEquality.hash(key); + final valueHash = _valueEquality.hash(map[key] as V); hash = (hash + 3 * keyHash + 7 * valueHash) & _hashMask; } hash = (hash + (hash << 3)) & _hashMask; - hash ^= (hash >> 11); + hash ^= hash >> 11; hash = (hash + (hash << 15)) & _hashMask; return hash; } @override - bool isValidKey(Object? o) => o is Map; + bool isValidKey(final Object? o) => o is Map; } class _MapEntry { + _MapEntry(this.equality, this.key, this.value); final MapEquality equality; final Object? key; final Object? value; - _MapEntry(this.equality, this.key, this.value); @override int get hashCode => @@ -216,7 +216,7 @@ class _MapEntry { _hashMask; @override - bool operator ==(Object other) => + bool operator ==(final Object other) => other is _MapEntry && equality._keyEquality.equals(key, other.key) && equality._valueEquality.equals(value, other.value); @@ -226,19 +226,19 @@ class _MapEntry { /// /// Two iterables are equal if they have the same elements in the same order. class IterableEquality implements IEquality> { - final IEquality _elementEquality; const IterableEquality( - [IEquality elementEquality = const DefaultEquality()]) + [final IEquality elementEquality = const DefaultEquality()]) : _elementEquality = elementEquality; + final IEquality _elementEquality; @override - bool equals(Iterable? elements1, Iterable? elements2) { + bool equals(final Iterable? elements1, final Iterable? elements2) { if (identical(elements1, elements2)) return true; if (elements1 == null || elements2 == null) return false; - var it1 = elements1.iterator; - var it2 = elements2.iterator; + final it1 = elements1.iterator; + final it2 = elements2.iterator; while (true) { - var hasNext = it1.moveNext(); + final hasNext = it1.moveNext(); if (hasNext != it2.moveNext()) return false; if (!hasNext) return true; if (!_elementEquality.equals(it1.current, it2.current)) return false; @@ -246,24 +246,24 @@ class IterableEquality implements IEquality> { } @override - int hash(Iterable? elements) { + int hash(final Iterable? elements) { if (elements == null) return null.hashCode; // Jenkins's one-at-a-time hash function. var hash = 0; - for (var element in elements) { - var c = _elementEquality.hash(element); + for (final element in elements) { + final c = _elementEquality.hash(element); hash = (hash + c) & _hashMask; hash = (hash + (hash << 10)) & _hashMask; - hash ^= (hash >> 6); + hash ^= hash >> 6; } hash = (hash + (hash << 3)) & _hashMask; - hash ^= (hash >> 11); + hash ^= hash >> 11; hash = (hash + (hash << 15)) & _hashMask; return hash; } @override - bool isValidKey(Object? o) => o is Iterable; + bool isValidKey(final Object? o) => o is Iterable; } /// Equality of sets. @@ -273,35 +273,34 @@ class IterableEquality implements IEquality> { /// of the other set, so that each pair are equal. class SetEquality extends _UnorderedEquality> { const SetEquality( - [IEquality elementEquality = const DefaultEquality()]) - : super(elementEquality); + [super.elementEquality = const DefaultEquality()]); @override - bool isValidKey(Object? o) => o is Set; + bool isValidKey(final Object? o) => o is Set; } abstract class _UnorderedEquality> implements IEquality { - final IEquality _elementEquality; const _UnorderedEquality(this._elementEquality); + final IEquality _elementEquality; @override - bool equals(T? elements1, T? elements2) { + bool equals(final T? elements1, final T? elements2) { if (identical(elements1, elements2)) return true; if (elements1 == null || elements2 == null) return false; - var counts = HashMap( + final counts = HashMap( equals: _elementEquality.equals, hashCode: _elementEquality.hash, isValidKey: _elementEquality.isValidKey); var length = 0; - for (var e in elements1) { - var count = counts[e] ?? 0; + for (final e in elements1) { + final count = counts[e] ?? 0; counts[e] = count + 1; length++; } - for (var e in elements2) { - var count = counts[e]; + for (final e in elements2) { + final count = counts[e]; if (count == null || count == 0) return false; counts[e] = count - 1; length--; @@ -310,15 +309,15 @@ abstract class _UnorderedEquality> } @override - int hash(T? elements) { + int hash(final T? elements) { if (elements == null) return null.hashCode; var hash = 0; - for (E element in elements) { - var c = _elementEquality.hash(element); + for (final E element in elements) { + final c = _elementEquality.hash(element); hash = (hash + c) & _hashMask; } hash = (hash + (hash << 3)) & _hashMask; - hash ^= (hash >> 11); + hash ^= hash >> 11; hash = (hash + (hash << 15)) & _hashMask; return hash; } @@ -331,9 +330,8 @@ abstract class _UnorderedEquality> /// of the other iterable, so that each pair are equal. class UnorderedIterableEquality extends _UnorderedEquality> { const UnorderedIterableEquality( - [IEquality elementEquality = const DefaultEquality()]) - : super(elementEquality); + [super.elementEquality = const DefaultEquality()]); @override - bool isValidKey(Object? o) => o is Iterable; + bool isValidKey(final Object? o) => o is Iterable; } diff --git a/lib/get_utils/src/extensions/context_extensions.dart b/lib/get_utils/src/extensions/context_extensions.dart index f4ad5092b..acc4b7b03 100644 --- a/lib/get_utils/src/extensions/context_extensions.dart +++ b/lib/get_utils/src/extensions/context_extensions.dart @@ -23,7 +23,7 @@ extension ContextExt on BuildContext { /// /// [reducedBy] is a percentage value of how much of the height you want /// if you for example want 46% of the height, then you reduce it by 56%. - double heightTransformer({double dividedBy = 1, double reducedBy = 0.0}) { + double heightTransformer({final double dividedBy = 1, final double reducedBy = 0.0}) { return (mediaQuerySize.height - ((mediaQuerySize.height / 100) * reducedBy)) / dividedBy; @@ -38,16 +38,16 @@ extension ContextExt on BuildContext { /// /// [reducedBy] is a percentage value of how much of the width you want /// if you for example want 46% of the width, then you reduce it by 56%. - double widthTransformer({double dividedBy = 1, double reducedBy = 0.0}) { + double widthTransformer({final double dividedBy = 1, final double reducedBy = 0.0}) { return (mediaQuerySize.width - ((mediaQuerySize.width / 100) * reducedBy)) / dividedBy; } /// Divide the height proportionally by the given value double ratio({ - double dividedBy = 1, - double reducedByW = 0.0, - double reducedByH = 0.0, + final double dividedBy = 1, + final double reducedByW = 0.0, + final double reducedByH = 0.0, }) { return heightTransformer(dividedBy: dividedBy, reducedBy: reducedByH) / widthTransformer(dividedBy: dividedBy, reducedBy: reducedByW); @@ -57,7 +57,7 @@ extension ContextExt on BuildContext { ThemeData get theme => Theme.of(this); /// Check if dark mode theme is enable - bool get isDarkMode => (theme.brightness == Brightness.dark); + bool get isDarkMode => theme.brightness == Brightness.dark; /// give access to Theme.of(context).iconTheme.color Color? get iconColor => theme.iconTheme.color; @@ -96,7 +96,7 @@ extension ContextExt on BuildContext { double get mediaQueryShortestSide => mediaQuerySize.shortestSide; /// True if width be larger than 800 - bool get showNavbar => (width > 800); + bool get showNavbar => width > 800; /// True if the width is smaller than 600p bool get isPhoneOrLess => width <= 600; @@ -105,7 +105,7 @@ extension ContextExt on BuildContext { bool get isPhoneOrWider => width >= 600; /// True if the shortestSide is smaller than 600p - bool get isPhone => (mediaQueryShortestSide < 600); + bool get isPhone => mediaQueryShortestSide < 600; /// True if the width is smaller than 600p bool get isSmallTabletOrLess => width <= 600; @@ -114,10 +114,10 @@ extension ContextExt on BuildContext { bool get isSmallTabletOrWider => width >= 600; /// True if the shortestSide is largest than 600p - bool get isSmallTablet => (mediaQueryShortestSide >= 600); + bool get isSmallTablet => mediaQueryShortestSide >= 600; /// True if the shortestSide is largest than 720p - bool get isLargeTablet => (mediaQueryShortestSide >= 720); + bool get isLargeTablet => mediaQueryShortestSide >= 720; /// True if the width is smaller than 720p bool get isLargeTabletOrLess => width <= 720; @@ -144,15 +144,15 @@ extension ContextExt on BuildContext { /// if the device width is less than 300 return [watch] value. /// in other cases return [mobile] value. T responsiveValue({ - T? watch, - T? mobile, - T? tablet, - T? desktop, + final T? watch, + final T? mobile, + final T? tablet, + final T? desktop, }) { assert( watch != null || mobile != null || tablet != null || desktop != null); - var deviceWidth = mediaQuerySize.width; + final deviceWidth = mediaQuerySize.width; //big screen width can display smaller sizes final strictValues = [ if (deviceWidth >= 1200) desktop, //desktop is allowed @@ -173,7 +173,7 @@ extension ContextExt on BuildContext { extension IterableExt on Iterable { /// The first element, or `null` if the iterable is empty. T? get firstOrNull { - var iterator = this.iterator; + final iterator = this.iterator; if (iterator.moveNext()) return iterator.current; return null; } diff --git a/lib/get_utils/src/extensions/double_extensions.dart b/lib/get_utils/src/extensions/double_extensions.dart index c8d8b1e72..704029c2a 100644 --- a/lib/get_utils/src/extensions/double_extensions.dart +++ b/lib/get_utils/src/extensions/double_extensions.dart @@ -1,9 +1,9 @@ import 'dart:math'; extension DoubleExt on double { - double toPrecision(int fractionDigits) { - var mod = pow(10, fractionDigits.toDouble()).toDouble(); - return ((this * mod).round().toDouble() / mod); + double toPrecision(final int fractionDigits) { + final mod = pow(10, fractionDigits.toDouble()).toDouble(); + return (this * mod).round().toDouble() / mod; } Duration get milliseconds => Duration(microseconds: (this * 1000).round()); diff --git a/lib/get_utils/src/extensions/duration_extensions.dart b/lib/get_utils/src/extensions/duration_extensions.dart index 0bfd97ce8..625da01d4 100644 --- a/lib/get_utils/src/extensions/duration_extensions.dart +++ b/lib/get_utils/src/extensions/duration_extensions.dart @@ -1,7 +1,7 @@ import 'dart:async'; /// Duration utilities. -extension GetDurationUtils on Duration { +extension GetDurationUtils on Duration { /// Utility to delay some callback (or code execution). /// /// Sample: @@ -15,6 +15,6 @@ extension GetDurationUtils on Duration { /// await 0.7.seconds.delay(() { /// } ///``` - Future delay([FutureOr Function()? callback]) async => - Future.delayed(this, callback); + Future delay([final FutureOr Function()? callback]) async => + Future.delayed(this, callback); } diff --git a/lib/get_utils/src/extensions/dynamic_extensions.dart b/lib/get_utils/src/extensions/dynamic_extensions.dart index 4ac4c3f9f..3337febf1 100644 --- a/lib/get_utils/src/extensions/dynamic_extensions.dart +++ b/lib/get_utils/src/extensions/dynamic_extensions.dart @@ -4,13 +4,13 @@ extension GetDynamicUtils on dynamic { bool? get isBlank => GetUtils.isBlank(this); void printError( - {String info = '', Function logFunction = GetUtils.printFunction}) => + {final String info = '', final Function logFunction = GetUtils.printFunction}) => // ignore: unnecessary_this logFunction('Error: ${this.runtimeType}', this, info, isError: true); void printInfo( - {String info = '', - Function printFunction = GetUtils.printFunction}) => + {final String info = '', + final Function printFunction = GetUtils.printFunction}) => // ignore: unnecessary_this printFunction('Info: ${this.runtimeType}', this, info); } diff --git a/lib/get_utils/src/extensions/event_loop_extensions.dart b/lib/get_utils/src/extensions/event_loop_extensions.dart index 3dbee3803..58e8d1f5d 100644 --- a/lib/get_utils/src/extensions/event_loop_extensions.dart +++ b/lib/get_utils/src/extensions/event_loop_extensions.dart @@ -3,14 +3,14 @@ import 'dart:async'; import '../../../get_core/src/get_interface.dart'; extension LoopEventsExt on GetInterface { - Future toEnd(FutureOr Function() computation) async { + Future toEnd(final FutureOr Function() computation) async { await Future.delayed(Duration.zero); final val = computation(); return val; } - FutureOr asap(T Function() computation, - {bool Function()? condition}) async { + FutureOr asap(final T Function() computation, + {final bool Function()? condition}) async { T val; if (condition == null || !condition()) { await Future.delayed(Duration.zero); diff --git a/lib/get_utils/src/extensions/export.dart b/lib/get_utils/src/extensions/export.dart index 3d94c059b..e3b8077c9 100644 --- a/lib/get_utils/src/extensions/export.dart +++ b/lib/get_utils/src/extensions/export.dart @@ -4,7 +4,7 @@ export 'duration_extensions.dart'; export 'dynamic_extensions.dart'; export 'event_loop_extensions.dart'; export 'int_extensions.dart'; -export 'internacionalization.dart' hide FirstWhereExt; +export 'internationalization.dart' hide FirstWhereExt; export 'iterable_extensions.dart'; export 'num_extensions.dart'; export 'string_extensions.dart'; diff --git a/lib/get_utils/src/extensions/internacionalization.dart b/lib/get_utils/src/extensions/internationalization.dart similarity index 71% rename from lib/get_utils/src/extensions/internacionalization.dart rename to lib/get_utils/src/extensions/internationalization.dart index e0155dd7c..c67ca9f2a 100644 --- a/lib/get_utils/src/extensions/internacionalization.dart +++ b/lib/get_utils/src/extensions/internationalization.dart @@ -12,8 +12,8 @@ class _IntlHost { extension FirstWhereExt on List { /// The first element satisfying [test], or `null` if there are none. - T? firstWhereOrNull(bool Function(T element) test) { - for (var element in this) { + T? firstWhereOrNull(final bool Function(T element) test) { + for (final element in this) { if (test(element)) return element; } return null; @@ -27,13 +27,13 @@ extension LocalesIntl on GetInterface { Locale? get fallbackLocale => _intlHost.fallbackLocale; - set locale(Locale? newLocale) => _intlHost.locale = newLocale; + set locale(final Locale? newLocale) => _intlHost.locale = newLocale; - set fallbackLocale(Locale? newLocale) => _intlHost.fallbackLocale = newLocale; + set fallbackLocale(final Locale? newLocale) => _intlHost.fallbackLocale = newLocale; Map> get translations => _intlHost.translations; - void addTranslations(Map> tr) { + void addTranslations(final Map> tr) { translations.addAll(tr); } @@ -41,8 +41,8 @@ extension LocalesIntl on GetInterface { translations.clear(); } - void appendTranslations(Map> tr) { - tr.forEach((key, map) { + void appendTranslations(final Map> tr) { + tr.forEach((final key, final map) { if (translations.containsKey(key)) { translations[key]!.addAll(map); } else { @@ -57,9 +57,9 @@ extension Trans on String { // whether the key is also present. bool get _fullLocaleAndKey { return Get.translations.containsKey( - "${Get.locale!.languageCode}_${Get.locale!.countryCode}") && + '${Get.locale!.languageCode}_${Get.locale!.countryCode}') && Get.translations[ - "${Get.locale!.languageCode}_${Get.locale!.countryCode}"]! + '${Get.locale!.languageCode}_${Get.locale!.countryCode}']! .containsKey(this); } @@ -67,15 +67,15 @@ extension Trans on String { // country, and if it contains that key. Map? get _getSimilarLanguageTranslation { final translationsWithNoCountry = Get.translations - .map((key, value) => MapEntry(key.split("_").first, value)); + .map((final key, final value) => MapEntry(key.split('_').first, value)); final containsKey = translationsWithNoCountry - .containsKey(Get.locale!.languageCode.split("_").first); + .containsKey(Get.locale!.languageCode.split('_').first); if (!containsKey) { return null; } - return translationsWithNoCountry[Get.locale!.languageCode.split("_").first]; + return translationsWithNoCountry[Get.locale!.languageCode.split('_').first]; } String get tr { @@ -89,7 +89,7 @@ extension Trans on String { if (_fullLocaleAndKey) { return Get.translations[ - "${Get.locale!.languageCode}_${Get.locale!.countryCode}"]![this]!; + '${Get.locale!.languageCode}_${Get.locale!.countryCode}']![this]!; } final similarTranslation = _getSimilarLanguageTranslation; if (similarTranslation != null && similarTranslation.containsKey(this)) { @@ -98,7 +98,7 @@ extension Trans on String { // the key. } else if (Get.fallbackLocale != null) { final fallback = Get.fallbackLocale!; - final key = "${fallback.languageCode}_${fallback.countryCode}"; + final key = '${fallback.languageCode}_${fallback.countryCode}'; if (Get.translations.containsKey(key) && Get.translations[key]!.containsKey(this)) { @@ -114,7 +114,7 @@ extension Trans on String { } } - String trArgs([List args = const []]) { + String trArgs([final List args = const []]) { var key = tr; if (args.isNotEmpty) { for (final arg in args) { @@ -124,14 +124,14 @@ extension Trans on String { return key; } - String trPlural([String? pluralKey, int? i, List args = const []]) { + String trPlural([final String? pluralKey, final int? i, final List args = const []]) { return i == 1 ? trArgs(args) : pluralKey!.trArgs(args); } - String trParams([Map params = const {}]) { + String trParams([final Map params = const {}]) { var trans = tr; if (params.isNotEmpty) { - params.forEach((key, value) { + params.forEach((final key, final value) { trans = trans.replaceAll('@$key', value); }); } @@ -139,7 +139,7 @@ extension Trans on String { } String trPluralParams( - [String? pluralKey, int? i, Map params = const {}]) { + [final String? pluralKey, final int? i, final Map params = const {}]) { return i == 1 ? trParams(params) : pluralKey!.trParams(params); } } diff --git a/lib/get_utils/src/extensions/iterable_extensions.dart b/lib/get_utils/src/extensions/iterable_extensions.dart index a9d9da8d9..7ba6d22af 100644 --- a/lib/get_utils/src/extensions/iterable_extensions.dart +++ b/lib/get_utils/src/extensions/iterable_extensions.dart @@ -1,9 +1,11 @@ extension IterableExtensions on Iterable { Iterable mapMany( - Iterable? Function(T item) selector) sync* { - for (var item in this) { - final res = selector(item); - if (res != null) yield* res; + final Iterable? Function(T item) selector) sync* { + for (final T item in this) { + final Iterable? res = selector(item); + if (res != null) { + yield* res; + } } } } diff --git a/lib/get_utils/src/extensions/num_extensions.dart b/lib/get_utils/src/extensions/num_extensions.dart index 00b5b475f..a725fffc6 100644 --- a/lib/get_utils/src/extensions/num_extensions.dart +++ b/lib/get_utils/src/extensions/num_extensions.dart @@ -3,11 +3,11 @@ import 'dart:async'; import '../get_utils/get_utils.dart'; extension GetNumUtils on num { - bool isLowerThan(num b) => GetUtils.isLowerThan(this, b); + bool isLowerThan(final num b) => GetUtils.isLowerThan(this, b); - bool isGreaterThan(num b) => GetUtils.isGreaterThan(this, b); + bool isGreaterThan(final num b) => GetUtils.isGreaterThan(this, b); - bool isEqual(num b) => GetUtils.isEqual(this, b); + bool isEqual(final num b) => GetUtils.isEqual(this, b); /// Utility to delay some callback (or code execution). /// TODO: Add a separated implementation of delay() with the ability @@ -24,7 +24,7 @@ extension GetNumUtils on num { /// print('currently running callback 1.2sec'); /// } ///``` - Future delay([FutureOr Function()? callback]) async => Future.delayed( + Future delay([final FutureOr Function()? callback]) async => Future.delayed( Duration(milliseconds: (this * 1000).round()), callback, ); diff --git a/lib/get_utils/src/extensions/string_extensions.dart b/lib/get_utils/src/extensions/string_extensions.dart index 7c0d5db32..eb3d82590 100644 --- a/lib/get_utils/src/extensions/string_extensions.dart +++ b/lib/get_utils/src/extensions/string_extensions.dart @@ -7,7 +7,7 @@ extension GetStringUtils on String { /// Discover if the String is numeric only bool get isNumericOnly => GetUtils.isNumericOnly(this); - String numericOnly({bool firstWordOnly = false}) => + String numericOnly({final bool firstWordOnly = false}) => GetUtils.numericOnly(this, firstWordOnly: firstWordOnly); /// Discover if the String is alphanumeric only @@ -97,11 +97,11 @@ extension GetStringUtils on String { bool get isCnpj => GetUtils.isCnpj(this); /// Discover if the String is a case insensitive - bool isCaseInsensitiveContains(String b) => + bool isCaseInsensitiveContains(final String b) => GetUtils.isCaseInsensitiveContains(this, b); /// Discover if the String is a case sensitive and contains any value - bool isCaseInsensitiveContainsAny(String b) => + bool isCaseInsensitiveContainsAny(final String b) => GetUtils.isCaseInsensitiveContainsAny(this, b); /// capitalize the String @@ -120,7 +120,7 @@ extension GetStringUtils on String { String? get paramCase => GetUtils.paramCase(this); /// add segments to the String - String createPath([Iterable? segments]) { + String createPath([final Iterable? segments]) { final path = startsWith('/') ? this : '/$this'; return GetUtils.createPath(path, segments); } diff --git a/lib/get_utils/src/extensions/widget_extensions.dart b/lib/get_utils/src/extensions/widget_extensions.dart index 3e4b6d3d8..fa18b7f3a 100644 --- a/lib/get_utils/src/extensions/widget_extensions.dart +++ b/lib/get_utils/src/extensions/widget_extensions.dart @@ -2,20 +2,20 @@ import 'package:flutter/widgets.dart'; /// add Padding Property to widget extension WidgetPaddingX on Widget { - Widget paddingAll(double padding) => + Widget paddingAll(final double padding) => Padding(padding: EdgeInsets.all(padding), child: this); - Widget paddingSymmetric({double horizontal = 0.0, double vertical = 0.0}) => + Widget paddingSymmetric({final double horizontal = 0.0, final double vertical = 0.0}) => Padding( padding: EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical), child: this); Widget paddingOnly({ - double left = 0.0, - double top = 0.0, - double right = 0.0, - double bottom = 0.0, + final double left = 0.0, + final double top = 0.0, + final double right = 0.0, + final double bottom = 0.0, }) => Padding( padding: EdgeInsets.only( @@ -27,20 +27,20 @@ extension WidgetPaddingX on Widget { /// Add margin property to widget extension WidgetMarginX on Widget { - Widget marginAll(double margin) => + Widget marginAll(final double margin) => Container(margin: EdgeInsets.all(margin), child: this); - Widget marginSymmetric({double horizontal = 0.0, double vertical = 0.0}) => + Widget marginSymmetric({final double horizontal = 0.0, final double vertical = 0.0}) => Container( margin: EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical), child: this); Widget marginOnly({ - double left = 0.0, - double top = 0.0, - double right = 0.0, - double bottom = 0.0, + final double left = 0.0, + final double top = 0.0, + final double right = 0.0, + final double bottom = 0.0, }) => Container( margin: EdgeInsets.only( diff --git a/lib/get_utils/src/get_utils/get_utils.dart b/lib/get_utils/src/get_utils/get_utils.dart index a5e89cb42..f79ba806a 100644 --- a/lib/get_utils/src/get_utils/get_utils.dart +++ b/lib/get_utils/src/get_utils/get_utils.dart @@ -5,7 +5,7 @@ import '../../../get_core/get_core.dart'; /// standard dart types that contains it. /// /// This is here to for the 'DRY' -bool? _isEmpty(dynamic value) { +bool? _isEmpty(final dynamic value) { if (value is String) { return value.toString().trim().isEmpty; } @@ -20,7 +20,7 @@ bool? _isEmpty(dynamic value) { /// standard dart types that contains it. /// /// This is here to for the 'DRY' -bool _hasLength(dynamic value) { +bool _hasLength(final dynamic value) { return value is Iterable || value is String || value is Map; } @@ -34,7 +34,7 @@ bool _hasLength(dynamic value) { /// Note 2: **this may return null!** /// /// Note 3: null [value] returns null. -int? _obtainDynamicLength(dynamic value) { +int? _obtainDynamicLength(final dynamic value) { if (value == null) { // ignore: avoid_returning_null return null; @@ -60,7 +60,7 @@ class GetUtils { GetUtils._(); /// Checks if data is null. - static bool isNull(dynamic value) => value == null; + static bool isNull(final dynamic value) => value == null; /// In dart2js (in flutter v1.17) a var by default is undefined. /// *Use this only if you are in version <- 1.17*. @@ -68,10 +68,10 @@ class GetUtils { /// "value":value==null?null:value; someVar.nil will force the null type /// if the var is null or undefined. /// `nil` taken from ObjC just to have a shorter syntax. - static dynamic nil(dynamic s) => s; + static dynamic nil(final dynamic s) => s; /// Checks if data is null or blank (empty or only contains whitespace). - static bool? isNullOrBlank(dynamic value) { + static bool? isNullOrBlank(final dynamic value) { if (isNull(value)) { return true; } @@ -82,12 +82,12 @@ class GetUtils { } /// Checks if data is null or blank (empty or only contains whitespace). - static bool? isBlank(dynamic value) { + static bool? isBlank(final dynamic value) { return _isEmpty(value); } /// Checks if string is int or double. - static bool isNum(String value) { + static bool isNum(final String value) { if (isNull(value)) { return false; } @@ -97,168 +97,168 @@ class GetUtils { /// Checks if string consist only numeric. /// Numeric only doesn't accepting "." which double data type have - static bool isNumericOnly(String s) => hasMatch(s, r'^\d+$'); + static bool isNumericOnly(final String s) => hasMatch(s, r'^\d+$'); /// Checks if string consist only Alphabet. (No Whitespace) - static bool isAlphabetOnly(String s) => hasMatch(s, r'^[a-zA-Z]+$'); + static bool isAlphabetOnly(final String s) => hasMatch(s, r'^[a-zA-Z]+$'); /// Checks if string contains at least one Capital Letter - static bool hasCapitalLetter(String s) => hasMatch(s, r'[A-Z]'); + static bool hasCapitalLetter(final String s) => hasMatch(s, r'[A-Z]'); /// Checks if string is boolean. - static bool isBool(String value) { + static bool isBool(final String value) { if (isNull(value)) { return false; } - return (value == 'true' || value == 'false'); + return value == 'true' || value == 'false'; } /// Checks if string is an video file. - static bool isVideo(String filePath) { - var ext = filePath.toLowerCase(); + static bool isVideo(final String filePath) { + final ext = filePath.toLowerCase(); - return ext.endsWith(".mp4") || - ext.endsWith(".avi") || - ext.endsWith(".wmv") || - ext.endsWith(".rmvb") || - ext.endsWith(".mpg") || - ext.endsWith(".mpeg") || - ext.endsWith(".3gp"); + return ext.endsWith('.mp4') || + ext.endsWith('.avi') || + ext.endsWith('.wmv') || + ext.endsWith('.rmvb') || + ext.endsWith('.mpg') || + ext.endsWith('.mpeg') || + ext.endsWith('.3gp'); } /// Checks if string is an image file. - static bool isImage(String filePath) { + static bool isImage(final String filePath) { final ext = filePath.toLowerCase(); - return ext.endsWith(".jpg") || - ext.endsWith(".jpeg") || - ext.endsWith(".png") || - ext.endsWith(".gif") || - ext.endsWith(".bmp"); + return ext.endsWith('.jpg') || + ext.endsWith('.jpeg') || + ext.endsWith('.png') || + ext.endsWith('.gif') || + ext.endsWith('.bmp'); } /// Checks if string is an audio file. - static bool isAudio(String filePath) { + static bool isAudio(final String filePath) { final ext = filePath.toLowerCase(); - return ext.endsWith(".mp3") || - ext.endsWith(".wav") || - ext.endsWith(".wma") || - ext.endsWith(".amr") || - ext.endsWith(".ogg"); + return ext.endsWith('.mp3') || + ext.endsWith('.wav') || + ext.endsWith('.wma') || + ext.endsWith('.amr') || + ext.endsWith('.ogg'); } /// Checks if string is an powerpoint file. - static bool isPPT(String filePath) { + static bool isPPT(final String filePath) { final ext = filePath.toLowerCase(); - return ext.endsWith(".ppt") || ext.endsWith(".pptx"); + return ext.endsWith('.ppt') || ext.endsWith('.pptx'); } /// Checks if string is an word file. - static bool isWord(String filePath) { + static bool isWord(final String filePath) { final ext = filePath.toLowerCase(); - return ext.endsWith(".doc") || ext.endsWith(".docx"); + return ext.endsWith('.doc') || ext.endsWith('.docx'); } /// Checks if string is an excel file. - static bool isExcel(String filePath) { + static bool isExcel(final String filePath) { final ext = filePath.toLowerCase(); - return ext.endsWith(".xls") || ext.endsWith(".xlsx"); + return ext.endsWith('.xls') || ext.endsWith('.xlsx'); } /// Checks if string is an apk file. - static bool isAPK(String filePath) { - return filePath.toLowerCase().endsWith(".apk"); + static bool isAPK(final String filePath) { + return filePath.toLowerCase().endsWith('.apk'); } /// Checks if string is an pdf file. - static bool isPDF(String filePath) { - return filePath.toLowerCase().endsWith(".pdf"); + static bool isPDF(final String filePath) { + return filePath.toLowerCase().endsWith('.pdf'); } /// Checks if string is an txt file. - static bool isTxt(String filePath) { - return filePath.toLowerCase().endsWith(".txt"); + static bool isTxt(final String filePath) { + return filePath.toLowerCase().endsWith('.txt'); } /// Checks if string is an chm file. - static bool isChm(String filePath) { - return filePath.toLowerCase().endsWith(".chm"); + static bool isChm(final String filePath) { + return filePath.toLowerCase().endsWith('.chm'); } /// Checks if string is a vector file. - static bool isVector(String filePath) { - return filePath.toLowerCase().endsWith(".svg"); + static bool isVector(final String filePath) { + return filePath.toLowerCase().endsWith('.svg'); } /// Checks if string is an html file. - static bool isHTML(String filePath) { - return filePath.toLowerCase().endsWith(".html"); + static bool isHTML(final String filePath) { + return filePath.toLowerCase().endsWith('.html'); } /// Checks if string is a valid username. - static bool isUsername(String s) => + static bool isUsername(final String s) => hasMatch(s, r'^[a-zA-Z0-9][a-zA-Z0-9_.]+[a-zA-Z0-9]$'); /// Checks if string is URL. - static bool isURL(String s) => hasMatch(s, + static bool isURL(final String s) => hasMatch(s, r"^((((H|h)(T|t)|(F|f))(T|t)(P|p)((S|s)?))\://)?(www.|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,7}(\:[0-9]{1,5})*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$"); /// Checks if string is email. - static bool isEmail(String s) => hasMatch(s, + static bool isEmail(final String s) => hasMatch(s, r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'); /// Checks if string is phone number. - static bool isPhoneNumber(String s) { + static bool isPhoneNumber(final String s) { if (s.length > 16 || s.length < 9) return false; return hasMatch(s, r'^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$'); } /// Checks if string is DateTime (UTC or Iso8601). - static bool isDateTime(String s) => + static bool isDateTime(final String s) => hasMatch(s, r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}.\d{3}Z?$'); /// Checks if string is MD5 hash. - static bool isMD5(String s) => hasMatch(s, r'^[a-f0-9]{32}$'); + static bool isMD5(final String s) => hasMatch(s, r'^[a-f0-9]{32}$'); /// Checks if string is SHA1 hash. - static bool isSHA1(String s) => + static bool isSHA1(final String s) => hasMatch(s, r'(([A-Fa-f0-9]{2}\:){19}[A-Fa-f0-9]{2}|[A-Fa-f0-9]{40})'); /// Checks if string is SHA256 hash. - static bool isSHA256(String s) => + static bool isSHA256(final String s) => hasMatch(s, r'([A-Fa-f0-9]{2}\:){31}[A-Fa-f0-9]{2}|[A-Fa-f0-9]{64}'); /// Checks if string is SSN (Social Security Number). - static bool isSSN(String s) => hasMatch(s, + static bool isSSN(final String s) => hasMatch(s, r'^(?!0{3}|6{3}|9[0-9]{2})[0-9]{3}-?(?!0{2})[0-9]{2}-?(?!0{4})[0-9]{4}$'); /// Checks if string is binary. - static bool isBinary(String s) => hasMatch(s, r'^[0-1]+$'); + static bool isBinary(final String s) => hasMatch(s, r'^[0-1]+$'); /// Checks if string is IPv4. - static bool isIPv4(String s) => + static bool isIPv4(final String s) => hasMatch(s, r'^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$'); /// Checks if string is IPv6. - static bool isIPv6(String s) => hasMatch(s, + static bool isIPv6(final String s) => hasMatch(s, r'^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$'); /// Checks if string is hexadecimal. /// Example: HexColor => #12F - static bool isHexadecimal(String s) => + static bool isHexadecimal(final String s) => hasMatch(s, r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$'); /// Checks if string is Palindrome. - static bool isPalindrome(String string) { + static bool isPalindrome(final String string) { final cleanString = string .toLowerCase() - .replaceAll(RegExp(r"\s+"), '') - .replaceAll(RegExp(r"[^0-9a-zA-Z]+"), ""); + .replaceAll(RegExp(r'\s+'), '') + .replaceAll(RegExp(r'[^0-9a-zA-Z]+'), ''); for (var i = 0; i < cleanString.length; i++) { if (cleanString[i] != cleanString[cleanString.length - i - 1]) { @@ -271,7 +271,7 @@ class GetUtils { /// Checks if all data have same value. /// Example: 111111 -> true, wwwww -> true, 1,1,1,1 -> true - static bool isOneAKind(dynamic value) { + static bool isOneAKind(final dynamic value) { if ((value is String || value is List) && !isNullOrBlank(value)!) { final first = value[0]; final len = value.length as num; @@ -302,15 +302,15 @@ class GetUtils { } /// Checks if string is Passport No. - static bool isPassport(String s) => + static bool isPassport(final String s) => hasMatch(s, r'^(?!^0+$)[a-zA-Z0-9]{6,9}$'); /// Checks if string is Currency. - static bool isCurrency(String s) => hasMatch(s, + static bool isCurrency(final String s) => hasMatch(s, r'^(S?\$|\₩|Rp|\¥|\€|\₹|\₽|fr|R\$|R)?[ ]?[-]?([0-9]{1,3}[,.]([0-9]{3}[,.])*[0-9]{3}|[0-9]+)([,.][0-9]{1,2})?( ?(USD?|AUD|NZD|CAD|CHF|GBP|CNY|EUR|JPY|IDR|MXN|NOK|KRW|TRY|INR|RUB|BRL|ZAR|SGD|MYR))?$'); /// Checks if length of data is GREATER than maxLength. - static bool isLengthGreaterThan(dynamic value, int maxLength) { + static bool isLengthGreaterThan(final dynamic value, final int maxLength) { final length = _obtainDynamicLength(value); if (length == null) { @@ -321,7 +321,7 @@ class GetUtils { } /// Checks if length of data is GREATER OR EQUAL to maxLength. - static bool isLengthGreaterOrEqual(dynamic value, int maxLength) { + static bool isLengthGreaterOrEqual(final dynamic value, final int maxLength) { final length = _obtainDynamicLength(value); if (length == null) { @@ -332,7 +332,7 @@ class GetUtils { } /// Checks if length of data is LESS than maxLength. - static bool isLengthLessThan(dynamic value, int maxLength) { + static bool isLengthLessThan(final dynamic value, final int maxLength) { final length = _obtainDynamicLength(value); if (length == null) { return false; @@ -342,7 +342,7 @@ class GetUtils { } /// Checks if length of data is LESS OR EQUAL to maxLength. - static bool isLengthLessOrEqual(dynamic value, int maxLength) { + static bool isLengthLessOrEqual(final dynamic value, final int maxLength) { final length = _obtainDynamicLength(value); if (length == null) { @@ -353,7 +353,7 @@ class GetUtils { } /// Checks if length of data is EQUAL to maxLength. - static bool isLengthEqualTo(dynamic value, int otherLength) { + static bool isLengthEqualTo(final dynamic value, final int otherLength) { final length = _obtainDynamicLength(value); if (length == null) { @@ -364,7 +364,7 @@ class GetUtils { } /// Checks if length of data is BETWEEN minLength to maxLength. - static bool isLengthBetween(dynamic value, int minLength, int maxLength) { + static bool isLengthBetween(final dynamic value, final int minLength, final int maxLength) { if (isNull(value)) { return false; } @@ -375,13 +375,13 @@ class GetUtils { /// Checks if a contains b (Treating or interpreting upper- and lowercase /// letters as being the same). - static bool isCaseInsensitiveContains(String a, String b) { + static bool isCaseInsensitiveContains(final String a, final String b) { return a.toLowerCase().contains(b.toLowerCase()); } /// Checks if a contains b or b contains a (Treating or /// interpreting upper- and lowercase letters as being the same). - static bool isCaseInsensitiveContainsAny(String a, String b) { + static bool isCaseInsensitiveContainsAny(final String a, final String b) { final lowA = a.toLowerCase(); final lowB = b.toLowerCase(); @@ -389,16 +389,16 @@ class GetUtils { } /// Checks if num a LOWER than num b. - static bool isLowerThan(num a, num b) => a < b; + static bool isLowerThan(final num a, final num b) => a < b; /// Checks if num a GREATER than num b. - static bool isGreaterThan(num a, num b) => a > b; + static bool isGreaterThan(final num a, final num b) => a > b; /// Checks if num a EQUAL than num b. - static bool isEqual(num a, num b) => a == b; + static bool isEqual(final num a, final num b) => a == b; // Checks if num is a cnpj - static bool isCnpj(String cnpj) { + static bool isCnpj(final String cnpj) { // Get only the numbers from the CNPJ final numbers = cnpj.replaceAll(RegExp(r'[^0-9]'), ''); @@ -418,7 +418,7 @@ class GetUtils { // Calculate the first check digit var calcDv1 = 0; var j = 0; - for (var i in Iterable.generate(12, (i) => i < 4 ? 5 - i : 13 - i)) { + for (final i in Iterable.generate(12, (final i) => i < 4 ? 5 - i : 13 - i)) { calcDv1 += digits[j++] * i; } calcDv1 %= 11; @@ -432,7 +432,7 @@ class GetUtils { // Calculate the second check digit var calcDv2 = 0; j = 0; - for (var i in Iterable.generate(13, (i) => i < 5 ? 6 - i : 14 - i)) { + for (final i in Iterable.generate(13, (final i) => i < 5 ? 6 - i : 14 - i)) { calcDv2 += digits[j++] * i; } calcDv2 %= 11; @@ -447,7 +447,7 @@ class GetUtils { } /// Checks if the cpf is valid. - static bool isCpf(String cpf) { + static bool isCpf(final String cpf) { // if (cpf == null) { // return false; // } @@ -468,7 +468,7 @@ class GetUtils { // Calculate the first verifier digit var calcDv1 = 0; - for (var i in Iterable.generate(9, (i) => 10 - i)) { + for (final i in Iterable.generate(9, (final i) => 10 - i)) { calcDv1 += digits[10 - i] * i; } calcDv1 %= 11; @@ -482,7 +482,7 @@ class GetUtils { // Calculate the second verifier digit var calcDv2 = 0; - for (var i in Iterable.generate(10, (i) => 11 - i)) { + for (final i in Iterable.generate(10, (final i) => 11 - i)) { calcDv2 += digits[11 - i] * i; } calcDv2 %= 11; @@ -499,27 +499,27 @@ class GetUtils { /// Capitalize each word inside string /// Example: your name => Your Name, your name => Your name - static String capitalize(String value) { + static String capitalize(final String value) { if (isBlank(value)!) return value; return value.split(' ').map(capitalizeFirst).join(' '); } /// Uppercase first letter inside string and let the others lowercase /// Example: your name => Your name - static String capitalizeFirst(String s) { + static String capitalizeFirst(final String s) { if (isBlank(s)!) return s; return s[0].toUpperCase() + s.substring(1).toLowerCase(); } /// Remove all whitespace inside string /// Example: your name => yourname - static String removeAllWhitespace(String value) { + static String removeAllWhitespace(final String value) { return value.replaceAll(' ', ''); } /// camelCase string /// Example: your name => yourName - static String? camelCase(String value) { + static String? camelCase(final String value) { if (isNullOrBlank(value)!) { return null; } @@ -537,20 +537,20 @@ class GetUtils { /// credits to "ReCase" package. static final RegExp _upperAlphaRegex = RegExp(r'[A-Z]'); - static final _symbolSet = {' ', '.', '/', '_', '\\', '-'}; - static List _groupIntoWords(String text) { - var sb = StringBuffer(); - var words = []; - var isAllCaps = text.toUpperCase() == text; + static final _symbolSet = {' ', '.', '/', '_', r'\', '-'}; + static List _groupIntoWords(final String text) { + final sb = StringBuffer(); + final words = []; + final isAllCaps = text.toUpperCase() == text; for (var i = 0; i < text.length; i++) { - var char = text[i]; - var nextChar = i + 1 == text.length ? null : text[i + 1]; + final char = text[i]; + final nextChar = i + 1 == text.length ? null : text[i + 1]; if (_symbolSet.contains(char)) { continue; } sb.write(char); - var isEndOfWord = nextChar == null || + final isEndOfWord = nextChar == null || (_upperAlphaRegex.hasMatch(nextChar) && !isAllCaps) || _symbolSet.contains(nextChar); if (isEndOfWord) { @@ -562,30 +562,30 @@ class GetUtils { } /// snake_case - static String? snakeCase(String? text, {String separator = '_'}) { + static String? snakeCase(final String? text, {final String separator = '_'}) { if (isNullOrBlank(text)!) { return null; } return _groupIntoWords(text!) - .map((word) => word.toLowerCase()) + .map((final word) => word.toLowerCase()) .join(separator); } /// param-case - static String? paramCase(String? text) => snakeCase(text, separator: '-'); + static String? paramCase(final String? text) => snakeCase(text, separator: '-'); /// Extract numeric value of string /// Example: OTP 12312 27/04/2020 => 1231227042020ß /// If firstWordOnly is true, then the example return is "12312" /// (first found numeric word) - static String numericOnly(String s, {bool firstWordOnly = false}) { + static String numericOnly(final String s, {final bool firstWordOnly = false}) { var numericOnlyStr = ''; for (var i = 0; i < s.length; i++) { if (isNumericOnly(s[i])) { numericOnlyStr += s[i]; } - if (firstWordOnly && numericOnlyStr.isNotEmpty && s[i] == " ") { + if (firstWordOnly && numericOnlyStr.isNotEmpty && s[i] == ' ') { break; } } @@ -596,30 +596,30 @@ class GetUtils { /// Capitalize only the first letter of each word in a string /// Example: getx will make it easy => Getx Will Make It Easy /// Example 2 : this is an example text => This Is An Example Text - static String capitalizeAllWordsFirstLetter(String s) { - String lowerCasedString = s.toLowerCase(); - String stringWithoutExtraSpaces = lowerCasedString.trim(); + static String capitalizeAllWordsFirstLetter(final String s) { + final String lowerCasedString = s.toLowerCase(); + final String stringWithoutExtraSpaces = lowerCasedString.trim(); if (stringWithoutExtraSpaces.isEmpty) { - return ""; + return ''; } if (stringWithoutExtraSpaces.length == 1) { return stringWithoutExtraSpaces.toUpperCase(); } - List stringWordsList = stringWithoutExtraSpaces.split(" "); - List capitalizedWordsFirstLetter = stringWordsList + final List stringWordsList = stringWithoutExtraSpaces.split(' '); + final List capitalizedWordsFirstLetter = stringWordsList .map( - (word) { - if (word.trim().isEmpty) return ""; + (final word) { + if (word.trim().isEmpty) return ''; return word.trim(); }, ) .where( - (word) => word != "", + (final word) => word != '', ) .map( - (word) { + (final word) { if (word.startsWith(RegExp(r'[\n\t\r]'))) { return word; } @@ -627,27 +627,27 @@ class GetUtils { }, ) .toList(); - String finalResult = capitalizedWordsFirstLetter.join(" "); + final String finalResult = capitalizedWordsFirstLetter.join(' '); return finalResult; } - static bool hasMatch(String? value, String pattern) { + static bool hasMatch(final String? value, final String pattern) { return (value == null) ? false : RegExp(pattern).hasMatch(value); } - static String createPath(String path, [Iterable? segments]) { + static String createPath(final String path, [final Iterable? segments]) { if (segments == null || segments.isEmpty) { return path; } - final list = segments.map((e) => '/$e'); + final list = segments.map((final e) => '/$e'); return path + list.join(); } static void printFunction( - String prefix, - dynamic value, - String info, { - bool isError = false, + final String prefix, + final dynamic value, + final String info, { + final bool isError = false, }) { Get.log('$prefix $value $info'.trim(), isError: isError); } diff --git a/lib/get_utils/src/queue/get_queue.dart b/lib/get_utils/src/queue/get_queue.dart index 25e78bd54..886b18536 100644 --- a/lib/get_utils/src/queue/get_queue.dart +++ b/lib/get_utils/src/queue/get_queue.dart @@ -7,7 +7,7 @@ class GetMicrotask { int get microtask => _microtask; int get version => _version; - void exec(Function callback) { + void exec(final Function callback) { if (_microtask == _version) { _microtask++; scheduleMicrotask(() { @@ -23,8 +23,8 @@ class GetQueue { final List<_Item> _queue = []; bool _active = false; - Future add(Function job) { - var completer = Completer(); + Future add(final Function job) { + final completer = Completer(); _queue.add(_Item(completer, job)); _check(); return completer.future; @@ -37,7 +37,7 @@ class GetQueue { void _check() async { if (!_active && _queue.isNotEmpty) { _active = true; - var item = _queue.removeAt(0); + final item = _queue.removeAt(0); try { item.completer.complete(await item.job()); } on Exception catch (e) { @@ -50,8 +50,8 @@ class GetQueue { } class _Item { - final dynamic completer; - final dynamic job; _Item(this.completer, this.job); + final dynamic completer; + final dynamic job; } diff --git a/lib/get_utils/src/widgets/otimized_listview.dart b/lib/get_utils/src/widgets/optimized_listview.dart similarity index 61% rename from lib/get_utils/src/widgets/otimized_listview.dart rename to lib/get_utils/src/widgets/optimized_listview.dart index 5692b1975..4e0210be2 100644 --- a/lib/get_utils/src/widgets/otimized_listview.dart +++ b/lib/get_utils/src/widgets/optimized_listview.dart @@ -1,20 +1,10 @@ import 'package:flutter/material.dart'; -class OtimizedListView extends StatelessWidget { - final List list; - final Axis scrollDirection; - final bool reverse; - final ScrollController? controller; - final bool? primary; - final ScrollPhysics? physics; - final bool shrinkWrap; - final Widget onEmpty; - final int length; - final Widget Function(BuildContext context, ValueKey key, T item) builder; - const OtimizedListView({ - Key? key, +class OptimizedListView extends StatelessWidget { + const OptimizedListView({ required this.list, required this.builder, + super.key, this.scrollDirection = Axis.vertical, this.reverse = false, this.controller, @@ -22,11 +12,22 @@ class OtimizedListView extends StatelessWidget { this.physics, this.onEmpty = const SizedBox.shrink(), this.shrinkWrap = false, - }) : length = list.length, - super(key: key); + }) : length = list.length; + final List list; + final Axis scrollDirection; + final bool reverse; + final ScrollController? controller; + final bool? primary; + final ScrollPhysics? physics; + final bool shrinkWrap; + final Widget onEmpty; + final int length; + final Widget Function(BuildContext context, ValueKey key, T item) builder; @override - Widget build(BuildContext context) { - if (list.isEmpty) return onEmpty; + Widget build(final BuildContext context) { + if (list.isEmpty) { + return onEmpty; + } return CustomScrollView( controller: controller, @@ -38,15 +39,15 @@ class OtimizedListView extends StatelessWidget { slivers: [ SliverList( delegate: SliverChildBuilderDelegate( - (context, i) { - final item = list[i]; - final key = ValueKey(item); + (final BuildContext context, final int i) { + final T item = list[i]; + final ValueKey key = ValueKey(item); return builder(context, key, item); }, childCount: list.length, - addAutomaticKeepAlives: true, - findChildIndexCallback: (key) { - return list.indexWhere((m) => m == (key as ValueKey).value); + findChildIndexCallback: (final Key key) { + return list + .indexWhere((final T m) => m == (key as ValueKey).value); }, ), ), diff --git a/lib/src/responsive/size_percent_extension.dart b/lib/src/responsive/size_percent_extension.dart index 660f2c20c..54f21019c 100644 --- a/lib/src/responsive/size_percent_extension.dart +++ b/lib/src/responsive/size_percent_extension.dart @@ -3,7 +3,7 @@ import '../../get.dart'; //Converts a double value to a percentage extension PercentSized on double { // height: 50.0.hp = 50% - double get hp => (Get.height * (this / 100)); + double get hp => Get.height * (this / 100); // width: 30.0.hp = 30% - double get wp => (Get.width * (this / 100)); + double get wp => Get.width * (this / 100); } diff --git a/pubspec.yaml b/pubspec.yaml index 9b447c536..b2e27eb5a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,7 +4,8 @@ version: 5.0.0-release-candidate-5 homepage: https://github.com/jonataslaw/getx environment: - sdk: ">=3.0.0 <4.0.0" + sdk: ">=3.1.5 <4.0.0" + flutter: ">=1.17.0" dependencies: flutter: @@ -13,43 +14,7 @@ dependencies: sdk: flutter dev_dependencies: - flutter_lints: ^2.0.3 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: - - # To add assets to your package, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - # - # For details regarding assets in packages, see - # https://flutter.dev/assets-and-images/#from-packages - # - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.dev/assets-and-images/#resolution-aware. - - # To add custom fonts to your package, 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 in packages, see - # https://flutter.dev/custom-fonts/#from-packages diff --git a/test/animations/extensions_test.dart b/test/animations/extensions_test.dart index 00c2024fb..fb4bee0c3 100644 --- a/test/animations/extensions_test.dart +++ b/test/animations/extensions_test.dart @@ -13,7 +13,7 @@ void main() { } testWidgets('fadeIn() and fadeOut() can not be used sequentially', - (WidgetTester tester) async { + (final WidgetTester tester) async { final widget = buildWidget(); expect(() => widget.fadeIn().fadeOut(), throwsAssertionError); @@ -26,7 +26,7 @@ void main() { }); testWidgets('can not use delay when isSequential is true', - (WidgetTester tester) async { + (final WidgetTester tester) async { final widget = buildWidget(); expect( @@ -37,7 +37,7 @@ void main() { testWidgets( 'fadeIn() and fadeOut() can be used together when isSequential is true', - (WidgetTester tester) async { + (final WidgetTester tester) async { final widget = buildWidget(); expect( @@ -49,7 +49,7 @@ void main() { }); testWidgets('fadeIn() returns a FadeInAnimation', - (WidgetTester tester) async { + (final WidgetTester tester) async { final widget = buildWidget(); const begin = 0.0; const end = 1.0; @@ -61,7 +61,7 @@ void main() { animation: animation, widget: widget, begin: begin, end: end); }); - testWidgets('fadeOut() returns a animation', (WidgetTester tester) async { + testWidgets('fadeOut() returns a animation', (final WidgetTester tester) async { final widget = buildWidget(); const begin = 1.0; const end = 0.0; @@ -74,7 +74,7 @@ void main() { }); testWidgets('rotate() returns a RotateAnimation', - (WidgetTester tester) async { + (final WidgetTester tester) async { const begin = 0.9; const end = 1.1; final widget = buildWidget(); @@ -87,7 +87,7 @@ void main() { }); testWidgets('scale() returns a ScaleAnimation', - (WidgetTester tester) async { + (final WidgetTester tester) async { const begin = 0.9; const end = 1.1; final widget = buildWidget(); @@ -100,11 +100,11 @@ void main() { }); testWidgets('slide() returns a SlideAnimation', - (WidgetTester tester) async { + (final WidgetTester tester) async { const begin = 0; const end = 1; final widget = buildWidget(); - final animation = widget.slide(offset: (_, __) => const Offset(0, 0)); + final animation = widget.slide(offset: (final _, final __) => const Offset(0, 0)); expect(animation, isA()); @@ -113,7 +113,7 @@ void main() { }); testWidgets('bounce() returns a BounceAnimation', - (WidgetTester tester) async { + (final WidgetTester tester) async { const begin = 0.9; const end = 1.1; final widget = buildWidget(); @@ -130,7 +130,7 @@ void main() { ); }); - testWidgets('spin() returns a SpinAnimation', (WidgetTester tester) async { + testWidgets('spin() returns a SpinAnimation', (final WidgetTester tester) async { final widget = buildWidget(); const begin = 0.0; const end = 360; @@ -142,7 +142,7 @@ void main() { animation: animation, widget: widget, begin: begin, end: end); }); - testWidgets('size() returns a SizeAnimation', (WidgetTester tester) async { + testWidgets('size() returns a SizeAnimation', (final WidgetTester tester) async { final widget = buildWidget(); const begin = 0.9; @@ -155,7 +155,7 @@ void main() { animation: animation, widget: widget, begin: begin, end: end); }); - testWidgets('blur() returns a BlurAnimation', (WidgetTester tester) async { + testWidgets('blur() returns a BlurAnimation', (final WidgetTester tester) async { final widget = buildWidget(); const begin = 0.9; @@ -168,7 +168,7 @@ void main() { animation: animation, widget: widget, begin: begin, end: end); }); - testWidgets('flip() returns a FlipAnimation', (WidgetTester tester) async { + testWidgets('flip() returns a FlipAnimation', (final WidgetTester tester) async { final widget = buildWidget(); const begin = 0.9; @@ -181,7 +181,7 @@ void main() { animation: animation, widget: widget, begin: begin, end: end); }); - testWidgets('wave() returns a FlipAnimation', (WidgetTester tester) async { + testWidgets('wave() returns a FlipAnimation', (final WidgetTester tester) async { final widget = buildWidget(); const begin = 0.9; @@ -197,11 +197,11 @@ void main() { } void _testDefaultValues({ - required GetAnimatedBuilder animation, - required Widget widget, - required T begin, - required T end, - Curve curve = Curves.linear, + required final GetAnimatedBuilder animation, + required final Widget widget, + required final T begin, + required final T end, + final Curve curve = Curves.linear, }) { expect(animation.tween.begin, begin); expect(animation.tween.end, end); diff --git a/test/animations/get_animated_builder_test.dart b/test/animations/get_animated_builder_test.dart index 664c7ea1a..5249c0572 100644 --- a/test/animations/get_animated_builder_test.dart +++ b/test/animations/get_animated_builder_test.dart @@ -7,7 +7,7 @@ class _Wrapper extends StatelessWidget { final Widget child; @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return MaterialApp( home: Scaffold(body: child), ); @@ -15,14 +15,14 @@ class _Wrapper extends StatelessWidget { } void main() { - testWidgets('GetAnimatedBuilder defaults', (WidgetTester tester) async { + testWidgets('GetAnimatedBuilder defaults', (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: GetAnimatedBuilder( duration: const Duration(milliseconds: 500), tween: Tween(begin: 0, end: 10), idleValue: 0, - builder: (_, value, __) => Text(value.toString()), + builder: (final _, final value, final __) => Text(value.toString()), delay: Duration.zero, child: Container(), ), @@ -39,14 +39,14 @@ void main() { expect(find.text('10'), findsOneWidget); }); - testWidgets('GetAnimatedBuilder changes value over time', (tester) async { + testWidgets('GetAnimatedBuilder changes value over time', (final tester) async { await tester.pumpWidget( _Wrapper( child: GetAnimatedBuilder( duration: const Duration(milliseconds: 500), tween: Tween(begin: 0.0, end: 1.0), idleValue: 0.0, - builder: (context, value, child) { + builder: (final context, final value, final child) { return Opacity(opacity: value); }, delay: const Duration(milliseconds: 500), @@ -88,7 +88,7 @@ void main() { }); testWidgets('onComplete callback is called when animation finishes', - (WidgetTester tester) async { + (final WidgetTester tester) async { AnimationController? controller; var onCompleteCalled = false; @@ -98,9 +98,9 @@ void main() { duration: const Duration(milliseconds: 500), tween: Tween(begin: 0, end: 10), idleValue: 0, - builder: (_, value, __) => Text(value.toString()), + builder: (final _, final value, final __) => Text(value.toString()), delay: Duration.zero, - onComplete: (c) { + onComplete: (final c) { onCompleteCalled = true; controller = c; }, @@ -121,7 +121,7 @@ void main() { }); testWidgets('onStart callback is called when animation starts', - (WidgetTester tester) async { + (final WidgetTester tester) async { var onStartCalled = false; await tester.pumpWidget( @@ -131,9 +131,9 @@ void main() { delay: Duration.zero, tween: Tween(begin: 0, end: 1), idleValue: 0, - builder: (context, value, child) => Container(), + builder: (final context, final value, final child) => Container(), child: Container(), - onStart: (_) { + onStart: (final _) { onStartCalled = true; }, ), @@ -146,14 +146,14 @@ void main() { expect(onStartCalled, isTrue); }); - testWidgets('GetAnimatedBuilder delay', (WidgetTester tester) async { + testWidgets('GetAnimatedBuilder delay', (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: GetAnimatedBuilder( duration: const Duration(milliseconds: 500), tween: Tween(begin: 0, end: 10), idleValue: 0, - builder: (_, value, __) => Text(value.toString()), + builder: (final _, final value, final __) => Text(value.toString()), delay: const Duration(milliseconds: 500), child: Container(), ), @@ -178,13 +178,12 @@ void main() { testWidgets( 'FadeInAnimation in idle should be visible, but not visible when the animation starts', - (WidgetTester tester) async { + (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: FadeInAnimation( delay: const Duration(milliseconds: 500), duration: const Duration(milliseconds: 500), - idleValue: 0, child: const Text('Hello'), ), ), @@ -225,7 +224,7 @@ void main() { testWidgets( 'willResetOnDispose should false when fadeOut is the last animation in a sequential animation', - (WidgetTester tester) async { + (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: const Text('Hello') @@ -262,7 +261,7 @@ void main() { testWidgets( 'willResetOnDispose should true when fadeOut is not last animation in a sequential animation', - (WidgetTester tester) async { + (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: const Text('Hello') @@ -297,7 +296,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('RotateAnimation', (WidgetTester tester) async { + testWidgets('RotateAnimation', (final WidgetTester tester) async { await tester.pumpWidget( RotateAnimation( duration: const Duration(seconds: 1), @@ -311,7 +310,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('ScaleAnimation', (WidgetTester tester) async { + testWidgets('ScaleAnimation', (final WidgetTester tester) async { await tester.pumpWidget( ScaleAnimation( duration: const Duration(seconds: 1), @@ -325,7 +324,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('WaveAnimation', (WidgetTester tester) async { + testWidgets('WaveAnimation', (final WidgetTester tester) async { await tester.pumpWidget( WaveAnimation( duration: const Duration(seconds: 1), @@ -339,7 +338,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('WobbleAnimation', (WidgetTester tester) async { + testWidgets('WobbleAnimation', (final WidgetTester tester) async { await tester.pumpWidget( WobbleAnimation( duration: const Duration(seconds: 1), @@ -353,10 +352,10 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('SlideAnimation', (WidgetTester tester) async { + testWidgets('SlideAnimation', (final WidgetTester tester) async { await tester.pumpWidget( SlideAnimation( - offsetBuild: (p0, p1) => const Offset(1.0, 1.0), + offsetBuild: (final p0, final p1) => const Offset(1.0, 1.0), duration: const Duration(seconds: 1), delay: Duration.zero, begin: 0, @@ -368,7 +367,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('SlideInLeftAnimation', (WidgetTester tester) async { + testWidgets('SlideInLeftAnimation', (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: SlideInLeftAnimation( @@ -384,7 +383,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('SlideInRightAnimation', (WidgetTester tester) async { + testWidgets('SlideInRightAnimation', (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: SlideInRightAnimation( @@ -400,7 +399,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('SlideInUpAnimation', (WidgetTester tester) async { + testWidgets('SlideInUpAnimation', (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: SlideInUpAnimation( @@ -416,7 +415,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('SlideInDownAnimation', (WidgetTester tester) async { + testWidgets('SlideInDownAnimation', (final WidgetTester tester) async { await tester.pumpWidget( _Wrapper( child: SlideInDownAnimation( @@ -432,7 +431,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('BounceAnimation', (WidgetTester tester) async { + testWidgets('BounceAnimation', (final WidgetTester tester) async { await tester.pumpWidget( BounceAnimation( duration: const Duration(seconds: 1), @@ -446,7 +445,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('SpinAnimation', (WidgetTester tester) async { + testWidgets('SpinAnimation', (final WidgetTester tester) async { await tester.pumpWidget( SpinAnimation( duration: const Duration(seconds: 1), @@ -458,7 +457,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('ColorAnimation', (WidgetTester tester) async { + testWidgets('ColorAnimation', (final WidgetTester tester) async { await tester.pumpWidget( ColorAnimation( duration: const Duration(seconds: 1), @@ -472,7 +471,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('SizeAnimation', (WidgetTester tester) async { + testWidgets('SizeAnimation', (final WidgetTester tester) async { await tester.pumpWidget( SizeAnimation( duration: const Duration(seconds: 1), @@ -486,7 +485,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('BlurAnimation', (WidgetTester tester) async { + testWidgets('BlurAnimation', (final WidgetTester tester) async { await tester.pumpWidget( BlurAnimation( duration: const Duration(seconds: 1), @@ -500,7 +499,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('FlipAnimation', (WidgetTester tester) async { + testWidgets('FlipAnimation', (final WidgetTester tester) async { await tester.pumpWidget( FlipAnimation( duration: const Duration(seconds: 1), diff --git a/test/benchmarks/benckmark_test.dart b/test/benchmarks/benckmark_test.dart index f2dcf51d6..f8a367759 100644 --- a/test/benchmarks/benckmark_test.dart +++ b/test/benchmarks/benckmark_test.dart @@ -6,7 +6,7 @@ import 'package:get/state_manager.dart'; int times = 30; -void printValue(String value) { +void printValue(final String value) { // ignore: avoid_print print(value); } @@ -21,7 +21,7 @@ Future valueNotifier() { if (times == value.value) { timer.stop(); printValue( - """${value.value} listeners notified | [VALUE_NOTIFIER] time: ${timer.elapsedMicroseconds}ms"""); + '''${value.value} listeners notified | [VALUE_NOTIFIER] time: ${timer.elapsedMicroseconds}ms'''); c.complete(timer.elapsedMicroseconds); } }); @@ -43,7 +43,7 @@ Future getValue() { if (times == value.value) { timer.stop(); printValue( - """${value.value} listeners notified | [GETX_VALUE] time: ${timer.elapsedMicroseconds}ms"""); + '''${value.value} listeners notified | [GETX_VALUE] time: ${timer.elapsedMicroseconds}ms'''); c.complete(timer.elapsedMicroseconds); } }); @@ -62,11 +62,11 @@ Future stream() { final timer = Stopwatch(); timer.start(); - value.stream.listen((v) { + value.stream.listen((final v) { if (times == v) { timer.stop(); printValue( - """$v listeners notified | [STREAM] time: ${timer.elapsedMicroseconds}ms"""); + '''$v listeners notified | [STREAM] time: ${timer.elapsedMicroseconds}ms'''); c.complete(timer.elapsedMicroseconds); value.close(); } @@ -110,11 +110,11 @@ Future miniStream() { final timer = Stopwatch(); timer.start(); - value.listen((v) { + value.listen((final v) { if (times == v) { timer.stop(); printValue( - """$v listeners notified | [MINI_STREAM] time: ${timer.elapsedMicroseconds}ms"""); + '''$v listeners notified | [MINI_STREAM] time: ${timer.elapsedMicroseconds}ms'''); c.complete(timer.elapsedMicroseconds); } }); @@ -191,6 +191,6 @@ GetStream is ${calculePercentage(dart, mini).round()}% faster than Default Strea }); } -int calculePercentage(int dart, int getx) { +int calculePercentage(final int dart, final int getx) { return (dart / getx * 100).round() - 100; } diff --git a/test/instance/get_instance_test.dart b/test/instance/get_instance_test.dart index 3575bfb6b..70254d65b 100644 --- a/test/instance/get_instance_test.dart +++ b/test/instance/get_instance_test.dart @@ -121,8 +121,8 @@ void main() { test('GetxService test', () async { Get.lazyPut(() => PermanentService()); - var sv1 = Get.find(); - var sv2 = Get.find(); + final sv1 = Get.find(); + final sv2 = Get.find(); expect(sv1, sv2); expect(Get.isRegistered(), true); Get.delete(); diff --git a/test/instance/util/matcher.dart b/test/instance/util/matcher.dart index a17a76abc..b978294d2 100644 --- a/test/instance/util/matcher.dart +++ b/test/instance/util/matcher.dart @@ -28,36 +28,36 @@ import 'package:flutter_test/flutter_test.dart'; class FunctionMatcher extends CustomMatcher { - final Object Function(T value) _feature; - FunctionMatcher(String name, this._feature, matcher) + FunctionMatcher(final String name, this._feature, final matcher) : super('`$name`:', '`$name`', matcher); + final Object Function(T value) _feature; @override - Object featureValueOf(covariant T actual) => _feature(actual); + Object featureValueOf(covariant final T actual) => _feature(actual); } class HavingMatcher implements TypeMatcher { - final TypeMatcher _parent; - final List> _functionMatchers; - HavingMatcher(TypeMatcher parent, String description, - Object Function(T) feature, dynamic matcher, - [Iterable>? existing]) + HavingMatcher(final TypeMatcher parent, final String description, + final Object Function(T) feature, final dynamic matcher, + [final Iterable>? existing]) : _parent = parent, _functionMatchers = [ ...?existing, FunctionMatcher(description, feature, matcher) ]; + final TypeMatcher _parent; + final List> _functionMatchers; @override TypeMatcher having( - Object Function(T) feature, String description, dynamic matcher) => + final Object Function(T) feature, final String description, final dynamic matcher) => HavingMatcher(_parent, description, feature, matcher, _functionMatchers); @override - bool matches(dynamic item, Map matchState) { - for (var matcher in [_parent].followedBy(_functionMatchers)) { + bool matches(final dynamic item, final Map matchState) { + for (final matcher in [_parent].followedBy(_functionMatchers)) { if (!matcher.matches(item, matchState)) { addStateInfo(matchState, {'matcher': matcher}); return false; @@ -68,19 +68,19 @@ class HavingMatcher implements TypeMatcher { @override Description describeMismatch( - dynamic item, - Description mismatchDescription, - Map matchState, - bool verbose, + final dynamic item, + final Description mismatchDescription, + final Map matchState, + final bool verbose, ) { - var matcher = matchState['matcher'] as Matcher; + final matcher = matchState['matcher'] as Matcher; matcher.describeMismatch( item, mismatchDescription, matchState['state'] as Map, verbose); return mismatchDescription; } @override - Description describe(Description description) => description + Description describe(final Description description) => description .add('') .addDescriptionOf(_parent) .add(' with ') @@ -91,30 +91,30 @@ class TypeMatcher extends Matcher { const TypeMatcher(); TypeMatcher having( - Object Function(T) feature, String description, dynamic matcher) => + final Object Function(T) feature, final String description, final dynamic matcher) => HavingMatcher(this, description, feature, matcher); @override - Description describe(Description description) { - var name = _stripDynamic(T); + Description describe(final Description description) { + final name = _stripDynamic(T); return description.add(""); } @override - bool matches(Object? item, Map matchState) => item is T; + bool matches(final Object? item, final Map matchState) => item is T; @override Description describeMismatch( - dynamic item, - Description mismatchDescription, - Map matchState, - bool verbose, + final dynamic item, + final Description mismatchDescription, + final Map matchState, + final bool verbose, ) { - var name = _stripDynamic(T); + final name = _stripDynamic(T); return mismatchDescription.add("is not an instance of '$name'"); } } -String _stripDynamic(Type type) => +String _stripDynamic(final Type type) => type.toString().replaceAll(_dart2DynamicArgs, ''); final _dart2DynamicArgs = RegExp(''); diff --git a/test/internationalization/internationalization_test.dart b/test/internationalization/internationalization_test.dart index 19b1d14f5..25aa33c06 100644 --- a/test/internationalization/internationalization_test.dart +++ b/test/internationalization/internationalization_test.dart @@ -5,7 +5,7 @@ import 'package:get/get.dart'; import '../navigation/utils/wrapper.dart'; void main() { - testWidgets("Get.defaultDialog smoke test", (tester) async { + testWidgets('Get.defaultDialog smoke test', (final tester) async { await tester.pumpWidget( Wrapper(child: Container()), ); diff --git a/test/navigation/bottomsheet_test.dart b/test/navigation/bottomsheet_test.dart index 6852462cf..134b04577 100644 --- a/test/navigation/bottomsheet_test.dart +++ b/test/navigation/bottomsheet_test.dart @@ -5,7 +5,7 @@ import 'package:get/get.dart'; import 'utils/wrapper.dart'; void main() { - testWidgets("Get.bottomSheet smoke test", (tester) async { + testWidgets('Get.bottomSheet smoke test', (final tester) async { await tester.pumpWidget( Wrapper(child: Container()), ); @@ -27,7 +27,7 @@ void main() { expect(find.byIcon(Icons.music_note), findsOneWidget); }); - testWidgets("Get.bottomSheet close test", (tester) async { + testWidgets('Get.bottomSheet close test', (final tester) async { await tester.pumpWidget( Wrapper(child: Container()), ); diff --git a/test/navigation/dialog_test.dart b/test/navigation/dialog_test.dart index 849402a87..a37713e7c 100644 --- a/test/navigation/dialog_test.dart +++ b/test/navigation/dialog_test.dart @@ -5,7 +5,7 @@ import 'package:get/get.dart'; import 'utils/wrapper.dart'; void main() { - testWidgets("Get.defaultDialog smoke test", (tester) async { + testWidgets('Get.defaultDialog smoke test', (final tester) async { await tester.pumpWidget( Wrapper(child: Container()), ); @@ -13,14 +13,14 @@ void main() { await tester.pump(); Get.defaultDialog( - onConfirm: () {}, middleText: "Dialog made in 3 lines of code"); + onConfirm: () {}, middleText: 'Dialog made in 3 lines of code'); await tester.pumpAndSettle(); - expect(find.text("Ok"), findsOneWidget); + expect(find.text('Ok'), findsOneWidget); }); - testWidgets("Get.dialog smoke test", (tester) async { + testWidgets('Get.dialog smoke test', (final tester) async { await tester.pumpWidget( Wrapper(child: Container()), ); @@ -34,7 +34,7 @@ void main() { expect(find.byType(YourDialogWidget), findsOneWidget); }); - testWidgets("Get.dialog close test", (tester) async { + testWidgets('Get.dialog close test', (final tester) async { await tester.pumpWidget( Wrapper(child: Container()), ); @@ -57,10 +57,10 @@ void main() { } class YourDialogWidget extends StatelessWidget { - const YourDialogWidget({Key? key}) : super(key: key); + const YourDialogWidget({super.key}); @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return Container(); } } diff --git a/test/navigation/dispose_dependencies_test.dart b/test/navigation/dispose_dependencies_test.dart index 04aa4568b..d4a06e5d7 100644 --- a/test/navigation/dispose_dependencies_test.dart +++ b/test/navigation/dispose_dependencies_test.dart @@ -5,7 +5,7 @@ import 'package:get/get.dart'; import 'utils/wrapper.dart'; void main() { - testWidgets("Test dispose dependencies with unnamed routes", (tester) async { + testWidgets('Test dispose dependencies with unnamed routes', (final tester) async { await tester.pumpWidget( Wrapper(child: Container()), ); @@ -56,10 +56,10 @@ class First extends StatelessWidget { const First({super.key}); @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { Get.put(Controller()); return const Center( - child: Text("first"), + child: Text('first'), ); } } @@ -68,10 +68,10 @@ class Second extends StatelessWidget { const Second({super.key}); @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { Get.put(Controller2()); return const Center( - child: Text("second"), + child: Text('second'), ); } } diff --git a/test/navigation/get_main_test.dart b/test/navigation/get_main_test.dart index 56d13bb8e..28bed2cd5 100644 --- a/test/navigation/get_main_test.dart +++ b/test/navigation/get_main_test.dart @@ -5,7 +5,7 @@ import 'package:get/get.dart'; import 'utils/wrapper.dart'; void main() { - testWidgets("Get.to navigates to provided route", (tester) async { + testWidgets('Get.to navigates to provided route', (final tester) async { await tester.pumpWidget(Wrapper(child: Container())); Get.to(() => const FirstScreen()); @@ -15,7 +15,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("Get.toNamed navigates to provided named route", (tester) async { + testWidgets('Get.toNamed navigates to provided named route', (final tester) async { await tester.pumpWidget(GetMaterialApp( initialRoute: '/first', getPages: [ @@ -32,7 +32,7 @@ void main() { expect(find.byType(SecondScreen), findsOneWidget); }); - testWidgets("unknowroute", (tester) async { + testWidgets('unknowroute', (final tester) async { await tester.pumpWidget(GetMaterialApp( initialRoute: '/first', unknownRoute: GetPage(name: '/404', page: () => const Scaffold()), @@ -51,7 +51,7 @@ void main() { '/404'); }); - testWidgets("Get.off navigates to provided route", (tester) async { + testWidgets('Get.off navigates to provided route', (final tester) async { await tester.pumpWidget(const Wrapper(child: FirstScreen())); // await tester.pump(); @@ -62,7 +62,7 @@ void main() { expect(find.byType(SecondScreen), findsOneWidget); }); - testWidgets("Get.off removes current route", (tester) async { + testWidgets('Get.off removes current route', (final tester) async { await tester.pumpWidget(const Wrapper(child: FirstScreen())); await tester.pump(); @@ -74,7 +74,7 @@ void main() { expect(find.byType(FirstScreen), findsNothing); }); - testWidgets("Get.offNamed navigates to provided named route", (tester) async { + testWidgets('Get.offNamed navigates to provided named route', (final tester) async { await tester.pumpWidget(GetMaterialApp( initialRoute: '/first', getPages: [ @@ -93,7 +93,7 @@ void main() { expect(find.byType(SecondScreen), findsOneWidget); }); - testWidgets("Get.offNamed removes current route", (tester) async { + testWidgets('Get.offNamed removes current route', (final tester) async { await tester.pumpWidget(GetMaterialApp( initialRoute: '/first', getPages: [ @@ -114,7 +114,7 @@ void main() { expect(find.byType(FirstScreen), findsNothing); }); - testWidgets("Get.offNamed removes only current route", (tester) async { + testWidgets('Get.offNamed removes only current route', (final tester) async { await tester.pumpWidget(GetMaterialApp( initialRoute: '/first', getPages: [ @@ -137,7 +137,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets("Get.offAll navigates to provided route", (tester) async { + testWidgets('Get.offAll navigates to provided route', (final tester) async { await tester.pumpWidget(const Wrapper(child: FirstScreen())); await tester.pump(); @@ -148,7 +148,7 @@ void main() { expect(find.byType(SecondScreen), findsOneWidget); }); - testWidgets("Get.offAll removes all previous routes", (tester) async { + testWidgets('Get.offAll removes all previous routes', (final tester) async { await tester.pumpWidget(const Wrapper(child: FirstScreen())); await tester.pump(); @@ -168,8 +168,8 @@ void main() { expect(find.byType(FirstScreen), findsNothing); }); - testWidgets("Get.offAllNamed navigates to provided named route", - (tester) async { + testWidgets('Get.offAllNamed navigates to provided named route', + (final tester) async { await tester.pumpWidget(WrapperNamed( initialRoute: '/first', namedRoutes: [ @@ -188,7 +188,7 @@ void main() { expect(find.byType(SecondScreen), findsOneWidget); }); - testWidgets("Get.offAllNamed removes all previous routes", (tester) async { + testWidgets('Get.offAllNamed removes all previous routes', (final tester) async { await tester.pumpWidget(WrapperNamed( initialRoute: '/first', namedRoutes: [ @@ -216,7 +216,7 @@ void main() { expect(find.byType(FirstScreen), findsNothing); }); - testWidgets("Get.offAndToNamed navigates to provided route", (tester) async { + testWidgets('Get.offAndToNamed navigates to provided route', (final tester) async { await tester.pumpWidget(WrapperNamed( initialRoute: '/first', namedRoutes: [ @@ -233,7 +233,7 @@ void main() { expect(find.byType(SecondScreen), findsOneWidget); }); - testWidgets("Get.offAndToNamed removes previous route", (tester) async { + testWidgets('Get.offAndToNamed removes previous route', (final tester) async { await tester.pumpWidget(WrapperNamed( initialRoute: '/first', namedRoutes: [ @@ -253,7 +253,7 @@ void main() { expect(find.byType(FirstScreen), findsNothing); }); - testWidgets("Get.offUntil navigates to provided route", (tester) async { + testWidgets('Get.offUntil navigates to provided route', (final tester) async { await tester.pumpWidget(Wrapper(child: Container())); Get.to(() => const FirstScreen()); @@ -261,7 +261,7 @@ void main() { await tester.pumpAndSettle(); Get.offUntil( - () => const ThirdScreen(), (route) => route.name == '/FirstScreen'); + () => const ThirdScreen(), (final route) => route.name == '/FirstScreen'); await tester.pumpAndSettle(); @@ -270,7 +270,7 @@ void main() { testWidgets( "Get.offUntil removes previous routes if they don't match predicate", - (tester) async { + (final tester) async { await tester.pumpWidget(Wrapper(child: Container())); Get.to(() => const FirstScreen()); @@ -278,7 +278,7 @@ void main() { Get.to(() => const SecondScreen()); await tester.pumpAndSettle(); Get.offUntil( - () => const ThirdScreen(), (route) => route.name == '/FirstScreen'); + () => const ThirdScreen(), (final route) => route.name == '/FirstScreen'); await tester.pumpAndSettle(); Get.back(); @@ -288,8 +288,8 @@ void main() { }); testWidgets( - "Get.offUntil leaves previous routes that match provided predicate", - (tester) async { + 'Get.offUntil leaves previous routes that match provided predicate', + (final tester) async { await tester.pumpWidget(Wrapper(child: Container())); Get.to(() => const FirstScreen()); @@ -297,7 +297,7 @@ void main() { Get.to(() => const SecondScreen()); await tester.pumpAndSettle(); Get.offUntil( - () => const ThirdScreen(), (route) => route.name == '/FirstScreen'); + () => const ThirdScreen(), (final route) => route.name == '/FirstScreen'); await tester.pumpAndSettle(); Get.back(); @@ -306,7 +306,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("Get.offNamedUntil navigates to provided route", (tester) async { + testWidgets('Get.offNamedUntil navigates to provided route', (final tester) async { await tester.pumpWidget(WrapperNamed( initialRoute: '/first', namedRoutes: [ @@ -316,7 +316,7 @@ void main() { ], )); - Get.offNamedUntil('/second', (route) => route.name == '/first'); + Get.offNamedUntil('/second', (final route) => route.name == '/first'); await tester.pumpAndSettle(); @@ -325,7 +325,7 @@ void main() { testWidgets( "Get.offNamedUntil removes previous routes if they don't match predicate", - (tester) async { + (final tester) async { await tester.pumpWidget(WrapperNamed( initialRoute: '/first', namedRoutes: [ @@ -337,7 +337,7 @@ void main() { Get.toNamed('/second'); await tester.pumpAndSettle(); - Get.offNamedUntil('/third', (route) => route.name == '/first'); + Get.offNamedUntil('/third', (final route) => route.name == '/first'); await tester.pumpAndSettle(); @@ -345,8 +345,8 @@ void main() { }); testWidgets( - "Get.offNamedUntil leaves previous routes that match provided predicate", - (tester) async { + 'Get.offNamedUntil leaves previous routes that match provided predicate', + (final tester) async { await tester.pumpWidget(WrapperNamed( initialRoute: '/first', namedRoutes: [ @@ -358,7 +358,7 @@ void main() { Get.toNamed('/second'); await tester.pumpAndSettle(); - Get.offNamedUntil('/third', (route) => route.name == '/first'); + Get.offNamedUntil('/third', (final route) => route.name == '/first'); await tester.pumpAndSettle(); Get.back(); @@ -367,7 +367,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("Get.back navigates back", (tester) async { + testWidgets('Get.back navigates back', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.circularReveal, @@ -390,8 +390,8 @@ void main() { }); testWidgets( - "Get.back with closeOverlays pops both snackbar and current route", - (tester) async { + 'Get.back with closeOverlays pops both snackbar and current route', + (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.circularReveal, @@ -405,7 +405,7 @@ void main() { await tester.pumpAndSettle(); Get.to(() => const SecondScreen()); await tester.pumpAndSettle(); - Get.snackbar('title', "message"); + Get.snackbar('title', 'message'); await tester.pumpAndSettle(); Get.backLegacy(closeOverlays: true); @@ -416,8 +416,8 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - group("Get.defaultTransition smoke test", () { - testWidgets("fadeIn", (tester) async { + group('Get.defaultTransition smoke test', () { + testWidgets('fadeIn', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.fadeIn, @@ -432,7 +432,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("downToUp", (tester) async { + testWidgets('downToUp', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.downToUp, @@ -447,7 +447,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("fade", (tester) async { + testWidgets('fade', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.fade, @@ -462,7 +462,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("leftToRight", (tester) async { + testWidgets('leftToRight', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.leftToRight, @@ -477,7 +477,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("leftToRightWithFade", (tester) async { + testWidgets('leftToRightWithFade', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.leftToRightWithFade, @@ -492,7 +492,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("leftToRightWithFade", (tester) async { + testWidgets('leftToRightWithFade', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.rightToLeft, @@ -507,7 +507,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("defaultTransition", (tester) async { + testWidgets('defaultTransition', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.rightToLeft, @@ -522,7 +522,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("rightToLeftWithFade", (tester) async { + testWidgets('rightToLeftWithFade', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.rightToLeftWithFade, @@ -537,7 +537,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("cupertino", (tester) async { + testWidgets('cupertino', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.cupertino, @@ -552,7 +552,7 @@ void main() { expect(find.byType(FirstScreen), findsOneWidget); }); - testWidgets("size", (tester) async { + testWidgets('size', (final tester) async { await tester.pumpWidget( Wrapper( defaultTransition: Transition.size, @@ -570,29 +570,29 @@ void main() { } class FirstScreen extends StatelessWidget { - const FirstScreen({Key? key}) : super(key: key); + const FirstScreen({super.key}); @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { // ignore: avoid_unnecessary_containers return Container(child: const Text('FirstScreen')); } } class SecondScreen extends StatelessWidget { - const SecondScreen({Key? key}) : super(key: key); + const SecondScreen({super.key}); @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return Container(); } } class ThirdScreen extends StatelessWidget { - const ThirdScreen({Key? key}) : super(key: key); + const ThirdScreen({super.key}); @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return Container(); } } diff --git a/test/navigation/middleware_test.dart b/test/navigation/middleware_test.dart index d6c509376..7470ff5ca 100644 --- a/test/navigation/middleware_test.dart +++ b/test/navigation/middleware_test.dart @@ -11,7 +11,7 @@ class RedirectMiddleware extends GetMiddleware { // } @override - Future redirectDelegate(RouteDecoder route) async { + Future redirectDelegate(final RouteDecoder route) async { return RouteDecoder.fromRoute('/second'); } } @@ -23,13 +23,13 @@ class RedirectMiddlewareNull extends GetMiddleware { // } @override - Future redirectDelegate(RouteDecoder route) async { + Future redirectDelegate(final RouteDecoder route) async { return null; } } void main() { - testWidgets("Middleware redirect smoke test", (tester) async { + testWidgets('Middleware redirect smoke test', (final tester) async { await tester.pumpWidget( GetMaterialApp( initialRoute: '/', @@ -53,7 +53,7 @@ void main() { expect(find.byType(SecondScreen), findsOneWidget); }); - testWidgets("Middleware redirect null test", (tester) async { + testWidgets('Middleware redirect null test', (final tester) async { await tester.pumpWidget( GetMaterialApp( initialRoute: '/', diff --git a/test/navigation/parse_route_test.dart b/test/navigation/parse_route_test.dart index 770435c10..b40d9c776 100644 --- a/test/navigation/parse_route_test.dart +++ b/test/navigation/parse_route_test.dart @@ -128,7 +128,7 @@ void main() { testWidgets( 'test params from dynamic route', - (tester) async { + (final tester) async { await tester.pumpWidget(GetMaterialApp( initialRoute: '/first/juan', getPages: [ @@ -173,7 +173,7 @@ void main() { testWidgets( 'params in url by parameters', - (tester) async { + (final tester) async { await tester.pumpWidget(GetMaterialApp( initialRoute: '/first/juan', getPages: [ @@ -183,13 +183,13 @@ void main() { )); // Get.parameters = ({"varginias": "varginia", "vinis": "viniiss"}); - var parameters = { - "varginias": "varginia", - "vinis": "viniiss" + final parameters = { + 'varginias': 'varginia', + 'vinis': 'viniiss' }; // print("Get.parameters: ${Get.parameters}"); - parameters.addAll({"a": "b", "c": "d"}); - Get.toNamed("/italy", parameters: parameters); + parameters.addAll({'a': 'b', 'c': 'd'}); + Get.toNamed('/italy', parameters: parameters); await tester.pumpAndSettle(); expect(Get.parameters['varginias'], 'varginia'); diff --git a/test/navigation/snackbar_test.dart b/test/navigation/snackbar_test.dart index f561b6dbd..ec92a2c1a 100644 --- a/test/navigation/snackbar_test.dart +++ b/test/navigation/snackbar_test.dart @@ -3,8 +3,8 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:get/get.dart'; void main() { - testWidgets("test if Get.isSnackbarOpen works with Get.snackbar", - (tester) async { + testWidgets('test if Get.isSnackbarOpen works with Get.snackbar', + (final tester) async { await tester.pumpWidget( GetMaterialApp( popGesture: true, @@ -13,7 +13,7 @@ void main() { onPressed: () { Get.snackbar( 'title', - "message", + 'message', duration: const Duration(seconds: 1), mainButton: TextButton(onPressed: () {}, child: const Text('button')), @@ -34,7 +34,7 @@ void main() { expect(Get.isSnackbarOpen, false); }); - testWidgets("Get.rawSnackbar test", (tester) async { + testWidgets('Get.rawSnackbar test', (final tester) async { await tester.pumpWidget( GetMaterialApp( popGesture: true, @@ -43,13 +43,11 @@ void main() { onPressed: () { Get.rawSnackbar( title: 'title', - message: "message", - onTap: (_) {}, - shouldIconPulse: true, + message: 'message', + onTap: (final _) {}, icon: const Icon(Icons.alarm), showProgressIndicator: true, duration: const Duration(seconds: 1), - isDismissible: true, leftBarIndicatorColor: Colors.amber, overlayBlur: 1.0, ); @@ -70,7 +68,7 @@ void main() { expect(Get.isSnackbarOpen, false); }); - testWidgets("test snackbar queue", (tester) async { + testWidgets('test snackbar queue', (final tester) async { const messageOne = Text('title'); const messageTwo = Text('titleTwo'); @@ -106,7 +104,7 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets("test snackbar dismissible", (tester) async { + testWidgets('test snackbar dismissible', (final tester) async { const dismissDirection = DismissDirection.vertical; const snackBarTapTarget = Key('snackbar-tap-target'); @@ -115,7 +113,7 @@ void main() { await tester.pumpWidget(GetMaterialApp( home: Scaffold( body: Builder( - builder: (context) { + builder: (final context) { return Column( children: [ GestureDetector( @@ -124,7 +122,6 @@ void main() { getBar = const GetSnackBar( message: 'bar1', duration: Duration(seconds: 2), - isDismissible: true, dismissDirection: dismissDirection, ); Get.showSnackbar(getBar); @@ -160,7 +157,7 @@ void main() { expect(Get.isSnackbarOpen, false); }); - testWidgets("test snackbar onTap", (tester) async { + testWidgets('test snackbar onTap', (final tester) async { const dismissDirection = DismissDirection.vertical; const snackBarTapTarget = Key('snackbar-tap-target'); var counter = 0; @@ -172,7 +169,7 @@ void main() { await tester.pumpWidget(GetMaterialApp( home: Scaffold( body: Builder( - builder: (context) { + builder: (final context) { return Column( children: [ GestureDetector( @@ -180,11 +177,10 @@ void main() { onTap: () { getBar = GetSnackBar( message: 'bar1', - onTap: (_) { + onTap: (final _) { counter++; }, duration: const Duration(seconds: 2), - isDismissible: true, dismissDirection: dismissDirection, ); getBarController = Get.showSnackbar(getBar); @@ -220,7 +216,7 @@ void main() { await getBarController.close(withAnimations: false); }); - testWidgets("Get test actions and icon", (tester) async { + testWidgets('Get test actions and icon', (final tester) async { const icon = Icon(Icons.alarm); final action = TextButton(onPressed: () {}, child: const Text('button')); diff --git a/test/navigation/utils/wrapper.dart b/test/navigation/utils/wrapper.dart index 5d9261cdc..d36105924 100644 --- a/test/navigation/utils/wrapper.dart +++ b/test/navigation/utils/wrapper.dart @@ -2,21 +2,21 @@ import 'package:flutter/material.dart'; import 'package:get/get.dart'; class Wrapper extends StatelessWidget { - final Widget? child; - final List? namedRoutes; - final String? initialRoute; - final Transition? defaultTransition; const Wrapper({ - Key? key, + super.key, this.child, this.namedRoutes, this.initialRoute, this.defaultTransition, - }) : super(key: key); + }); + final Widget? child; + final List? namedRoutes; + final String? initialRoute; + final Transition? defaultTransition; @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return GetMaterialApp( defaultTransition: defaultTransition, initialRoute: initialRoute, @@ -33,21 +33,21 @@ class Wrapper extends StatelessWidget { } class WrapperNamed extends StatelessWidget { - final Widget? child; - final List? namedRoutes; - final String? initialRoute; - final Transition? defaultTransition; const WrapperNamed({ - Key? key, + super.key, this.child, this.namedRoutes, this.initialRoute, this.defaultTransition, - }) : super(key: key); + }); + final Widget? child; + final List? namedRoutes; + final String? initialRoute; + final Transition? defaultTransition; @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return GetMaterialApp( defaultTransition: defaultTransition, initialRoute: initialRoute, diff --git a/test/rx/rx_workers_test.dart b/test/rx/rx_workers_test.dart index accb40f71..ba2dcfca4 100644 --- a/test/rx/rx_workers_test.dart +++ b/test/rx/rx_workers_test.dart @@ -7,7 +7,7 @@ void main() { test('once', () async { final count = 0.obs; var result = -1; - once(count, (dynamic _) { + once(count, (final dynamic _) { result = _ as int; }); count.value++; @@ -24,7 +24,7 @@ void main() { test('ever', () async { final count = 0.obs; var result = -1; - ever(count, (value) { + ever(count, (final value) { result = value; }); count.value++; @@ -41,7 +41,7 @@ void main() { test('debounce', () async { final count = 0.obs; int? result = -1; - debounce(count, (dynamic _) { + debounce(count, (final dynamic _) { // print(_); result = _ as int?; }, time: const Duration(milliseconds: 100)); @@ -59,7 +59,7 @@ void main() { test('interval', () async { final count = 0.obs; int? result = -1; - interval(count, (v) { + interval(count, (final v) { result = v; }, time: const Duration(milliseconds: 100)); @@ -84,7 +84,7 @@ void main() { final controller = StreamController(); final rx = 0.obs; - rx.listen((value) { + rx.listen((final value) { count = value; }); rx.bindStream(controller.stream); @@ -97,9 +97,9 @@ void main() { }); test('Rx same value will not call the same listener when call', () async { - var reactiveInteger = RxInt(2); + final reactiveInteger = RxInt(2); var timesCalled = 0; - reactiveInteger.listen((newInt) { + reactiveInteger.listen((final newInt) { timesCalled++; }); @@ -114,9 +114,9 @@ void main() { }); test('Rx different value will call the listener when trigger', () async { - var reactiveInteger = RxInt(0); + final reactiveInteger = RxInt(0); var timesCalled = 0; - reactiveInteger.listen((newInt) { + reactiveInteger.listen((final newInt) { timesCalled++; }); @@ -132,9 +132,9 @@ void main() { }); test('Rx same value will call the listener when trigger', () async { - var reactiveInteger = RxInt(2); + final reactiveInteger = RxInt(2); var timesCalled = 0; - reactiveInteger.listen((newInt) { + reactiveInteger.listen((final newInt) { timesCalled++; }); @@ -150,41 +150,41 @@ void main() { }); test('Rx String with non null values', () async { - final reactiveString = Rx("abc"); + final reactiveString = Rx('abc'); String? currentString; - reactiveString.listen((newString) { + reactiveString.listen((final newString) { currentString = newString; }); - expect(reactiveString.endsWith("c"), true); + expect(reactiveString.endsWith('c'), true); // we call 3 - reactiveString("b"); + reactiveString('b'); await Future.delayed(Duration.zero); - expect(currentString, "b"); + expect(currentString, 'b'); }); test('Rx String with null values', () async { - var reactiveString = Rx(null); + final reactiveString = Rx(null); String? currentString; - reactiveString.listen((newString) { + reactiveString.listen((final newString) { currentString = newString; }); // we call 3 - reactiveString("abc"); + reactiveString('abc'); await Future.delayed(Duration.zero); - expect(reactiveString.endsWith("c"), true); - expect(currentString, "abc"); + expect(reactiveString.endsWith('c'), true); + expect(currentString, 'abc'); }); test('Number of times "ever" is called in RxList', () async { final list = [1, 2, 3].obs; var count = 0; - ever>(list, (value) { + ever>(list, (final value) { count++; }); @@ -203,12 +203,12 @@ void main() { expect(count, 1); count = 0; - list.removeWhere((element) => element == 2); + list.removeWhere((final element) => element == 2); await Future.delayed(Duration.zero); expect(count, 1); count = 0; - list.retainWhere((element) => element == 1); + list.retainWhere((final element) => element == 1); await Future.delayed(Duration.zero); expect(count, 1); }); diff --git a/test/state_manager/get_mixin_state_test.dart b/test/state_manager/get_mixin_state_test.dart index 1a5a278f3..f12d64234 100644 --- a/test/state_manager/get_mixin_state_test.dart +++ b/test/state_manager/get_mixin_state_test.dart @@ -4,14 +4,15 @@ import 'package:get/get.dart'; import 'package:get/get_state_manager/src/simple/mixin_builder.dart'; void main() { - testWidgets("MixinBuilder with reactive and not reactive", (tester) async { + testWidgets('MixinBuilder with reactive and not reactive', + (final WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: MixinBuilder( init: Controller(), - builder: (controller) { + builder: (final Controller controller) { return Column( - children: [ + children: [ Text( 'Count: ${controller.counter.value}', ), @@ -34,11 +35,11 @@ void main() { 'Map: ${controller.map.length}', ), TextButton( - child: const Text("increment"), + child: const Text('increment'), onPressed: () => controller.increment(), ), TextButton( - child: const Text("increment2"), + child: const Text('increment2'), onPressed: () => controller.increment2(), ) ], @@ -48,31 +49,31 @@ void main() { ), ); - expect(find.text("Count: 0"), findsOneWidget); - expect(find.text("Count2: 0"), findsOneWidget); - expect(find.text("Double: 0.0"), findsOneWidget); - expect(find.text("String: string"), findsOneWidget); - expect(find.text("Bool: true"), findsOneWidget); - expect(find.text("List: 0"), findsOneWidget); - expect(find.text("Map: 0"), findsOneWidget); + expect(find.text('Count: 0'), findsOneWidget); + expect(find.text('Count2: 0'), findsOneWidget); + expect(find.text('Double: 0.0'), findsOneWidget); + expect(find.text('String: string'), findsOneWidget); + expect(find.text('Bool: true'), findsOneWidget); + expect(find.text('List: 0'), findsOneWidget); + expect(find.text('Map: 0'), findsOneWidget); Controller.to.increment(); await tester.pump(); - expect(find.text("Count: 1"), findsOneWidget); + expect(find.text('Count: 1'), findsOneWidget); await tester.tap(find.text('increment')); await tester.pump(); - expect(find.text("Count: 2"), findsOneWidget); + expect(find.text('Count: 2'), findsOneWidget); await tester.tap(find.text('increment2')); await tester.pump(); - expect(find.text("Count2: 1"), findsOneWidget); + expect(find.text('Count2: 1'), findsOneWidget); }); // testWidgets( @@ -89,14 +90,14 @@ void main() { // ); } -class Controller extends GetxController { +class Controller extends GetxController { static Controller get to => Get.find(); int count = 0; RxInt counter = 0.obs; RxDouble doubleNum = 0.0.obs; - RxString string = "string".obs; - RxList list = [].obs; - RxMap map = {}.obs; + RxString string = 'string'.obs; + RxList list = [].obs; + RxMap map = {}.obs; RxBool boolean = true.obs; void increment() { diff --git a/test/state_manager/get_obx_test.dart b/test/state_manager/get_obx_test.dart index 41626a1f2..69651bd29 100644 --- a/test/state_manager/get_obx_test.dart +++ b/test/state_manager/get_obx_test.dart @@ -3,7 +3,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:get/get.dart'; void main() { - testWidgets("GetxController smoke test", (tester) async { + testWidgets('GetxController smoke test', (final tester) async { final controller = Get.put(Controller()); await tester.pumpWidget( MaterialApp( @@ -19,7 +19,7 @@ void main() { Text('Map: ${controller.map.length}'), TextButton( onPressed: controller.increment, - child: const Text("increment"), + child: const Text('increment'), ), Obx(() => Text('Obx: ${controller.map.length}')) ]), @@ -29,25 +29,25 @@ void main() { ), ); - expect(find.text("Count: 0"), findsOneWidget); - expect(find.text("Double: 0.0"), findsOneWidget); - expect(find.text("String: string"), findsOneWidget); - expect(find.text("Bool: true"), findsOneWidget); - expect(find.text("List: 0"), findsOneWidget); - expect(find.text("Map: 0"), findsOneWidget); - expect(find.text("Obx: 0"), findsOneWidget); + expect(find.text('Count: 0'), findsOneWidget); + expect(find.text('Double: 0.0'), findsOneWidget); + expect(find.text('String: string'), findsOneWidget); + expect(find.text('Bool: true'), findsOneWidget); + expect(find.text('List: 0'), findsOneWidget); + expect(find.text('Map: 0'), findsOneWidget); + expect(find.text('Obx: 0'), findsOneWidget); Controller.to.increment(); await tester.pump(); - expect(find.text("Count: 1"), findsOneWidget); + expect(find.text('Count: 1'), findsOneWidget); await tester.tap(find.text('increment')); await tester.pump(); - expect(find.text("Count: 2"), findsOneWidget); + expect(find.text('Count: 2'), findsOneWidget); }); } @@ -56,7 +56,7 @@ class Controller extends GetxController { RxInt counter = 0.obs; RxDouble doubleNum = 0.0.obs; - RxString string = "string".obs; + RxString string = 'string'.obs; RxList list = [].obs; RxMap map = {}.obs; RxBool boolean = true.obs; diff --git a/test/state_manager/get_rxstate_test.dart b/test/state_manager/get_rxstate_test.dart index aef1c2f16..2a302a34a 100644 --- a/test/state_manager/get_rxstate_test.dart +++ b/test/state_manager/get_rxstate_test.dart @@ -4,12 +4,12 @@ import 'package:get/get.dart'; void main() { Get.lazyPut(() => Controller2()); - testWidgets("GetxController smoke test", (tester) async { + testWidgets('GetxController smoke test', (final tester) async { await tester.pumpWidget( MaterialApp( home: GetX( init: Controller(), - builder: (controller) { + builder: (final controller) { return Column( children: [ Text( @@ -31,16 +31,16 @@ void main() { 'Map: ${controller.map.length}', ), TextButton( - child: const Text("increment"), + child: const Text('increment'), onPressed: () => controller.increment(), ), - GetX(builder: (controller) { + GetX(builder: (final controller) { return Text('lazy ${controller.lazy.value}'); }), GetX( init: ControllerNonGlobal(), global: false, - builder: (controller) { + builder: (final controller) { return Text('single ${controller.nonGlobal.value}'); }) ], @@ -50,26 +50,26 @@ void main() { ), ); - expect(find.text("Count: 0"), findsOneWidget); - expect(find.text("Double: 0.0"), findsOneWidget); - expect(find.text("String: string"), findsOneWidget); - expect(find.text("Bool: true"), findsOneWidget); - expect(find.text("List: 0"), findsOneWidget); - expect(find.text("Map: 0"), findsOneWidget); + expect(find.text('Count: 0'), findsOneWidget); + expect(find.text('Double: 0.0'), findsOneWidget); + expect(find.text('String: string'), findsOneWidget); + expect(find.text('Bool: true'), findsOneWidget); + expect(find.text('List: 0'), findsOneWidget); + expect(find.text('Map: 0'), findsOneWidget); Controller.to.increment(); await tester.pump(); - expect(find.text("Count: 1"), findsOneWidget); + expect(find.text('Count: 1'), findsOneWidget); await tester.tap(find.text('increment')); await tester.pump(); - expect(find.text("Count: 2"), findsOneWidget); - expect(find.text("lazy 0"), findsOneWidget); - expect(find.text("single 0"), findsOneWidget); + expect(find.text('Count: 2'), findsOneWidget); + expect(find.text('lazy 0'), findsOneWidget); + expect(find.text('single 0'), findsOneWidget); }); } @@ -86,7 +86,7 @@ class Controller extends GetxController { RxInt counter = 0.obs; RxDouble doubleNum = 0.0.obs; - RxString string = "string".obs; + RxString string = 'string'.obs; RxList list = [].obs; RxMap map = {}.obs; RxBool boolean = true.obs; diff --git a/test/state_manager/get_state_test.dart b/test/state_manager/get_state_test.dart index 2272e2dc1..849a10e9a 100644 --- a/test/state_manager/get_state_test.dart +++ b/test/state_manager/get_state_test.dart @@ -4,39 +4,39 @@ import 'package:get/get.dart'; void main() { Get.lazyPut(() => Controller2()); - testWidgets("GetxController smoke test", (test) async { + testWidgets('GetxController smoke test', (final test) async { await test.pumpWidget( MaterialApp( home: GetBuilder( init: Controller(), - builder: (controller) => Column( + builder: (final controller) => Column( children: [ Text( '${controller.counter}', ), TextButton( - child: const Text("increment"), + child: const Text('increment'), onPressed: () => controller.increment(), ), TextButton( - child: const Text("incrementWithId"), + child: const Text('incrementWithId'), onPressed: () => controller.incrementWithId(), ), GetBuilder( id: '1', - didChangeDependencies: (_) { + didChangeDependencies: (final _) { // print("didChangeDependencies called"); }, - builder: (controller) { + builder: (final controller) { return Text('id ${controller.counter}'); }), - GetBuilder(builder: (controller) { + GetBuilder(builder: (final controller) { return Text('lazy ${controller.test}'); }), GetBuilder( init: ControllerNonGlobal(), global: false, - builder: (controller) { + builder: (final controller) { return Text('single ${controller.nonGlobal}'); }) ], @@ -45,27 +45,27 @@ void main() { ), ); - expect(find.text("0"), findsOneWidget); + expect(find.text('0'), findsOneWidget); Controller.to.increment(); await test.pump(); - expect(find.text("1"), findsOneWidget); + expect(find.text('1'), findsOneWidget); await test.tap(find.text('increment')); await test.pump(); - expect(find.text("2"), findsOneWidget); + expect(find.text('2'), findsOneWidget); await test.tap(find.text('incrementWithId')); await test.pump(); - expect(find.text("id 3"), findsOneWidget); - expect(find.text("lazy 0"), findsOneWidget); - expect(find.text("single 0"), findsOneWidget); + expect(find.text('id 3'), findsOneWidget); + expect(find.text('lazy 0'), findsOneWidget); + expect(find.text('single 0'), findsOneWidget); }); // testWidgets( diff --git a/test/utils/extensions/context_extensions_test.dart b/test/utils/extensions/context_extensions_test.dart index ac7ed85ec..e0827de60 100644 --- a/test/utils/extensions/context_extensions_test.dart +++ b/test/utils/extensions/context_extensions_test.dart @@ -5,65 +5,65 @@ import 'package:get/get.dart'; import '../../navigation/utils/wrapper.dart'; void main() { - testWidgets("Get.defaultDialog smoke test", (tester) async { + testWidgets('Get.defaultDialog smoke test', (final tester) async { await tester.pumpWidget(Wrapper(child: Container())); await tester.pumpAndSettle(); final BuildContext context = tester.element(find.byType(Container)); - var mediaQuery = MediaQuery.of(context); + final mediaQuery = MediaQuery.of(context); expect(mediaQuery, context.mediaQuery); - var mediaQuerySize = mediaQuery.size; + final mediaQuerySize = mediaQuery.size; expect(mediaQuerySize, context.mediaQuerySize); - var theme = Theme.of(context); + final theme = Theme.of(context); expect(theme, context.theme); - var textTheme = theme.textTheme; + final textTheme = theme.textTheme; expect(textTheme, context.textTheme); - var devicePixelRatio = mediaQuery.devicePixelRatio; + final devicePixelRatio = mediaQuery.devicePixelRatio; expect(devicePixelRatio, context.devicePixelRatio); - var height = mediaQuerySize.height; + final height = mediaQuerySize.height; expect(height, context.height); final heightTransformer = (mediaQuerySize.height - ((mediaQuerySize.height / 100) * 0)) / 1; expect(heightTransformer, context.heightTransformer()); - var iconColor = theme.iconTheme.color; + final iconColor = theme.iconTheme.color; expect(iconColor, context.iconColor); - var isDarkMode = (theme.brightness == Brightness.dark); + final isDarkMode = (theme.brightness == Brightness.dark); expect(isDarkMode, context.isDarkMode); - var orientation = mediaQuery.orientation; + final orientation = mediaQuery.orientation; expect(orientation, context.orientation); - var isLandscape = orientation == Orientation.landscape; + final isLandscape = orientation == Orientation.landscape; expect(isLandscape, context.isLandscape); - var mediaQueryShortestSide = mediaQuerySize.shortestSide; + final mediaQueryShortestSide = mediaQuerySize.shortestSide; expect(mediaQueryShortestSide, context.mediaQueryShortestSide); - var width = mediaQuerySize.width; + final width = mediaQuerySize.width; expect(width, context.width); - var isLargeTabletOrWider = (width >= 720); + final isLargeTabletOrWider = width >= 720; expect(isLargeTabletOrWider, context.isLargeTabletOrWider); - var isPhoneOrLess = (width < 600); + final isPhoneOrLess = width < 600; expect(isPhoneOrLess, context.isPhoneOrLess); - var isPortrait = orientation == Orientation.portrait; + final isPortrait = orientation == Orientation.portrait; expect(isPortrait, context.isPortrait); - var isSmallTabletOrWider = (width >= 600); + final isSmallTabletOrWider = width >= 600; expect(isSmallTabletOrWider, context.isSmallTabletOrWider); - var isTablet = isSmallTabletOrWider || isLargeTabletOrWider; + final isTablet = isSmallTabletOrWider || isLargeTabletOrWider; expect(isTablet, context.isSmallTabletOrWider); - var mediaQueryPadding = mediaQuery.padding; + final mediaQueryPadding = mediaQuery.padding; expect(mediaQueryPadding, context.mediaQueryPadding); - var mediaQueryViewInsets = mediaQuery.viewInsets; + final mediaQueryViewInsets = mediaQuery.viewInsets; expect(mediaQueryViewInsets, context.mediaQueryViewInsets); - var mediaQueryViewPadding = mediaQuery.viewPadding; + final mediaQueryViewPadding = mediaQuery.viewPadding; expect(mediaQueryViewPadding, context.mediaQueryViewPadding); - var widthTransformer = + final widthTransformer = (mediaQuerySize.width - ((mediaQuerySize.width / 100) * 0)) / 1; expect(widthTransformer, context.widthTransformer()); - var ratio = heightTransformer / widthTransformer; + final ratio = heightTransformer / widthTransformer; expect(ratio, context.ratio()); - var showNavbar = (width > 800); + final showNavbar = width > 800; expect(showNavbar, context.showNavbar); - var textScaleFactor = mediaQuery.textScaleFactor; + final textScaleFactor = mediaQuery.textScaleFactor; expect(textScaleFactor, context.textScaleFactor); }); } diff --git a/test/utils/extensions/dynamic_extensions_test.dart b/test/utils/extensions/dynamic_extensions_test.dart index 530b96f9d..5bacc55c7 100644 --- a/test/utils/extensions/dynamic_extensions_test.dart +++ b/test/utils/extensions/dynamic_extensions_test.dart @@ -3,10 +3,10 @@ import 'package:get/utils.dart'; void main() { test('String test', () { - var value = 'string'; + const value = 'string'; var expected = ''; - void logFunction(String prefix, dynamic value, String info, - {bool isError = false}) { + void logFunction(final String prefix, final dynamic value, final String info, + {final bool isError = false}) { expected = '$prefix $value $info'.trim(); } @@ -14,10 +14,10 @@ void main() { expect(expected, 'Error: String string'); }); test('Int test', () { - var value = 1; + const value = 1; var expected = ''; - void logFunction(String prefix, dynamic value, String info, - {bool isError = false}) { + void logFunction(final String prefix, final dynamic value, final String info, + {final bool isError = false}) { expected = '$prefix $value $info'.trim(); } @@ -25,10 +25,10 @@ void main() { expect(expected, 'Error: int 1'); }); test('Double test', () { - var value = 1.0; + const value = 1.0; var expected = ''; - void logFunction(String prefix, dynamic value, String info, - {bool isError = false}) { + void logFunction(final String prefix, final dynamic value, final String info, + {final bool isError = false}) { expected = '$prefix $value $info'.trim(); } diff --git a/test/utils/extensions/num_extensions_test.dart b/test/utils/extensions/num_extensions_test.dart index aec15f95a..cd837ca31 100644 --- a/test/utils/extensions/num_extensions_test.dart +++ b/test/utils/extensions/num_extensions_test.dart @@ -2,14 +2,14 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:get/utils.dart'; void main() { - num x = 5; - num y = 7; - num z = 5; + const num x = 5; + const num y = 7; + const num z = 5; - var doubleX = 2.1; - var doubleY = 3.1; - var doubleZ = 5.0; - var pi = 3.14159265359; + const doubleX = 2.1; + const doubleY = 3.1; + const doubleZ = 5.0; + const pi = 3.14159265359; group('num extensions text', () { test('var.isLowerThan(value)', () { diff --git a/test/utils/extensions/string_extensions_test.dart b/test/utils/extensions/string_extensions_test.dart index f9b75fed3..2fe1c5a89 100644 --- a/test/utils/extensions/string_extensions_test.dart +++ b/test/utils/extensions/string_extensions_test.dart @@ -3,12 +3,12 @@ import 'package:get/utils.dart'; void main() { group('String extensions', () { - const text = "oi"; - const digit = "5"; - const specialCaracters = "#\$!%@"; - const alphaNumeric = "123asd"; - const numbers = "123"; - const letters = "foo"; + const text = 'oi'; + const digit = '5'; + const specialCaracters = r'#$!%@'; + const alphaNumeric = '123asd'; + const numbers = '123'; + const letters = 'foo'; // String notInitializedVar; test('var.isNum', () { @@ -18,38 +18,38 @@ void main() { test('var.capitalizeAllWordsFirstLetter()', () { final List sentences = [ - "getx", - "this is an example sentence", - "this is an example sentence with a number 5", - "this is an example sentence with a number 5 and a special character #", - "this is an example sentence with a number 5 and a special character # and b letter C", - " emm, lemme think !", - "Bro, $letters is a good word", - "THIS IS A SENTENCE WITH ALL CAPITAL LETTERS", - "" + 'getx', + 'this is an example sentence', + 'this is an example sentence with a number 5', + 'this is an example sentence with a number 5 and a special character #', + 'this is an example sentence with a number 5 and a special character # and b letter C', + ' emm, lemme think !', + 'Bro, $letters is a good word', + 'THIS IS A SENTENCE WITH ALL CAPITAL LETTERS', + '' ]; - expect(text.capitalizeAllWordsFirstLetter(), "Oi"); - expect(digit.capitalizeAllWordsFirstLetter(), "5"); - expect(specialCaracters.capitalizeAllWordsFirstLetter(), "#\$!%@"); - expect(alphaNumeric.capitalizeAllWordsFirstLetter(), "123asd"); - expect(numbers.capitalizeAllWordsFirstLetter(), "123"); - expect(letters.capitalizeAllWordsFirstLetter(), "Foo"); - expect(sentences[0].capitalizeAllWordsFirstLetter(), "Getx"); + expect(text.capitalizeAllWordsFirstLetter(), 'Oi'); + expect(digit.capitalizeAllWordsFirstLetter(), '5'); + expect(specialCaracters.capitalizeAllWordsFirstLetter(), r'#$!%@'); + expect(alphaNumeric.capitalizeAllWordsFirstLetter(), '123asd'); + expect(numbers.capitalizeAllWordsFirstLetter(), '123'); + expect(letters.capitalizeAllWordsFirstLetter(), 'Foo'); + expect(sentences[0].capitalizeAllWordsFirstLetter(), 'Getx'); expect(sentences[1].capitalizeAllWordsFirstLetter(), - "This Is An Example Sentence"); + 'This Is An Example Sentence'); expect(sentences[2].capitalizeAllWordsFirstLetter(), - "This Is An Example Sentence With A Number 5"); + 'This Is An Example Sentence With A Number 5'); expect(sentences[3].capitalizeAllWordsFirstLetter(), - "This Is An Example Sentence With A Number 5 And A Special Character #"); + 'This Is An Example Sentence With A Number 5 And A Special Character #'); expect(sentences[4].capitalizeAllWordsFirstLetter(), - "This Is An Example Sentence With A Number 5 And A Special Character # And B Letter C"); + 'This Is An Example Sentence With A Number 5 And A Special Character # And B Letter C'); expect( - sentences[5].capitalizeAllWordsFirstLetter(), "Emm, Lemme Think !"); + sentences[5].capitalizeAllWordsFirstLetter(), 'Emm, Lemme Think !'); expect(sentences[6].capitalizeAllWordsFirstLetter(), - "Bro, Foo Is A Good Word"); + 'Bro, Foo Is A Good Word'); expect(sentences[7].capitalizeAllWordsFirstLetter(), - "This Is A Sentence With All Capital Letters"); - expect(sentences[8].capitalizeAllWordsFirstLetter(), ""); + 'This Is A Sentence With All Capital Letters'); + expect(sentences[8].capitalizeAllWordsFirstLetter(), ''); }); test('var.isNumericOnly', () { @@ -73,20 +73,20 @@ void main() { }); test('var.isVectorFileName', () { - const path = "logo.svg"; - const fullPath = "C:/Users/Getx/Documents/logo.svg"; + const path = 'logo.svg'; + const fullPath = 'C:/Users/Getx/Documents/logo.svg'; expect(path.isVectorFileName, true); expect(fullPath.isVectorFileName, true); expect(alphaNumeric.isVectorFileName, false); }); test('var.isImageFileName', () { - const jpgPath = "logo.jpg"; - const jpegPath = "logo.jpeg"; - const pngPath = "logo.png"; - const gifPath = "logo.gif"; - const bmpPath = "logo.bmp"; - const svgPath = "logo.svg"; + const jpgPath = 'logo.jpg'; + const jpegPath = 'logo.jpeg'; + const pngPath = 'logo.png'; + const gifPath = 'logo.gif'; + const bmpPath = 'logo.bmp'; + const svgPath = 'logo.svg'; expect(jpgPath.isImageFileName, true); expect(jpegPath.isImageFileName, true); @@ -97,12 +97,12 @@ void main() { }); test('var.isAudioFileName', () { - const mp3Path = "logo.mp3"; - const wavPath = "logo.wav"; - const wmaPath = "logo.wma"; - const amrPath = "logo.amr"; - const oggPath = "logo.ogg"; - const svgPath = "logo.svg"; + const mp3Path = 'logo.mp3'; + const wavPath = 'logo.wav'; + const wmaPath = 'logo.wma'; + const amrPath = 'logo.amr'; + const oggPath = 'logo.ogg'; + const svgPath = 'logo.svg'; expect(mp3Path.isAudioFileName, true); expect(wavPath.isAudioFileName, true); @@ -113,14 +113,14 @@ void main() { }); test('var.isVideoFileName', () { - const mp4Path = "logo.mp4"; - const aviPath = "logo.avi"; - const wmvPath = "logo.wmv"; - const rmvbPath = "logo.rmvb"; - const mpgPath = "logo.mpg"; - const mpegPath = "logo.mpeg"; - const threegpPath = "logo.3gp"; - const svgPath = "logo.svg"; + const mp4Path = 'logo.mp4'; + const aviPath = 'logo.avi'; + const wmvPath = 'logo.wmv'; + const rmvbPath = 'logo.rmvb'; + const mpgPath = 'logo.mpg'; + const mpegPath = 'logo.mpeg'; + const threegpPath = 'logo.3gp'; + const svgPath = 'logo.svg'; expect(mp4Path.isVideoFileName, true); expect(aviPath.isVideoFileName, true); @@ -139,8 +139,8 @@ void main() { }); test('var.isDocumentFileName', () { - const docPath = "file.doc"; - const docxPath = "file.docx"; + const docPath = 'file.doc'; + const docxPath = 'file.docx'; expect(docPath.isDocumentFileName, true); expect(docxPath.isDocumentFileName, true); @@ -148,8 +148,8 @@ void main() { }); test('var.isExcelFileName', () { - const xlsPath = "file.xls"; - const xlsxPath = "file.xlsx"; + const xlsPath = 'file.xls'; + const xlsxPath = 'file.xlsx'; expect(xlsPath.isExcelFileName, true); expect(xlsxPath.isExcelFileName, true); @@ -157,8 +157,8 @@ void main() { }); test('var.isPPTFileName', () { - const pptPath = "file.ppt"; - const pptxPath = "file.pptx"; + const pptPath = 'file.ppt'; + const pptxPath = 'file.pptx'; expect(pptPath.isPPTFileName, true); expect(pptxPath.isPPTFileName, true); @@ -166,20 +166,20 @@ void main() { }); test('var.isAPKFileName', () { - const apkPath = "file.apk"; + const apkPath = 'file.apk'; expect(apkPath.isAPKFileName, true); expect(alphaNumeric.isAPKFileName, false); }); test('var.isPDFFileName', () { - const pdfPath = "file.pdf"; + const pdfPath = 'file.pdf'; expect(pdfPath.isPDFFileName, true); expect(alphaNumeric.isPDFFileName, false); }); test('var.isHTMLFileName', () { - const htmlPath = "file.html"; + const htmlPath = 'file.html'; expect(htmlPath.isHTMLFileName, true); expect(alphaNumeric.isHTMLFileName, false); @@ -569,7 +569,7 @@ void main() { 'Redder', 'Refer', 'Repaper', - 'Don\'t nod.', + "Don't nod.", 'I did, did I?', 'My gym', 'Red rum, sir, is murder', @@ -628,8 +628,8 @@ void main() { test('var.isCurrency', () { final currencies = [ - 'R\$50.58', - '\$82.48', + r'R$50.58', + r'$82.48', '₩54.24', '¥81.04', '€4.06', diff --git a/test/utils/extensions/widget_extensions_test.dart b/test/utils/extensions/widget_extensions_test.dart index 1767c78d6..714aa4790 100644 --- a/test/utils/extensions/widget_extensions_test.dart +++ b/test/utils/extensions/widget_extensions_test.dart @@ -6,15 +6,15 @@ class Foo extends StatelessWidget { const Foo({super.key}); @override - Widget build(BuildContext context) { + Widget build(final BuildContext context) { return const SizedBox.shrink(); } } void main() { group('Group test for PaddingX Extension', () { - testWidgets('Test of paddingAll', (tester) async { - Widget containerTest = const Foo(); + testWidgets('Test of paddingAll', (final tester) async { + const Widget containerTest = Foo(); expect(find.byType(Padding), findsNothing); @@ -23,8 +23,8 @@ void main() { expect(find.byType(Padding), findsOneWidget); }); - testWidgets('Test of paddingOnly', (tester) async { - Widget containerTest = const Foo(); + testWidgets('Test of paddingOnly', (final tester) async { + const Widget containerTest = Foo(); expect(find.byType(Padding), findsNothing); @@ -33,8 +33,8 @@ void main() { expect(find.byType(Padding), findsOneWidget); }); - testWidgets('Test of paddingSymmetric', (tester) async { - Widget containerTest = const Foo(); + testWidgets('Test of paddingSymmetric', (final tester) async { + const Widget containerTest = Foo(); expect(find.byType(Padding), findsNothing); @@ -43,8 +43,8 @@ void main() { expect(find.byType(Padding), findsOneWidget); }); - testWidgets('Test of paddingZero', (tester) async { - Widget containerTest = const Foo(); + testWidgets('Test of paddingZero', (final tester) async { + const Widget containerTest = Foo(); expect(find.byType(Padding), findsNothing); @@ -55,32 +55,32 @@ void main() { }); group('Group test for MarginX Extension', () { - testWidgets('Test of marginAll', (tester) async { - Widget containerTest = const Foo(); + testWidgets('Test of marginAll', (final tester) async { + const Widget containerTest = Foo(); await tester.pumpWidget(containerTest.marginAll(16)); expect(find.byType(Container), findsOneWidget); }); - testWidgets('Test of marginOnly', (tester) async { - Widget containerTest = const Foo(); + testWidgets('Test of marginOnly', (final tester) async { + const Widget containerTest = Foo(); await tester.pumpWidget(containerTest.marginOnly(top: 16)); expect(find.byType(Container), findsOneWidget); }); - testWidgets('Test of marginSymmetric', (tester) async { - Widget containerTest = const Foo(); + testWidgets('Test of marginSymmetric', (final tester) async { + const Widget containerTest = Foo(); await tester.pumpWidget(containerTest.marginSymmetric(vertical: 16)); expect(find.byType(Container), findsOneWidget); }); - testWidgets('Test of marginZero', (tester) async { - Widget containerTest = const Foo(); + testWidgets('Test of marginZero', (final tester) async { + const Widget containerTest = Foo(); await tester.pumpWidget(containerTest.marginZero); diff --git a/test/utils/get_utils_test.dart b/test/utils/get_utils_test.dart index 68fd38b9d..9081e4767 100644 --- a/test/utils/get_utils_test.dart +++ b/test/utils/get_utils_test.dart @@ -2,13 +2,13 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:get/get.dart'; class TestClass { - final name = "John"; + final name = 'John'; } class EmptyClass {} void main() { - dynamic newId(dynamic e) => e; + dynamic newId(final dynamic e) => e; test('null isNullOrBlank should be true for null', () { expect(GetUtils.isNullOrBlank(null), true); @@ -28,13 +28,13 @@ void main() { }); test('isNullOrBlank should validate strings', () { - expect(GetUtils.isNullOrBlank(""), true); - expect(GetUtils.isNullOrBlank(" "), true); + expect(GetUtils.isNullOrBlank(''), true); + expect(GetUtils.isNullOrBlank(' '), true); - expect(GetUtils.isNullOrBlank("foo"), false); - expect(GetUtils.isNullOrBlank(" foo "), false); + expect(GetUtils.isNullOrBlank('foo'), false); + expect(GetUtils.isNullOrBlank(' foo '), false); - expect(GetUtils.isNullOrBlank("null"), false); + expect(GetUtils.isNullOrBlank('null'), false); }); test('isNullOrBlank should validate iterables', () { @@ -58,11 +58,11 @@ void main() { test('isNullOrBlank should validate maps', () { expect(GetUtils.isNullOrBlank({}), true); expect(GetUtils.isNullOrBlank({1: 1}), false); - expect(GetUtils.isNullOrBlank({"other": "thing"}), false); + expect(GetUtils.isNullOrBlank({'other': 'thing'}), false); - final map = {"foo": 'bar', "one": "um"}; - expect(GetUtils.isNullOrBlank(map["foo"]), false); - expect(GetUtils.isNullOrBlank(map["other"]), true); + final map = {'foo': 'bar', 'one': 'um'}; + expect(GetUtils.isNullOrBlank(map['foo']), false); + expect(GetUtils.isNullOrBlank(map['other']), true); }); group('GetUtils.isLength* functions', () { test('isLengthEqualTo should validate iterable lengths', () { @@ -74,9 +74,9 @@ void main() { expect(GetUtils.isLengthEqualTo({1: 1, 2: 1}, 2), true); expect(GetUtils.isLengthEqualTo({}, 2), false); - expect(GetUtils.isLengthEqualTo("", 0), true); - expect(GetUtils.isLengthEqualTo("a", 0), false); - expect(GetUtils.isLengthEqualTo("a", 1), true); + expect(GetUtils.isLengthEqualTo('', 0), true); + expect(GetUtils.isLengthEqualTo('a', 0), false); + expect(GetUtils.isLengthEqualTo('a', 1), true); }); test('isLengthGreaterOrEqual should validate lengths', () { @@ -90,9 +90,9 @@ void main() { expect(GetUtils.isLengthGreaterOrEqual({1: 1, 2: 1}, 2), true); expect(GetUtils.isLengthGreaterOrEqual({}, 2), false); - expect(GetUtils.isLengthGreaterOrEqual("", 0), true); - expect(GetUtils.isLengthGreaterOrEqual("a", 0), true); - expect(GetUtils.isLengthGreaterOrEqual("", 1), false); + expect(GetUtils.isLengthGreaterOrEqual('', 0), true); + expect(GetUtils.isLengthGreaterOrEqual('a', 0), true); + expect(GetUtils.isLengthGreaterOrEqual('', 1), false); }); test('isLengthLessOrEqual should validate lengths', () { @@ -106,9 +106,9 @@ void main() { expect(GetUtils.isLengthLessOrEqual({1: 1, 2: 1}, 3), true); expect(GetUtils.isLengthLessOrEqual({}, 2), true); - expect(GetUtils.isLengthLessOrEqual("", 0), true); - expect(GetUtils.isLengthLessOrEqual("a", 2), true); - expect(GetUtils.isLengthLessOrEqual("a", 0), false); + expect(GetUtils.isLengthLessOrEqual('', 0), true); + expect(GetUtils.isLengthLessOrEqual('a', 2), true); + expect(GetUtils.isLengthLessOrEqual('a', 0), false); }); }); }