mutation support added
multiple data, error/mutate listeners on query
This commit is contained in:
@@ -2,6 +2,7 @@ import 'dart:math';
|
|||||||
|
|
||||||
import 'package:example/another_component.dart';
|
import 'package:example/another_component.dart';
|
||||||
import 'package:example/lazy_query.dart';
|
import 'package:example/lazy_query.dart';
|
||||||
|
import 'package:example/mutation_example.dart';
|
||||||
import 'package:example/query_with_external_data.dart';
|
import 'package:example/query_with_external_data.dart';
|
||||||
import 'package:fl_query/fl_query.dart';
|
import 'package:fl_query/fl_query.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
@@ -137,6 +138,17 @@ class _MyHomePageState extends State<MyHomePage> {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
ElevatedButton(
|
||||||
|
child: const Text("Mutation Example"),
|
||||||
|
onPressed: () {
|
||||||
|
Navigator.of(context).push(
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (context) => const MutationExample(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
const AnotherComponent(),
|
const AnotherComponent(),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:math';
|
||||||
|
|
||||||
|
import 'package:fl_query/models/mutation_job.dart';
|
||||||
|
import 'package:fl_query/mutation_builder.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
final postSomethingJob = MutationJob<Map, Map<String, dynamic>>(
|
||||||
|
mutationKey: "post-something-job",
|
||||||
|
task: (key, data) async {
|
||||||
|
final response = await http.post(
|
||||||
|
Uri.parse(
|
||||||
|
"https://jsonplaceholder.typicode.com/posts",
|
||||||
|
),
|
||||||
|
headers: {'Content-type': 'application/json; charset=UTF-8'},
|
||||||
|
body: jsonEncode(data),
|
||||||
|
);
|
||||||
|
return jsonDecode(response.body);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
class MutationExample extends StatefulWidget {
|
||||||
|
const MutationExample({Key? key}) : super(key: key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<MutationExample> createState() => _MutationExampleState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MutationExampleState extends State<MutationExample> {
|
||||||
|
late TextEditingController titleController;
|
||||||
|
late TextEditingController bodyController;
|
||||||
|
late int id;
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
id = Random().nextInt(2000000);
|
||||||
|
titleController = TextEditingController();
|
||||||
|
bodyController = TextEditingController();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
titleController.dispose();
|
||||||
|
bodyController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(title: const Text("Post Something")),
|
||||||
|
body: MutationBuilder<Map, Map<String, dynamic>>(
|
||||||
|
job: postSomethingJob,
|
||||||
|
builder: (context, mutation) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.all(8.0),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
TextField(
|
||||||
|
controller: titleController,
|
||||||
|
decoration: const InputDecoration(labelText: "Title"),
|
||||||
|
),
|
||||||
|
TextField(
|
||||||
|
controller: bodyController,
|
||||||
|
decoration: const InputDecoration(labelText: "Body"),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () {
|
||||||
|
final title = titleController.value.text;
|
||||||
|
final body = bodyController.value.text;
|
||||||
|
if (body.isEmpty || title.isEmpty) return;
|
||||||
|
mutation.mutate({
|
||||||
|
"title": title,
|
||||||
|
"body": body,
|
||||||
|
"id": id,
|
||||||
|
}, onData: (data) {
|
||||||
|
// resetting the form
|
||||||
|
titleController.text = "";
|
||||||
|
bodyController.text = "";
|
||||||
|
});
|
||||||
|
},
|
||||||
|
child: const Text("Post"),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
if (mutation.hasData) Text("Response\n${mutation.data}")
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -81,6 +81,20 @@ packages:
|
|||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
http:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: http
|
||||||
|
url: "https://pub.dartlang.org"
|
||||||
|
source: hosted
|
||||||
|
version: "0.13.4"
|
||||||
|
http_parser:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: http_parser
|
||||||
|
url: "https://pub.dartlang.org"
|
||||||
|
source: hosted
|
||||||
|
version: "4.0.1"
|
||||||
lints:
|
lints:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -163,6 +177,13 @@ packages:
|
|||||||
url: "https://pub.dartlang.org"
|
url: "https://pub.dartlang.org"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.4.9"
|
version: "0.4.9"
|
||||||
|
typed_data:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: typed_data
|
||||||
|
url: "https://pub.dartlang.org"
|
||||||
|
source: hosted
|
||||||
|
version: "1.3.1"
|
||||||
vector_math:
|
vector_math:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ dependencies:
|
|||||||
cupertino_icons: ^1.0.2
|
cupertino_icons: ^1.0.2
|
||||||
fl_query:
|
fl_query:
|
||||||
path: ../fl_query
|
path: ../fl_query
|
||||||
|
http: ^0.13.4
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import 'package:fl_query/mutation.dart';
|
||||||
|
|
||||||
|
class MutationJob<T extends Object, V> {
|
||||||
|
final String mutationKey;
|
||||||
|
MutationTaskFunction<T, V> task;
|
||||||
|
final int? retries;
|
||||||
|
final Duration? retryDelay;
|
||||||
|
final Duration? cacheTime;
|
||||||
|
|
||||||
|
MutationJob({
|
||||||
|
required this.mutationKey,
|
||||||
|
required this.task,
|
||||||
|
this.retries,
|
||||||
|
this.retryDelay,
|
||||||
|
this.cacheTime,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:fl_query/models/mutation_job.dart';
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
|
enum MutationStatus {
|
||||||
|
failed,
|
||||||
|
succeed,
|
||||||
|
pending,
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef MutationListener<T> = FutureOr<void> Function(T);
|
||||||
|
|
||||||
|
typedef MutationTaskFunction<T, V> = FutureOr<T> Function(String, V);
|
||||||
|
|
||||||
|
class Mutation<T extends Object, V> extends ChangeNotifier {
|
||||||
|
// all params
|
||||||
|
final String mutationKey;
|
||||||
|
MutationTaskFunction<T, V> task;
|
||||||
|
final int retries;
|
||||||
|
final Duration retryDelay;
|
||||||
|
final Duration _cacheTime;
|
||||||
|
|
||||||
|
// all properties
|
||||||
|
T? data;
|
||||||
|
dynamic error;
|
||||||
|
MutationStatus status;
|
||||||
|
|
||||||
|
/// total count of how many times the query retried to get a successful
|
||||||
|
/// result
|
||||||
|
int retryAttempts = 0;
|
||||||
|
DateTime updatedAt;
|
||||||
|
|
||||||
|
/// used for keeping track of mutation activity. If the are no mounts &
|
||||||
|
/// the passed cached time is over than the mutation is removed from
|
||||||
|
/// storage/cache
|
||||||
|
Set<Widget> _mounts = {};
|
||||||
|
|
||||||
|
@protected
|
||||||
|
final Set<MutationListener<T>> onDataListeners = {};
|
||||||
|
@protected
|
||||||
|
final Set<MutationListener<dynamic>> onErrorListeners = {};
|
||||||
|
@protected
|
||||||
|
final Set<MutationListener<V>> onMutateListeners = {};
|
||||||
|
|
||||||
|
Mutation({
|
||||||
|
required this.mutationKey,
|
||||||
|
required this.task,
|
||||||
|
required this.retries,
|
||||||
|
required this.retryDelay,
|
||||||
|
required Duration cacheTime,
|
||||||
|
MutationListener<T>? onData,
|
||||||
|
MutationListener<dynamic>? onError,
|
||||||
|
MutationListener<V>? onMutate,
|
||||||
|
}) : status = MutationStatus.pending,
|
||||||
|
updatedAt = DateTime.now(),
|
||||||
|
_cacheTime = cacheTime {
|
||||||
|
if (onData != null) onDataListeners.add(onData);
|
||||||
|
if (onError != null) onErrorListeners.add(onError);
|
||||||
|
if (onMutate != null) onMutateListeners.add(onMutate);
|
||||||
|
}
|
||||||
|
|
||||||
|
Mutation.fromOptions(
|
||||||
|
MutationJob<T, V> options, {
|
||||||
|
MutationListener<T>? onData,
|
||||||
|
MutationListener<dynamic>? onError,
|
||||||
|
MutationListener<V>? onMutate,
|
||||||
|
}) : mutationKey = options.mutationKey,
|
||||||
|
task = options.task,
|
||||||
|
retries = options.retries ?? 3,
|
||||||
|
retryDelay = options.retryDelay ?? const Duration(milliseconds: 200),
|
||||||
|
_cacheTime = options.cacheTime ?? const Duration(minutes: 5),
|
||||||
|
status = MutationStatus.pending,
|
||||||
|
updatedAt = DateTime.now() {
|
||||||
|
if (onData != null) onDataListeners.add(onData);
|
||||||
|
if (onError != null) onErrorListeners.add(onError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// all getters & setters
|
||||||
|
bool get hasData => data != null && error == null;
|
||||||
|
bool get hasError =>
|
||||||
|
status == MutationStatus.failed && error != null && data == null;
|
||||||
|
bool get isLoading =>
|
||||||
|
status == MutationStatus.pending && data == null && error == null;
|
||||||
|
bool get isSucceeded => status == MutationStatus.succeed && data != null;
|
||||||
|
bool get isIdle => isSucceeded && error == null;
|
||||||
|
bool get isInactive => _mounts.isEmpty;
|
||||||
|
// all methods
|
||||||
|
|
||||||
|
void mount(Widget widget) {
|
||||||
|
_mounts.add(widget);
|
||||||
|
}
|
||||||
|
|
||||||
|
void unmount(Widget widget) {
|
||||||
|
if (_mounts.length == 1) {
|
||||||
|
Future.delayed(_cacheTime, () {
|
||||||
|
_mounts.remove(widget);
|
||||||
|
// for letting know QueryBowl that this one's time has come for
|
||||||
|
// getting crushed
|
||||||
|
notifyListeners();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
_mounts.remove(widget);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Calls the task function & doesn't check if there's already
|
||||||
|
/// cached data available
|
||||||
|
Future<void> _execMutation(V variables) async {
|
||||||
|
try {
|
||||||
|
retryAttempts = 0;
|
||||||
|
for (final onMutate in onMutateListeners) {
|
||||||
|
onMutate(variables);
|
||||||
|
}
|
||||||
|
data = await task(mutationKey, variables);
|
||||||
|
updatedAt = DateTime.now();
|
||||||
|
status = MutationStatus.succeed;
|
||||||
|
for (final onData in onDataListeners) {
|
||||||
|
onData(data!);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
} catch (e) {
|
||||||
|
if (retries == 0) {
|
||||||
|
status = MutationStatus.failed;
|
||||||
|
error = e;
|
||||||
|
for (final onError in onErrorListeners) {
|
||||||
|
onError(error);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
} else {
|
||||||
|
// retrying for retry count if failed for the first time
|
||||||
|
while (retryAttempts <= retries) {
|
||||||
|
await Future.delayed(retryDelay);
|
||||||
|
try {
|
||||||
|
for (final onMutate in onMutateListeners) {
|
||||||
|
onMutate(variables);
|
||||||
|
}
|
||||||
|
data = await task(mutationKey, variables);
|
||||||
|
status = MutationStatus.succeed;
|
||||||
|
for (final onData in onDataListeners) {
|
||||||
|
onData(data!);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
break;
|
||||||
|
} catch (e) {
|
||||||
|
if (retryAttempts == retries) {
|
||||||
|
status = MutationStatus.failed;
|
||||||
|
error = e;
|
||||||
|
for (final onError in onErrorListeners) {
|
||||||
|
onError(error);
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
retryAttempts++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void mutate(
|
||||||
|
V variables, {
|
||||||
|
MutationListener<T>? onData,
|
||||||
|
MutationListener<dynamic>? onError,
|
||||||
|
}) {
|
||||||
|
if (onData != null) onDataListeners.add(onData);
|
||||||
|
if (onError != null) onErrorListeners.add(onError);
|
||||||
|
_execMutation(variables).then((_) {
|
||||||
|
onDataListeners.remove(onData);
|
||||||
|
onErrorListeners.remove(onError);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<T?> mutateAsync(V variables) async {
|
||||||
|
return await _execMutation(variables).then((_) => data);
|
||||||
|
}
|
||||||
|
|
||||||
|
reset() {
|
||||||
|
data = null;
|
||||||
|
retryAttempts = 0;
|
||||||
|
updatedAt = DateTime.now();
|
||||||
|
onDataListeners.clear();
|
||||||
|
onErrorListeners.clear();
|
||||||
|
status = MutationStatus.pending;
|
||||||
|
onMutateListeners.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
A? cast<A>() => this is A ? this as A : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import 'package:fl_query/models/mutation_job.dart';
|
||||||
|
import 'package:fl_query/mutation.dart';
|
||||||
|
import 'package:fl_query/query_bowl.dart';
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
|
class MutationBuilder<T extends Object, V> extends StatefulWidget {
|
||||||
|
final Function(BuildContext, Mutation<T, V>) builder;
|
||||||
|
final MutationJob<T, V> job;
|
||||||
|
|
||||||
|
/// Called when the query returns new data, on query
|
||||||
|
/// refetch or query gets expired
|
||||||
|
final MutationListener<T>? onData;
|
||||||
|
|
||||||
|
/// Called when the query returns error
|
||||||
|
final MutationListener<dynamic>? onError;
|
||||||
|
|
||||||
|
/// called right before the mutation is about to run
|
||||||
|
///
|
||||||
|
/// perfect scenario for doing optimistic updates
|
||||||
|
final MutationListener<V>? onMutate;
|
||||||
|
|
||||||
|
const MutationBuilder({
|
||||||
|
required this.job,
|
||||||
|
required this.builder,
|
||||||
|
this.onData,
|
||||||
|
this.onError,
|
||||||
|
this.onMutate,
|
||||||
|
Key? key,
|
||||||
|
}) : super(key: key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<MutationBuilder<T, V>> createState() => _MutationBuilderState<T, V>();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MutationBuilderState<T extends Object, V>
|
||||||
|
extends State<MutationBuilder<T, V>> {
|
||||||
|
late QueryBowl queryBowl;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
queryBowl = QueryBowl.of(context);
|
||||||
|
queryBowl.addMutation<T, V>(
|
||||||
|
widget.job,
|
||||||
|
onData: widget.onData,
|
||||||
|
onError: widget.onError,
|
||||||
|
onMutate: widget.onMutate,
|
||||||
|
mount: widget,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
final mutation = queryBowl.getMutation(widget.job.mutationKey);
|
||||||
|
mutation?.unmount(widget);
|
||||||
|
if (widget.onData != null) mutation?.onDataListeners.remove(widget.onData);
|
||||||
|
if (widget.onError != null)
|
||||||
|
mutation?.onErrorListeners.remove(widget.onError);
|
||||||
|
if (widget.onMutate != null)
|
||||||
|
mutation?.onMutateListeners.remove(widget.onMutate);
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
queryBowl = QueryBowl.of(context);
|
||||||
|
final mutation = queryBowl.getMutation<T, V>(widget.job.mutationKey);
|
||||||
|
if (mutation == null) return Container();
|
||||||
|
return widget.builder(context, mutation);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -46,8 +46,11 @@ class Query<T extends Object, Outside> extends ChangeNotifier {
|
|||||||
@protected
|
@protected
|
||||||
bool fetched = false;
|
bool fetched = false;
|
||||||
|
|
||||||
final QueryListener<T>? _onData;
|
@protected
|
||||||
final QueryListener<dynamic>? _onError;
|
final Set<QueryListener<T>> onDataListeners = Set<QueryListener<T>>();
|
||||||
|
@protected
|
||||||
|
final Set<QueryListener<dynamic>> onErrorListeners =
|
||||||
|
Set<QueryListener<dynamic>>();
|
||||||
|
|
||||||
// externalData will always be passed to the task Callback
|
// externalData will always be passed to the task Callback
|
||||||
// it will change based on the presence of QueryBuilder
|
// it will change based on the presence of QueryBuilder
|
||||||
@@ -78,9 +81,10 @@ class Query<T extends Object, Outside> extends ChangeNotifier {
|
|||||||
_initialData = initialData,
|
_initialData = initialData,
|
||||||
_externalData = externalData,
|
_externalData = externalData,
|
||||||
data = initialData,
|
data = initialData,
|
||||||
_onData = onData,
|
updatedAt = DateTime.now() {
|
||||||
_onError = onError,
|
if (onData != null) onDataListeners.add(onData);
|
||||||
updatedAt = DateTime.now();
|
if (onError != null) onErrorListeners.add(onError);
|
||||||
|
}
|
||||||
|
|
||||||
Query.fromOptions(
|
Query.fromOptions(
|
||||||
QueryJob<T, Outside> options, {
|
QueryJob<T, Outside> options, {
|
||||||
@@ -96,11 +100,12 @@ class Query<T extends Object, Outside> extends ChangeNotifier {
|
|||||||
_cacheTime = options.cacheTime ?? const Duration(minutes: 5),
|
_cacheTime = options.cacheTime ?? const Duration(minutes: 5),
|
||||||
_initialData = options.initialData,
|
_initialData = options.initialData,
|
||||||
_externalData = externalData,
|
_externalData = externalData,
|
||||||
_onData = onData,
|
|
||||||
_onError = onError,
|
|
||||||
data = options.initialData,
|
data = options.initialData,
|
||||||
status = QueryStatus.pending,
|
status = QueryStatus.pending,
|
||||||
updatedAt = DateTime.now();
|
updatedAt = DateTime.now() {
|
||||||
|
if (onData != null) onDataListeners.add(onData);
|
||||||
|
if (onError != null) onErrorListeners.add(onError);
|
||||||
|
}
|
||||||
|
|
||||||
// all getters & setters
|
// all getters & setters
|
||||||
bool get hasData => data != null && error == null;
|
bool get hasData => data != null && error == null;
|
||||||
@@ -144,13 +149,17 @@ class Query<T extends Object, Outside> extends ChangeNotifier {
|
|||||||
_prevUsedExternalData = _externalData;
|
_prevUsedExternalData = _externalData;
|
||||||
updatedAt = DateTime.now();
|
updatedAt = DateTime.now();
|
||||||
status = QueryStatus.succeed;
|
status = QueryStatus.succeed;
|
||||||
_onData?.call(data!);
|
for (final onData in onDataListeners) {
|
||||||
|
onData(data!);
|
||||||
|
}
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (retries == 0) {
|
if (retries == 0) {
|
||||||
status = QueryStatus.failed;
|
status = QueryStatus.failed;
|
||||||
error = e;
|
error = e;
|
||||||
_onError?.call(e);
|
for (final onError in onErrorListeners) {
|
||||||
|
onError(error);
|
||||||
|
}
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
} else {
|
} else {
|
||||||
// retrying for retry count if failed for the first time
|
// retrying for retry count if failed for the first time
|
||||||
@@ -160,14 +169,18 @@ class Query<T extends Object, Outside> extends ChangeNotifier {
|
|||||||
data = await task(queryKey, _externalData);
|
data = await task(queryKey, _externalData);
|
||||||
_prevUsedExternalData = _externalData;
|
_prevUsedExternalData = _externalData;
|
||||||
status = QueryStatus.succeed;
|
status = QueryStatus.succeed;
|
||||||
_onData?.call(data!);
|
for (final onData in onDataListeners) {
|
||||||
|
onData(data!);
|
||||||
|
}
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
break;
|
break;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (retryAttempts == retries) {
|
if (retryAttempts == retries) {
|
||||||
status = QueryStatus.failed;
|
status = QueryStatus.failed;
|
||||||
error = e;
|
error = e;
|
||||||
_onError?.call(e);
|
for (final onError in onErrorListeners) {
|
||||||
|
onError(error);
|
||||||
|
}
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
retryAttempts++;
|
retryAttempts++;
|
||||||
@@ -234,6 +247,9 @@ class Query<T extends Object, Outside> extends ChangeNotifier {
|
|||||||
fetched = false;
|
fetched = false;
|
||||||
status = QueryStatus.pending;
|
status = QueryStatus.pending;
|
||||||
retryAttempts = 0;
|
retryAttempts = 0;
|
||||||
|
onDataListeners.clear();
|
||||||
|
onErrorListeners.clear();
|
||||||
|
_mounts.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool get isStale {
|
bool get isStale {
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:fl_query/models/mutation_job.dart';
|
||||||
import 'package:fl_query/models/query_job.dart';
|
import 'package:fl_query/models/query_job.dart';
|
||||||
|
import 'package:fl_query/mutation.dart';
|
||||||
import 'package:fl_query/query.dart';
|
import 'package:fl_query/query.dart';
|
||||||
import 'package:collection/collection.dart';
|
import 'package:collection/collection.dart';
|
||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
@@ -27,6 +29,7 @@ class QueryBowlScope extends StatefulWidget {
|
|||||||
|
|
||||||
class _QueryBowlScopeState extends State<QueryBowlScope> {
|
class _QueryBowlScopeState extends State<QueryBowlScope> {
|
||||||
late Set<Query> queries;
|
late Set<Query> queries;
|
||||||
|
late Set<Mutation> mutations;
|
||||||
|
|
||||||
late Timer refreshIntervalTimer;
|
late Timer refreshIntervalTimer;
|
||||||
|
|
||||||
@@ -34,6 +37,7 @@ class _QueryBowlScopeState extends State<QueryBowlScope> {
|
|||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
queries = {};
|
queries = {};
|
||||||
|
mutations = {};
|
||||||
refreshIntervalTimer = Timer.periodic(
|
refreshIntervalTimer = Timer.periodic(
|
||||||
widget.refreshInterval,
|
widget.refreshInterval,
|
||||||
_checkAndUpdateStaleQueriesOnBg,
|
_checkAndUpdateStaleQueriesOnBg,
|
||||||
@@ -43,7 +47,7 @@ class _QueryBowlScopeState extends State<QueryBowlScope> {
|
|||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
refreshIntervalTimer.cancel();
|
refreshIntervalTimer.cancel();
|
||||||
_disposeListeners();
|
_disposeUpdateListeners();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,16 +59,22 @@ class _QueryBowlScopeState extends State<QueryBowlScope> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _listenToQueryUpdate() {
|
void _listenToUpdates() {
|
||||||
for (final query in queries) {
|
for (final query in queries) {
|
||||||
query.addListener(() => updateQueries(query));
|
query.addListener(() => updateQueries(query));
|
||||||
}
|
}
|
||||||
|
for (final mutation in mutations) {
|
||||||
|
mutation.addListener(() => updateMutations(mutation));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _disposeListeners() {
|
void _disposeUpdateListeners() {
|
||||||
for (final query in queries) {
|
for (final query in queries) {
|
||||||
query.removeListener(() => updateQueries(query));
|
query.removeListener(() => updateQueries(query));
|
||||||
}
|
}
|
||||||
|
for (final mutation in mutations) {
|
||||||
|
mutation.removeListener(() => updateMutations(mutation));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void updateQueries(Query query) {
|
void updateQueries(Query query) {
|
||||||
@@ -79,19 +89,41 @@ class _QueryBowlScopeState extends State<QueryBowlScope> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void updateMutations(Mutation mutation) {
|
||||||
|
setState(() {
|
||||||
|
// checking & not including inactive mutations
|
||||||
|
// basically garbage collecting mutations
|
||||||
|
mutations = Set.from(
|
||||||
|
mutation.isInactive
|
||||||
|
? mutations.where(
|
||||||
|
(el) => el.mutationKey != mutation.mutationKey,
|
||||||
|
)
|
||||||
|
: mutations,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
void addQuery<T extends Object, Outside>(Query<T, Outside> query) {
|
void addQuery<T extends Object, Outside>(Query<T, Outside> query) {
|
||||||
setState(() {
|
setState(() {
|
||||||
queries = Set.from({...queries, query});
|
queries = Set.from({...queries, query});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void addMutation<T extends Object, V>(Mutation<T, V> mutation) {
|
||||||
|
setState(() {
|
||||||
|
mutations = Set.from({...mutations, mutation});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
_disposeListeners();
|
_disposeUpdateListeners();
|
||||||
_listenToQueryUpdate();
|
_listenToUpdates();
|
||||||
return QueryBowl(
|
return QueryBowl(
|
||||||
addQuery: addQuery,
|
addQuery: addQuery,
|
||||||
|
addMutation: addMutation,
|
||||||
queries: queries,
|
queries: queries,
|
||||||
|
mutations: mutations,
|
||||||
staleTime: widget.staleTime,
|
staleTime: widget.staleTime,
|
||||||
child: widget.child,
|
child: widget.child,
|
||||||
);
|
);
|
||||||
@@ -102,21 +134,30 @@ class _QueryBowlScopeState extends State<QueryBowlScope> {
|
|||||||
/// Its responsible for creating/updating/delete queries
|
/// Its responsible for creating/updating/delete queries
|
||||||
class QueryBowl extends InheritedWidget {
|
class QueryBowl extends InheritedWidget {
|
||||||
final Set<Query> _queries;
|
final Set<Query> _queries;
|
||||||
|
final Set<Mutation> _mutations;
|
||||||
final Duration staleTime;
|
final Duration staleTime;
|
||||||
|
|
||||||
final void Function<T extends Object, Outside>(Query<T, Outside> query)
|
final void Function<T extends Object, Outside>(Query<T, Outside> query)
|
||||||
_addQuery;
|
_addQuery;
|
||||||
|
|
||||||
|
final void Function<T extends Object, V>(Mutation<T, V> mutation)
|
||||||
|
_addMutation;
|
||||||
|
|
||||||
const QueryBowl({
|
const QueryBowl({
|
||||||
required Widget child,
|
required Widget child,
|
||||||
required final void Function<T extends Object, Outside>(
|
required final void Function<T extends Object, Outside>(
|
||||||
Query<T, Outside> query)
|
Query<T, Outside> query)
|
||||||
addQuery,
|
addQuery,
|
||||||
|
required final void Function<T extends Object, V>(Mutation<T, V> mutation)
|
||||||
|
addMutation,
|
||||||
required final Set<Query> queries,
|
required final Set<Query> queries,
|
||||||
|
required final Set<Mutation> mutations,
|
||||||
required this.staleTime,
|
required this.staleTime,
|
||||||
Key? key,
|
Key? key,
|
||||||
}) : _addQuery = addQuery,
|
}) : _addQuery = addQuery,
|
||||||
_queries = queries,
|
_queries = queries,
|
||||||
|
_mutations = mutations,
|
||||||
|
_addMutation = addMutation,
|
||||||
super(child: child, key: key);
|
super(child: child, key: key);
|
||||||
|
|
||||||
Future<T?> fetchQuery<T extends Object, Outside>(
|
Future<T?> fetchQuery<T extends Object, Outside>(
|
||||||
@@ -134,6 +175,8 @@ class QueryBowl extends InheritedWidget {
|
|||||||
final hasExternalDataChanged =
|
final hasExternalDataChanged =
|
||||||
prevQuery.prevUsedExternalData != externalData;
|
prevQuery.prevUsedExternalData != externalData;
|
||||||
if (mount != null) prevQuery.mount(mount);
|
if (mount != null) prevQuery.mount(mount);
|
||||||
|
if (onData != null) prevQuery.onDataListeners.add(onData);
|
||||||
|
if (onError != null) prevQuery.onErrorListeners.add(onError);
|
||||||
if (!prevQuery.hasData || hasExternalDataChanged) {
|
if (!prevQuery.hasData || hasExternalDataChanged) {
|
||||||
if (hasExternalDataChanged) prevQuery.setExternalData(externalData);
|
if (hasExternalDataChanged) prevQuery.setExternalData(externalData);
|
||||||
return prevQuery.fetched
|
return prevQuery.fetched
|
||||||
@@ -154,12 +197,44 @@ class QueryBowl extends InheritedWidget {
|
|||||||
return await query.fetch();
|
return await query.fetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void addMutation<T extends Object, V>(
|
||||||
|
MutationJob<T, V> options, {
|
||||||
|
final MutationListener<T>? onData,
|
||||||
|
final MutationListener<dynamic>? onError,
|
||||||
|
final MutationListener<V>? onMutate,
|
||||||
|
Widget? mount,
|
||||||
|
}) {
|
||||||
|
final prevMutation = _mutations.firstWhereOrNull(
|
||||||
|
(mutation) => mutation.mutationKey == options.mutationKey);
|
||||||
|
if (prevMutation != null && prevMutation is Mutation<T, V>) {
|
||||||
|
if (onData != null) prevMutation.onDataListeners.add(onData);
|
||||||
|
if (onError != null) prevMutation.onErrorListeners.add(onError);
|
||||||
|
if (onMutate != null) prevMutation.onMutateListeners.add(onMutate);
|
||||||
|
if (mount != null) prevMutation.mount(mount);
|
||||||
|
} else {
|
||||||
|
final mutation = Mutation.fromOptions(
|
||||||
|
options,
|
||||||
|
onData: onData,
|
||||||
|
onError: onError,
|
||||||
|
onMutate: onMutate,
|
||||||
|
);
|
||||||
|
if (mount != null) mutation.mount(mount);
|
||||||
|
_addMutation(mutation);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Query<T, Outside>? getQuery<T extends Object, Outside>(String queryKey) {
|
Query<T, Outside>? getQuery<T extends Object, Outside>(String queryKey) {
|
||||||
return _queries.firstWhereOrNull((query) {
|
return _queries.firstWhereOrNull((query) {
|
||||||
return query.queryKey == queryKey && query is Query<T, Outside>;
|
return query.queryKey == queryKey && query is Query<T, Outside>;
|
||||||
})?.cast<Query<T, Outside>>();
|
})?.cast<Query<T, Outside>>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Mutation<T, V>? getMutation<T extends Object, V>(String mutationKey) {
|
||||||
|
return _mutations.firstWhereOrNull((mutation) {
|
||||||
|
return mutation.mutationKey == mutationKey && mutation is Mutation<T, V>;
|
||||||
|
})?.cast<Mutation<T, V>>();
|
||||||
|
}
|
||||||
|
|
||||||
int get isFetching {
|
int get isFetching {
|
||||||
return _queries.fold<int>(
|
return _queries.fold<int>(
|
||||||
0,
|
0,
|
||||||
@@ -170,6 +245,16 @@ class QueryBowl extends InheritedWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int get isMutating {
|
||||||
|
return _mutations.fold<int>(
|
||||||
|
0,
|
||||||
|
(acc, mutation) {
|
||||||
|
if (mutation.isLoading) acc++;
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
void resetQuery(String queryKey) {
|
void resetQuery(String queryKey) {
|
||||||
_queries
|
_queries
|
||||||
.firstWhereOrNull((element) => element.queryKey == queryKey)
|
.firstWhereOrNull((element) => element.queryKey == queryKey)
|
||||||
@@ -181,6 +266,8 @@ class QueryBowl extends InheritedWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
bool updateShouldNotify(QueryBowl oldWidget) {
|
bool updateShouldNotify(QueryBowl oldWidget) {
|
||||||
return oldWidget.staleTime != staleTime || oldWidget._queries != _queries;
|
return oldWidget.staleTime != staleTime ||
|
||||||
|
oldWidget._queries != _queries ||
|
||||||
|
oldWidget._mutations != _mutations;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,7 +68,10 @@ class _QueryBuilderState<T extends Object, Outside>
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
queryBowl.getQuery(widget.job.queryKey)?.unmount(widget);
|
final query = queryBowl.getQuery(widget.job.queryKey);
|
||||||
|
query?.unmount(widget);
|
||||||
|
if (widget.onData != null) query?.onDataListeners.remove(widget.onData);
|
||||||
|
if (widget.onError != null) query?.onErrorListeners.remove(widget.onError);
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user