better linting

This commit is contained in:
Mguy13 2023-01-01 13:04:22 +01:00
parent c7324a6b19
commit aa31a79d20
26 changed files with 163 additions and 131 deletions

View File

@ -1,3 +1,5 @@
include: package:very_good_analysis/analysis_options.3.1.0.yaml
analyzer:
strong-mode:
implicit-dynamic: true

View File

@ -25,7 +25,7 @@ class McgRouter {
path: Routes.imageCarousel.routePath,
name: Routes.imageCarousel.routeName,
builder: (context, state) => ImageCarouselView(
imageCarouselViewArguments: state.extra as ImageCarouselViewArguments,
imageCarouselViewArguments: state.extra! as ImageCarouselViewArguments,
),
),
],

View File

@ -17,11 +17,11 @@ enum Routes {
}
class RoutesInfo {
final String routePath;
final String routeName;
const RoutesInfo({
required this.routePath,
required this.routeName,
});
final String routePath;
final String routeName;
}

View File

@ -3,7 +3,7 @@ import 'package:flutter/material.dart';
abstract class ConstColours {
/// Smoke Gray => a neutral grey with neutral warmth/cold
static const galleryBackgroundColour = Color.fromRGBO(127, 127, 125, 1.0);
static const galleryBackgroundColour = Color.fromRGBO(127, 127, 125, 1);
static const red = Colors.red;
static const white = Colors.white;

View File

@ -1,6 +1,7 @@
import 'package:dio/dio.dart';
extension ResponseExtensions on Response {
/// Extensions on [Dio]'s [Response].
extension ResponseExtensions<T> on Response<T> {
/// Shorthand for getting response's successful state.
bool get isSuccessful => (data as Map)['response'];
bool get isSuccessful => (data! as Map<String, dynamic>)['response'] as bool;
}

View File

@ -1,3 +1,4 @@
/// String extensions
extension StringExtensions on String {
/// Returns true if given word contains atleast all the characters in [targetChars], and `false` otherwise
///
@ -6,9 +7,9 @@ extension StringExtensions on String {
required String targetChars,
bool ignoreCase = true,
}) {
final Set<String> characterSet = ignoreCase
? Set.from(targetChars.toLowerCase().split(''))
: Set.from(targetChars.split(''));
final characterSet = ignoreCase
? Set<String>.from(targetChars.toLowerCase().split(''))
: Set<String>.from(targetChars.split(''));
for (final testChar in ignoreCase ? toLowerCase().split('') : split('')) {
characterSet.remove(testChar);
if (characterSet.isEmpty) return true;

View File

@ -25,7 +25,7 @@ class AppLifecycleService with WidgetsBindingObserver {
late final StreamController<AppLifecycleState> _lifecycleStateStreamController =
StreamController.broadcast();
final Map<String, StreamSubscription> _appLifecycleSubscriptions = {};
final Map<String, StreamSubscription<dynamic>> _appLifecycleSubscriptions = {};
AppLifecycleState? _appLifeCycleState;
AppLifecycleState? get appLifeCycleState => _appLifeCycleState;

View File

@ -64,7 +64,7 @@ class ConnectionsService {
static ConnectionsService get locate => Locator.locate();
}
extension _connectionStatusEmojiExtension on InternetConnectionStatus {
extension _ConnectionStatusEmojiExtension on InternetConnectionStatus {
String get nameWithIcon {
switch (this) {
case InternetConnectionStatus.connected:
@ -75,7 +75,7 @@ extension _connectionStatusEmojiExtension on InternetConnectionStatus {
}
}
extension _connectivityEmojiExtension on ConnectivityResult {
extension _ConnectivityEmojiExtension on ConnectivityResult {
String get nameWithIcon {
switch (this) {
case ConnectivityResult.bluetooth:

View File

@ -29,7 +29,7 @@ class LocalStorageService {
}
void updateFavourite({
required index,
required int index,
required bool newValue,
}) {
try {

View File

@ -15,8 +15,8 @@ class LoggingService {
useHistory: false,
),
logger: TalkerLogger(
formater:
!Platform.isIOS ? const ColoredLoggerFormatter() : const ExtendedLoggerFormatter()),
formater: !Platform.isIOS ? const ColoredLoggerFormatter() : const ExtendedLoggerFormatter(),
),
loggerSettings: TalkerLoggerSettings(
enableColors: !Platform.isIOS,
),
@ -49,11 +49,10 @@ class LoggingService {
TalkerDioLogger(
talker: Talker(
logger: TalkerLogger(
formater: !Platform.isIOS
? const ColoredLoggerFormatter()
: const ExtendedLoggerFormatter()),
formater:
!Platform.isIOS ? const ColoredLoggerFormatter() : const ExtendedLoggerFormatter(),
),
settings: TalkerSettings(
useConsoleLogs: true,
useHistory: false,
),
loggerSettings: TalkerLoggerSettings(
@ -63,7 +62,6 @@ class LoggingService {
settings: const TalkerDioLoggerSettings(
printRequestHeaders: true,
printResponseHeaders: true,
printResponseMessage: true,
),
),
);

View File

@ -24,8 +24,9 @@ class OverlayService {
//todo(mehul): Fix and not ignore Overlay building while Widget building error.
} on FlutterError catch (_) {}
_loggingService.info('Overlay inserted with tag: $tag');
} else
} else {
_loggingService.info('Overlay with tag: $tag, NOT inserted');
}
}
void removeOverlayEntry({
@ -37,10 +38,12 @@ class OverlayService {
_overlayEntryMap[tag.hashCode]?.remove();
_overlayEntryMap.remove(tag.hashCode);
_loggingService.info('Overlay removed with tag: $tag');
} else
} else {
_loggingService.info('Overlay with tag: $tag already mounted OR not found. Skipped');
} else
}
} else {
_loggingService.info('Overlay with tag: $tag already exists. Skipped');
}
}
void dispose() {

View File

@ -4,19 +4,19 @@ import 'dart:ui';
/// A simple Mutex implementation using a [Completer].
class Mutex {
final _completerQueue = Queue<Completer>();
final _completerQueue = Queue<Completer<void>>();
/// Runs the given [run] function-block in a thread-safe/blocked zone. A convenient `unlock()`
/// is provided, which can be called anywhere to signal re-entry.
FutureOr<T> lockAndRun<T>({
required FutureOr<T> Function(VoidCallback unlock) run,
}) async {
final completer = Completer();
final completer = Completer<void>();
_completerQueue.add(completer);
if (_completerQueue.first != completer) {
await _completerQueue.removeFirst().future;
}
final value = await run(() => completer.complete());
final value = await run(completer.complete);
return value;
}

View File

@ -17,7 +17,7 @@ class ErrorPageView extends StatelessWidget {
child: Column(
children: [
Text(Strings.current.errorPageMessage),
const Gap(16),
Gap.size16,
],
),
);

View File

@ -1,8 +1,12 @@
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// Const evenly-sized gap.
class Gap extends LeafRenderObjectWidget {
const Gap(this.size, {Key? key}) : super(key: key);
const Gap(
this.size, {
super.key,
});
final double size;
@ -58,13 +62,14 @@ class RenderGap extends RenderBox {
}
}
/// Animates [Gap] insertion.
class AnimatedGap extends StatefulWidget {
const AnimatedGap(
this.gap, {
Key? key,
this.duration = const Duration(milliseconds: 200),
this.curve = Curves.easeInOut,
}) : super(key: key);
super.key,
});
final Duration duration;
final double gap;
@ -107,10 +112,10 @@ class _AnimatedGapState extends State<AnimatedGap> with SingleTickerProviderStat
class AnimatedSliverGap extends StatefulWidget {
const AnimatedSliverGap(
this.gap, {
Key? key,
this.duration = const Duration(milliseconds: 200),
this.curve = Curves.easeInOut,
}) : super(key: key);
super.key,
});
final Duration duration;
final double gap;

View File

@ -8,10 +8,13 @@ class MultiValueListenableBuilder extends StatelessWidget {
required this.builder,
this.child,
super.key,
}) : assert(valueListenables.length != 0);
}) : assert(
valueListenables.length != 0,
'Attached valueListenables must not be empty',
);
/// List of [ValueListenable]s to be listened to.
final List<ValueListenable> valueListenables;
final List<ValueListenable<dynamic>> valueListenables;
/// The builder function to be called when value of any of the [ValueListenable] changes.
/// The order of values list will be same as [valueListenables] list.

View File

@ -9,16 +9,19 @@ import '../abstracts/images_api.dart';
import '../data/dtos/image_model_dto.dart';
class UnsplashImagesApi extends ImagesApi {
UnsplashImagesApi({required super.token});
//final LoggingService _loggingService = LoggingService.locate;
final random = Random();
UnsplashImagesApi({required super.token});
@override
FutureOr<Iterable<ImageModelDTO>> fetchImageUri() async {
// Dummy fetching delay emulation
await Future.delayed(const Duration(
milliseconds: ConstValues.defaultEmulatedLatencyMillis * ConstValues.numberOfImages));
await Future<void>.delayed(
const Duration(
milliseconds: ConstValues.defaultEmulatedLatencyMillis * ConstValues.numberOfImages,
),
);
final Iterable<Map<String, dynamic>> fetchedImageModelDtos;
try {
@ -48,8 +51,7 @@ class UnsplashImagesApi extends ImagesApi {
}
// Emulating deserialization
return fetchedImageModelDtos
.map((final emulatedModelSerialized) => ImageModelDTO.fromJson(emulatedModelSerialized));
return fetchedImageModelDtos.map(ImageModelDTO.fromJson);
}
@override
@ -59,8 +61,11 @@ class UnsplashImagesApi extends ImagesApi {
final numberOfResults = random.nextIntInRange(min: 0, max: ConstValues.numberOfImages);
// Dummy fetching delay emulation
await Future.delayed(
Duration(milliseconds: ConstValues.defaultEmulatedLatencyMillis * numberOfResults));
await Future<void>.delayed(
Duration(
milliseconds: ConstValues.defaultEmulatedLatencyMillis * numberOfResults,
),
);
final Iterable<Map<String, dynamic>> searchImageModelDtos;
try {
@ -87,8 +92,7 @@ class UnsplashImagesApi extends ImagesApi {
return List.empty();
}
return searchImageModelDtos
.map((final emulatedModelSerialized) => ImageModelDTO.fromJson(emulatedModelSerialized));
return searchImageModelDtos.map(ImageModelDTO.fromJson);
}
Uri _imageUrlGenerator({required int imageSide}) => Uri(

View File

@ -2,13 +2,24 @@ import '../dtos/image_model_dto.dart';
/// Represents an Image, that would be displayed in the gallery.
class ImageModel {
const ImageModel({
const ImageModel._({
required this.uri,
required this.imageIndex,
required this.imageName,
required this.isFavourite,
});
factory ImageModel.fromDto({
required ImageModelDTO imageModelDto,
required bool isFavourite,
}) =>
ImageModel._(
uri: imageModelDto.uri,
imageIndex: imageModelDto.imageIndex,
imageName: imageModelDto.imageName,
isFavourite: isFavourite,
);
/// An image's target [Uri].
///
/// Storing an image's [ByteData] is more expensive, memory-wise.
@ -23,24 +34,13 @@ class ImageModel {
/// Whether the image was 'Starred' ot not.
final bool isFavourite;
factory ImageModel.fromDto({
required ImageModelDTO imageModelDto,
required bool isFavourite,
}) =>
ImageModel(
uri: imageModelDto.uri,
imageIndex: imageModelDto.imageIndex,
imageName: imageModelDto.imageName,
isFavourite: isFavourite,
);
ImageModel copyWith({
Uri? uri,
int? imageIndex,
String? imageName,
bool? isFavourite,
}) {
return ImageModel(
return ImageModel._(
uri: uri ?? this.uri,
imageIndex: imageIndex ?? this.imageIndex,
imageName: imageName ?? this.imageName,

View File

@ -22,7 +22,7 @@ class ImageCacheManagerService {
final LoggingService _loggingService = LoggingService.locate;
final _cacheManager = DefaultCacheManager();
Future<void> emptyCache() async => await _cacheManager.emptyCache();
void emptyCache() => _cacheManager.emptyCache();
Future<void> _init() async {
_appLifecycleService.addListener(

View File

@ -54,19 +54,25 @@ class ImagesService {
// Prefill from stored values
if (favouritesStatuses.isNotEmpty) {
_loggingService.good('Found favourites statuses on device -> Prefilling');
assert(fetchedImageModelDtos.length == favouritesStatuses.length);
_loggingService.fine('Found favourites statuses on device -> Prefilling');
assert(
fetchedImageModelDtos.length == favouritesStatuses.length,
'Downloaded images must be the same number as the statuses stored on device',
);
_imageModels = LinkedHashMap.of({
for (final pair in IterableZip([fetchedImageModelDtos, favouritesStatuses]))
(pair[0] as ImageModelDTO).imageName: ImageModel.fromDto(
imageModelDto: pair[0] as ImageModelDTO,
isFavourite: pair[1] as bool,
for (final zippedDtosAndFavourites
in IterableZip([fetchedImageModelDtos, favouritesStatuses]))
(zippedDtosAndFavourites[0] as ImageModelDTO).imageName: ImageModel.fromDto(
imageModelDto: zippedDtosAndFavourites[0] as ImageModelDTO,
isFavourite: zippedDtosAndFavourites[1] as bool,
)
});
// Set to false and create the stored values
} else {
_loggingService.good('NO favourites statuses found -> creating new');
_imageModels = LinkedHashMap.of({
for (final fetchedImageModelDto in fetchedImageModelDtos)
fetchedImageModelDto.imageName: ImageModel.fromDto(
@ -119,8 +125,10 @@ class ImagesService {
: imageName.containsAllCharacters(targetChars: imageNamePart))
.toList(growable: false)
// Sorting by the highest similarity first
..sort((final a, final b) =>
ConstSorters.stringsSimilarityTarget(targetWord: imageNamePart, a, b))
..sort(
(final a, final b) =>
ConstSorters.stringsSimilarityTarget(targetWord: imageNamePart, a, b),
)
..reversed;
return _imageModels.valuesByKeys(keys: rankedKeys).toList(growable: false);

View File

@ -150,8 +150,8 @@ class _SearchBox extends StatelessWidget {
items: [
for (final searchOption in SearchOption.values)
DropdownMenuItem(
child: Center(child: Text(searchOption.name)),
value: searchOption,
child: Center(child: Text(searchOption.name)),
),
],
value: searchOption,

View File

@ -42,7 +42,7 @@ class GalleryViewModel extends BaseViewModel {
ValueListenable<bool> get isViewingFavouriteListenable => _isViewingFavouriteNotifier;
@override
Future<void> initialise(bool Function() mounted, [arguments]) async {
Future<void> initialise(bool Function() mounted, [Object? arguments]) async {
super.initialise(mounted, arguments);
}

View File

@ -40,7 +40,7 @@ class ImageCarouselView extends StatelessWidget {
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8),
child: Card(
elevation: 8,
surfaceTintColor: ConstColours.transparent,
@ -110,7 +110,7 @@ class ImageCarouselView extends StatelessWidget {
),
),
),
const Gap(24),
Gap.size24,
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
// Assuming that this data is coming from an external CRM, if it is coming with the

View File

@ -21,9 +21,11 @@ class ImageCarouselViewModel extends BaseViewModel {
final CarouselController carouselController = CarouselController();
@override
Future<void> initialise(bool Function() mounted, [arguments]) async {
_currentImageModelNotifier = ValueNotifier(_imagesService.imageModels
.elementAt((arguments as ImageCarouselViewArguments).imageIndexKey));
Future<void> initialise(bool Function() mounted, [Object? arguments]) async {
_currentImageModelNotifier = ValueNotifier(
_imagesService.imageModels
.elementAt((arguments! as ImageCarouselViewArguments).imageIndexKey),
);
log.info('Initialized with image: ${_currentImageModelNotifier.value.imageIndex}');
super.initialise(mounted, arguments);

View File

@ -58,61 +58,59 @@ class Locator {
}
static FutureOr<void> _registerServices(GetIt it) async {
it.registerLazySingleton(
() => NavigationService(
mcgRouter: McgRouter.locate,
),
);
it.registerFactory(
() => LoggingService(),
);
it.registerSingleton<ConnectionsService>(
ConnectionsService(
connectivity: Connectivity(),
internetConnectionChecker: InternetConnectionChecker(),
loggingService: LoggingService.locate,
),
signalsReady: true,
dispose: (final param) async => await param.dispose(),
);
it
..registerLazySingleton(
() => NavigationService(
mcgRouter: McgRouter.locate,
),
)
..registerFactory(
LoggingService.new,
)
..registerSingleton<ConnectionsService>(
ConnectionsService(
connectivity: Connectivity(),
internetConnectionChecker: InternetConnectionChecker(),
loggingService: LoggingService.locate,
),
signalsReady: true,
dispose: (final param) async => param.dispose(),
);
await it.isReady<ConnectionsService>();
it.registerLazySingleton(
() => OverlayService(
loggingService: LoggingService.locate,
),
dispose: (param) => param.dispose(),
);
it.registerSingleton<AppLifecycleService>(
AppLifecycleService(
loggingService: LoggingService.locate,
),
dispose: (final param) async => await param.dispose(),
);
it.registerSingleton<LocalStorageService>(
LocalStorageService(),
signalsReady: true,
);
it
..registerLazySingleton(
() => OverlayService(
loggingService: LoggingService.locate,
),
dispose: (param) => param.dispose(),
)
..registerSingleton<AppLifecycleService>(
AppLifecycleService(
loggingService: LoggingService.locate,
),
dispose: (final param) async => param.dispose(),
)
..registerSingleton<LocalStorageService>(
LocalStorageService(),
signalsReady: true,
);
await it.isReady<LocalStorageService>();
it.registerSingleton<ImagesService>(
ImagesService(
imagesApi: UnsplashImagesApi.locate,
localStorageService: LocalStorageService.locate,
loggingService: LoggingService.locate,
),
);
it.registerSingleton(
ImageCacheManagerService(
appLifecycleService: AppLifecycleService.locate,
localStorageService: LocalStorageService.locate,
),
);
it
..registerSingleton<ImagesService>(
ImagesService(
imagesApi: UnsplashImagesApi.locate,
localStorageService: LocalStorageService.locate,
loggingService: LoggingService.locate,
),
)
..registerSingleton(
ImageCacheManagerService(
appLifecycleService: AppLifecycleService.locate,
localStorageService: LocalStorageService.locate,
),
);
}
static FutureOr<void> _registerRepos(GetIt locator) {}

View File

@ -437,7 +437,7 @@ packages:
source: hosted
version: "0.6.4"
json_annotation:
dependency: "direct dev"
dependency: "direct main"
description:
name: json_annotation
url: "https://pub.dartlang.org"
@ -833,6 +833,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.2"
very_good_analysis:
dependency: "direct dev"
description:
name: very_good_analysis
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.0"
watcher:
dependency: transitive
description:

View File

@ -36,19 +36,19 @@ dependencies:
intl_utils: ^2.8.1
connectivity_plus: ^3.0.2
internet_connection_checker: ^1.0.0+1
json_annotation: ^4.7.0
string_similarity: ^2.0.0
# Util frontend
flutter_markdown: ^0.6.13
auto_size_text: ^3.0.0
flutter_svg: ^1.1.6
carousel_slider: ^4.2.1
# Logging
talker: ^2.2.0
talker_dio_logger: ^1.0.0
# Assets
flutter_svg: ^1.1.6
dev_dependencies:
@ -63,8 +63,8 @@ dev_dependencies:
hive_generator: ^2.0.0
envied_generator: ^0.3.0
# Annotations
json_annotation: ^4.7.0
# Linters
very_good_analysis: ^3.1.0
flutter:
uses-material-design: true