Merge branch 'reimplementation'

This commit is contained in:
Kingkor Roy Tirtho
2022-05-28 18:40:03 +06:00
136 changed files with 4989 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.packages
build/
+10
View File
@@ -0,0 +1,10 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: fb57da5f945d02ef4f98dfd9409a72b7cce74268
channel: stable
project_type: package
+19
View File
@@ -0,0 +1,19 @@
library fl_query;
import 'package:flutter/material.dart';
class FlQueryScope extends StatefulWidget {
final Widget child;
const FlQueryScope({required this.child, Key? key}) : super(key: key);
@override
State<FlQueryScope> createState() => _FlQueryScopeState();
}
class _FlQueryScopeState extends State<FlQueryScope> {
@override
Widget build(BuildContext context) {
Theme.of(context);
return widget.child;
}
}
+166
View File
@@ -0,0 +1,166 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
enum QueryStatus {
failed,
succeed,
pending,
refetching;
}
typedef QueryTaskFunction<T> = FutureOr<T> Function(String);
typedef QueryListener<T> = FutureOr<void> Function(T);
typedef ListenerUnsubscriber = void Function();
class Query<T> extends ChangeNotifier {
// all params
final String queryKey;
QueryTaskFunction<T> task;
final int retries;
final Duration retryDelay;
final T? _initialData;
// got from global options
final Duration _staleTime;
// all properties
T? data;
dynamic error;
QueryStatus status;
int retryAttempts = 0;
DateTime updatedAt;
int refetchCount = 0;
@protected
bool fetched = false;
final QueryListener<T>? _onData;
final QueryListener<dynamic>? _onError;
Query({
required this.queryKey,
required this.task,
required Duration staleTime,
required this.retries,
required this.retryDelay,
T? initialData,
QueryListener<T>? onData,
QueryListener<dynamic>? onError,
}) : status = QueryStatus.pending,
_staleTime = staleTime,
_initialData = initialData,
data = initialData,
_onData = onData,
_onError = onError,
updatedAt = DateTime.now();
// all getters & setters
bool get hasData => data != null && error == null;
bool get hasError =>
status == QueryStatus.failed && error != null && data == null;
bool get isLoading =>
status == QueryStatus.pending && data == null && error == null;
bool get isRefetching =>
status == QueryStatus.refetching && (data != null || error != null);
bool get isSucceeded => status == QueryStatus.succeed && data != null;
// all methods
/// Calls the task function & doesn't check if there's already
/// cached data available
Future<void> _execute() async {
try {
retryAttempts = 0;
data = await task(queryKey);
updatedAt = DateTime.now();
status = QueryStatus.succeed;
_onData?.call(data!);
notifyListeners();
} catch (e) {
if (retries == 0) {
status = QueryStatus.failed;
error = e;
_onError?.call(e);
notifyListeners();
} else {
// retrying for retry count if failed for the first time
while (retryAttempts <= retries) {
await Future.delayed(retryDelay);
try {
data = await task(queryKey);
status = QueryStatus.succeed;
_onData?.call(data!);
notifyListeners();
break;
} catch (e) {
if (retryAttempts == retries) {
status = QueryStatus.failed;
error = e;
_onError?.call(e);
notifyListeners();
}
retryAttempts++;
}
}
}
}
}
Future<T?> fetch() async {
status = QueryStatus.pending;
notifyListeners();
if (!isStale && hasData) {
return data;
}
return _execute().then((_) {
fetched = true;
return data;
});
}
Future<T?> refetch() {
status = QueryStatus.refetching;
refetchCount++;
notifyListeners();
return _execute().then((_) => data);
}
/// can be used to update the data manually. Can be useful when used
/// together with mutations to perform optimistic updates or manual data
/// updates
/// For updating particular queries after a mutation using the
/// `QueryBowl.refetchQueries` is more appropriate. But this one can be
/// used when only 1 query needs get updated
///
/// Every time a new instance of data should be returned because of
/// immutability
update(FutureOr<T> Function(T? data) updateFn) async {
final newData = await updateFn(data);
if (data == newData) {
// TODO: Better Error handling & Error structure
throw Exception(
"[fl_query] new instance of data should be returned because of immutability");
}
data = newData;
status = QueryStatus.succeed;
notifyListeners();
}
void reset() {
refetchCount = 0;
data = _initialData;
error = null;
fetched = false;
status = QueryStatus.pending;
retryAttempts = 0;
}
bool get isStale {
// when current DateTime is after [update_at + stale_time] it means
// the data has become stale
return DateTime.now().isAfter(updatedAt.add(_staleTime));
}
}
+158
View File
@@ -0,0 +1,158 @@
import 'dart:async';
import 'package:fl_query/query.dart';
import 'package:collection/collection.dart';
import 'package:flutter/widgets.dart';
class QueryBowlScope extends StatefulWidget {
final Widget child;
final Duration staleTime;
/// used for periodically checking if any query got stale.
/// If none is supplied then half of the value of staleTime is used
final Duration? refreshInterval;
const QueryBowlScope({
required this.child,
this.staleTime = const Duration(minutes: 5),
this.refreshInterval,
Key? key,
}) : super(key: key);
@override
State<QueryBowlScope> createState() => _QueryBowlScopeState();
}
class _QueryBowlScopeState extends State<QueryBowlScope> {
late Set<Query> queries;
late Timer refreshIntervalTimer;
@override
void initState() {
super.initState();
queries = {};
refreshIntervalTimer = Timer.periodic(
widget.refreshInterval ??
Duration(
milliseconds: (widget.staleTime.inMilliseconds / 2).round(),
),
_checkAndUpdateStaleQueriesOnBg,
);
}
@override
void dispose() {
refreshIntervalTimer.cancel();
_disposeListeners();
super.dispose();
}
Future<void> _checkAndUpdateStaleQueriesOnBg([dynamic _]) async {
// checking for staled queries inside the widget as InheritedWidget
// classes has to be constant & doesn't this kind of dynamic behavior
for (final query in queries) {
if (query.isStale) await query.refetch();
}
}
void _listenToQueryUpdate() {
for (final query in queries) {
query.addListener(updateQueries);
}
}
void _disposeListeners() {
for (final query in queries) {
query.removeListener(updateQueries);
}
}
void updateQueries() {
setState(() {
queries = Set.from(queries);
});
}
void addQuery(Query query) {
setState(() {
queries = Set.from({...queries, query});
});
}
@override
Widget build(BuildContext context) {
_listenToQueryUpdate();
return QueryBowl(
onUpdate: updateQueries,
addQuery: addQuery,
queries: queries,
staleTime: widget.staleTime,
child: widget.child,
);
}
}
/// QueryBowl holds all the query related methods & properties.
/// Its responsible for creating/updating/delete queries
class QueryBowl extends InheritedWidget {
final Set<Query> _queries;
final Duration staleTime;
final void Function(Query query) _addQuery;
const QueryBowl({
required Widget child,
required final void Function() onUpdate,
required final void Function(Query query) addQuery,
required final Set<Query> queries,
required this.staleTime,
Key? key,
}) : _addQuery = addQuery,
_queries = queries,
super(child: child, key: key);
Future<T?> fetchQuery<T>(Query<T> query) async {
final prevQuery =
_queries.firstWhereOrNull((q) => q.queryKey == query.queryKey);
if (prevQuery is Query<T>) {
if (!prevQuery.hasData) {
return prevQuery.fetched
? await prevQuery.refetch()
: await prevQuery.fetch();
}
return prevQuery.data;
}
_addQuery(query);
return await query.fetch();
}
Query<T>? getQuery<T>(String queryKey) {
return _queries.firstWhereOrNull(
(query) => query.queryKey == queryKey && query is Query<T>)
as Query<T>?;
}
int get isFetching {
return _queries.fold<int>(
0,
(acc, query) {
if (query.isLoading || query.isRefetching) acc++;
return acc;
},
);
}
void resetQuery(String queryKey) {
_queries
.firstWhereOrNull((element) => element.queryKey == queryKey)
?.reset();
}
static QueryBowl of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<QueryBowl>()!;
@override
bool updateShouldNotify(QueryBowl oldWidget) {
return oldWidget.staleTime != staleTime || oldWidget._queries != _queries;
}
}
+58
View File
@@ -0,0 +1,58 @@
import 'package:fl_query/query.dart';
import 'package:fl_query/query_bowl.dart';
import 'package:flutter/widgets.dart';
class QueryBuilder<T> extends StatefulWidget {
final Widget Function(BuildContext, Query<T>) builder;
final QueryTaskFunction<T> task;
final String queryKey;
final Duration? staleTime;
final int retries;
final T? initialData;
final Duration retryDelay;
final QueryListener<T>? onData;
final QueryListener<dynamic>? onError;
const QueryBuilder({
required this.builder,
required this.task,
required this.queryKey,
this.initialData,
this.staleTime,
this.retryDelay = const Duration(milliseconds: 200),
this.retries = 3,
this.onData,
this.onError,
Key? key,
}) : super(key: key);
@override
State<QueryBuilder<T>> createState() => _QueryBuilderState<T>();
}
class _QueryBuilderState<T> extends State<QueryBuilder<T>> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
await QueryBowl.of(context).fetchQuery(Query<T>(
queryKey: widget.queryKey,
task: widget.task,
staleTime: widget.staleTime ?? QueryBowl.of(context).staleTime,
retries: widget.retries,
initialData: widget.initialData,
retryDelay: widget.retryDelay,
onData: widget.onData,
onError: widget.onError,
));
});
}
@override
Widget build(BuildContext context) {
final query = QueryBowl.of(context).getQuery<T>(widget.queryKey);
if (query == null) return Container();
return widget.builder(context, query);
}
}
+10
View File
@@ -0,0 +1,10 @@
import 'package:fl_query/query.dart';
Future<void> callQueryListeners<T>(Set<QueryListener<T>> listeners, T data) {
return Future.wait(listeners.map(
(listener) => Future.value(listener(data)),
));
// for (final listener in listeners) {
// await listener(data);
// }
}
+56
View File
@@ -0,0 +1,56 @@
name: fl_query
description: A new Flutter package project.
version: 0.0.1
homepage: https://github.com/KRTirtho/fl-query
environment:
sdk: ">=2.17.1 <3.0.0"
flutter: ">=1.17.0"
dependencies:
async: ^2.8.2
collection: ^1.16.0
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
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