basic README Documentation added

doc comments for query bowl added
license, contribution guidelines & code of conduct added
This commit is contained in:
Kingkor Roy Tirtho
2022-06-26 23:47:53 +06:00
parent ff8fa9eb15
commit 78bb84e7b9
7 changed files with 584 additions and 110 deletions
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
https://github.com/KRTirtho/fl-query/discussions.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+113
View File
@@ -0,0 +1,113 @@
# Contributing to Fl-Query
First off, thanks for taking the time to contribute! ❤️
All types of contributions are encouraged and valued. See the [Table of Contents](#table-of-contents) for different ways to help and details about how this project handles them. Please make sure to read the relevant section before making your contribution. It will make it a lot easier for us maintainers and smooth out the experience for all involved. The community looks forward to your contributions. 🎉
> And if you like the project, but just don't have time to contribute, that's fine. There are other easy ways to support the project and show your appreciation, which we would also be very happy about:
> - Star the project
> - Tweet about it
> - Refer this project in your project's readme
> - Mention the project at local meetups and tell your friends/colleagues
## Table of Contents
- [Contributing to Fl-Query](#contributing-to-fl-query)
- [Table of Contents](#table-of-contents)
- [Code of Conduct](#code-of-conduct)
- [I Have a Question](#i-have-a-question)
- [I Want To Contribute](#i-want-to-contribute)
- [Reporting Bugs](#reporting-bugs)
- [Before Submitting a Bug Report](#before-submitting-a-bug-report)
- [How Do I Submit a Good Bug Report?](#how-do-i-submit-a-good-bug-report)
- [Suggesting Enhancements](#suggesting-enhancements)
## Code of Conduct
This project and everyone participating in it is governed by the
[Fl-Query Code of Conduct][code_of_conduct].
By participating, you are expected to uphold this code. Please report unacceptable behavior
to <>.
## I Have a Question
> If you want to ask a question, we assume that you have read the available [Documentation][readme].
Before you ask a question, it is best to search for existing [Issues][issues] that might help you. In case you have found a suitable issue and still need clarification, you can write your question in this issue. It is also advisable to search the internet for answers first.
If you then still feel the need to ask a question and need clarification, we recommend the following:
- Open an [Discussion][new_discussions] with the question label.
- Provide as much context as you can about what you're running into.
- Provide project and platform versions (flutter, dart, pub, linux etc..), depending on what seems relevant.
We will then take care of the issue as soon as possible.
## I Want To Contribute
> ### Legal Notice
> When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license.
### Reporting Bugs
#### Before Submitting a Bug Report
A good bug report shouldn't leave others needing to chase you up for more information. Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report. Please complete the following steps in advance to help us fix any potential bug as fast as possible.
- Make sure that you are using the latest version.
- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (Make sure that you have read the [documentation][readme]. If you are looking for support, you might want to check [this section](#i-have-a-question)).
- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error in the [bug tracker](https://github.com/KRTirtho/fl-query/issues?q=label%3Abug).
- Also make sure to search the internet (including Stack Overflow) to see if users outside of the GitHub community have discussed the issue.
- Collect information about the bug:
- Stack trace (Traceback)
- OS, Platform and Version (Windows, Linux, macOS, x86, ARM, web, android, ios)
- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant.
- Possibly your input and the output
- Can you reliably reproduce the issue? And can you also reproduce it with older versions?
#### How Do I Submit a Good Bug Report?
> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to
We use GitHub issues to track bugs and errors. If you run into an issue with the project:
- Open an [Issue](https://github.com/KRTirtho/fl-query/issues/new). (Since we can't be sure at this point whether it is a bug or not, we ask you not to talk about a bug yet and not to label the issue.)
- Explain the behavior you would expect and the actual behavior.
- Please provide as much context as possible and describe the *reproduction steps* that someone else can follow to recreate the issue on their own. This usually includes your code. For good bug reports you should isolate the problem and create a reduced test case.
- Provide the information you collected in the previous section.
Once it's filed:
- The project team will label the issue accordingly.
- A team member will try to reproduce the issue with your provided steps. If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for those steps and mark the issue as `needs-repro`. Bugs with the `needs-repro` tag will not be addressed until they are reproduced.
- If the team is able to reproduce the issue, it will be marked `needs-fix`, as well as possibly other tags (such as `critical`), and the issue will be left to be [implemented by someone](#your-first-code-contribution).
### Suggesting Enhancements
This section guides you through submitting an enhancement suggestion for Fl-Query, **including completely new features and minor improvements to existing functionality**. Following these guidelines will help maintainers and the community to understand your suggestion and find related suggestions.
<!-- omit in toc -->
#### Before Submitting an Enhancement
- Make sure that you are using the latest version.
- Read the [documentation][readme] carefully and find out if the functionality is already covered, maybe by an individual configuration.
- Perform a [search][issues] to see if the enhancement has already been suggested. If it has, add a comment to the existing issue instead of opening a new one.
- Find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Keep in mind that we want features that will be useful to the majority of our users and not just a small subset
<!-- omit in toc -->
#### How Do I Submit a Good Enhancement Suggestion?
Enhancement suggestions are tracked as [GitHub issues][issues].
- Use a **clear and descriptive title** for the issue to identify the suggestion.
- Provide a **step-by-step description of the suggested enhancement** in as many details as possible.
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why. At this point you can also tell which alternatives do not work for you.
- You may want to **include screenshots and animated GIFs** which help you demonstrate the steps or point out the part which the suggestion is related to. You can use [this tool](https://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. <!-- this should only be included if the project has a GUI -->
- **Explain why this enhancement would be useful** to most Fl-Query users. You may also want to point out the other projects that solved it better and which could serve as inspiration.
[code_of_conduct]: [https://github.com/KRTirtho/fl-query/main/CODE_OF_CONDUCT.md]
[readme]: [https://github.com/KRTirtho/fl-query#readme]
[issues]: [https://github.com/KRTirtho/fl-query/issues]
[new_discussions]: [https://github.com/KRTirtho/fl-query/discussions/new]
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+89 -104
View File
@@ -1,24 +1,41 @@
# FL-Query # FL-Query
Asynchronous data caching, refetching & invalidation library for Flutter. FL-Query lets you manage & distribute your data async data without touching any global state Asynchronous data caching, refetching & invalidation library for Flutter. FL-Query lets you manage & distribute your async data without touching any global state
# Examples Fl-Query makes asynchronous server state management a breeze in flutter
All examples of fl-query can be found in the [packages/example/lib](https://github.com/KRTirtho/fl-query/tree/main/packages/example/lib) directory
# Features
- Async data caching & management
- Smart + effective refetching
- Optimistic updates
- Automatically cached data invalidation & unneeded query/mutation garbage collection
- Easy to write & understand code. Follows DRY (Don't repeat yourself) convention
- Compatible with both vanilla Flutter & elite [flutter_hooks](https://pub.dev/packages/flutter_hooks)
# Installation
Regular installation:
```bash
$ flutter pub add fl_query
```
For elite flutter_hooks user:
```bash
$ flutter pub add flutter_hooks
```
# Basic Usage
First wrap your `MaterialApp` with with `QueryBowlScope` widget
Here's a basic example:
```dart ```dart
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return QueryBowlScope( return QueryBowlScope(
child: MaterialApp( child: MaterialApp(
title: 'FL-Query Demo', title: 'Fl-Query Example App',
theme: ThemeData( theme: ThemeData(
useMaterial3: true, useMaterial3: true,
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
@@ -27,97 +44,65 @@ class MyApp extends StatelessWidget {
), ),
); );
} }
}
// defining jobs that'll return results
// this query resolve successfully with expected Data
final successJob = QueryJob<String, void>(
queryKey: "success",
task: (queryKey, externalData) => Future.delayed(const Duration(seconds: 2),
() => "Welcome ($queryKey) ${Random.secure().nextInt(100)}"),
);
// this query can fail or can be successful
final failedJob = QueryJob<String, void>(
queryKey: "failure",
task: (queryKey, externalData) => Random().nextBool()
? Future.error("[$queryKey] Failed for unknown reason")
: Future.value(
"Success, you'll get slowly ${Random().nextInt(100)}!",
),
);
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Fl Query Example"),
),
body: Column(
children: [
Row(
children: [
QueryBuilder<String, void>(
job: successJob,
// if you want to pass any external data or variable to the
// query/task function or just pass null
externalData: null,
builder: (context, query) {
// returning based on the status of the query
if (query.isLoading || query.isRefetching) {
return const CircularProgressIndicator();
}
return TextButton(
child: Text(query.data!),
onPressed: () async {
// refetching data forcibly
await query.refetch();
},
);
},
),
QueryBuilder<String, void>(
job: failedJob,
externalData: null,
builder: (context, query) {
return Row(
children: [
if (query.hasError)
Text(
"${query.error}. Retrying: ${query.retryAttempts}",
),
if (query.hasData)
Text(
"Success after ${query.retryAttempts}. Data: ${query.data}"),
ElevatedButton(
child: Text("Refetch ${query.queryKey}"),
onPressed: () => query.refetch(),
)
],
);
},
),
],
),
],
),
);
}
}
``` ```
# TODO Fl-Query has two types of jobs
- `QueryJob`: Used for storing GET requests or for storing changeable yet readonly async data
- `MutationJob`: Used for POST/PUT/DELETE requests or for mutating/changing data in services or a store asynchronously
- Invalidate Queries when Window Focus Lost You can write all your query or mutation logic a method parameter named `task` & identify the query uniquely by passing a unique `queryKey`
- Invalidate Queries when Connection Lose based configure network behavior
Example of a QueryJob:
```dart
final exampleQueryJob = QueryJob<Map, void>(
queryKey: "example", // have to be unique
task: (queryKey, externalData) async {
final res = await http.get("/api/example-data");
return jsonDecode(res.body);
}
);
```
Store the `QueryJob` somewhere globally accessible in your project so you can reuse it later
Now you can use this `QueryJob` anywhere inside your flutter app inside the build method using a `QueryBuilder` widget
```dart
Widget build(BuildContext context){
return QueryBuilder<String, void>(
job: exampleQueryJob,
externalData: null,
builder: (context, query) {
if (!query.hasData || query.isLoading) {
return const CircularProgressIndicator();
}
return Row(
children: [
Text(query.data!),
ElevatedButton(
child: const Text("Refetch"),
onPressed: () async {
// refetches the query
await query.refetch();
},
),
],
);
},
);
}
```
# Why?
![The hell, why?](https://media.giphy.com/media/1M9fmo1WAFVK0/giphy.gif)
The main purpose of Fl-Query is providing the easiest way to manage the messy server-state part requiring the least amount of code with code reusability & performance
**Isn't `FutureBuilder` good?**
Yes but it is only if your commercial server has huge load of power & you're made of money or your app is simple or mostly offline & barely requires internet connection
`FutureBuilder` isn't good for data persistency & its impossible to share data across the entire application using it
**So `FutureProvider` from riverpod or provider not enough?**
Yeah, indeed its more than enough for many applications but what if your app needs Optimistic Updates & proper server-state synchronization or simply want a custom `cacheTime`? Although `FutureProvider` is a viable solution most of the `Future` related stuff, why not kick it up a notch with smart refetching capabilities with proper server-state synchronization?
Riverpod is definitely a inspiration for Fl-Query & the `QueryJob` is actually inspired by riverpod & imo is the best state management solution any library has ever provided but that's still a client state manager just like other client state manager or synchronous data manager
@@ -1 +1 @@
{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"connectivity_plus","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus-2.3.5/","native_build":true,"dependencies":[]}],"android":[{"name":"connectivity_plus","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus-2.3.5/","native_build":true,"dependencies":[]}],"macos":[{"name":"connectivity_plus_macos","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_macos-1.2.4/","native_build":true,"dependencies":[]}],"linux":[{"name":"connectivity_plus_linux","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_linux-1.3.1/","native_build":false,"dependencies":[]}],"windows":[{"name":"connectivity_plus_windows","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_windows-1.2.2/","native_build":true,"dependencies":[]}],"web":[{"name":"connectivity_plus_web","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_web-1.2.2/","dependencies":[]}]},"dependencyGraph":[{"name":"connectivity_plus","dependencies":["connectivity_plus_linux","connectivity_plus_macos","connectivity_plus_web","connectivity_plus_windows"]},{"name":"connectivity_plus_linux","dependencies":[]},{"name":"connectivity_plus_macos","dependencies":[]},{"name":"connectivity_plus_web","dependencies":[]},{"name":"connectivity_plus_windows","dependencies":[]}],"date_created":"2022-06-22 21:14:04.467520","version":"3.0.1"} {"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"connectivity_plus","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus-2.3.5/","native_build":true,"dependencies":[]}],"android":[{"name":"connectivity_plus","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus-2.3.5/","native_build":true,"dependencies":[]}],"macos":[{"name":"connectivity_plus_macos","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_macos-1.2.4/","native_build":true,"dependencies":[]}],"linux":[{"name":"connectivity_plus_linux","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_linux-1.3.1/","native_build":false,"dependencies":[]}],"windows":[{"name":"connectivity_plus_windows","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_windows-1.2.2/","native_build":true,"dependencies":[]}],"web":[{"name":"connectivity_plus_web","path":"/home/krtirtho/.pub-cache/hosted/pub.dartlang.org/connectivity_plus_web-1.2.2/","dependencies":[]}]},"dependencyGraph":[{"name":"connectivity_plus","dependencies":["connectivity_plus_linux","connectivity_plus_macos","connectivity_plus_web","connectivity_plus_windows"]},{"name":"connectivity_plus_linux","dependencies":[]},{"name":"connectivity_plus_macos","dependencies":[]},{"name":"connectivity_plus_web","dependencies":[]},{"name":"connectivity_plus_windows","dependencies":[]}],"date_created":"2022-06-26 23:45:47.442373","version":"3.0.1"}
+51 -4
View File
@@ -1,16 +1,39 @@
import 'dart:async'; import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:fl_query/fl_query_hooks.dart';
import 'package:fl_query/src/models/query_job.dart'; import 'package:fl_query/src/models/query_job.dart';
import 'package:fl_query/src/mutation.dart'; import 'package:fl_query/src/mutation.dart';
import 'package:fl_query/src/mutation_builder.dart';
import 'package:fl_query/src/query.dart'; import 'package:fl_query/src/query.dart';
import 'package:fl_query/src/utils.dart'; import 'package:fl_query/src/utils.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:flutter/widgets.dart'; import 'package:flutter/widgets.dart';
/// The widget that holds & provides every [Query] & [Mutation] to your
/// entire Flutter application in anywhere
/// This must be used on the above any other widget
///
/// ```dart
/// Widget build(BuildContext context) {
/// return QueryBowlScope(
/// child: MaterialApp(/*...other stuff...*/),
/// );
/// }
/// ```
///
class QueryBowlScope extends StatefulWidget { class QueryBowlScope extends StatefulWidget {
final Widget child; final Widget child;
/// global stale time
///
/// Makes [Query.data] stale after crossing the duration of provided
/// [staleTime]
final Duration staleTime; final Duration staleTime;
/// global cache time
///
/// Removes inactive queries after provided duration of [cacheTime]
final Duration cacheTime; final Duration cacheTime;
// refetching options // refetching options
@@ -34,16 +57,17 @@ class QueryBowlScope extends StatefulWidget {
/// rate-limit /// rate-limit
/// ///
/// Though its recommended most of the time to use but it can be turned /// Though its recommended most of the time to use but it can be turned
/// off by setting passing [Duration.zero] /// off by passing [Duration.zero]
final Duration refetchOnReconnectDelay; final Duration refetchOnReconnectDelay;
/// used for periodically checking if any query got stale. /// used for periodically checking if any query got stale.
/// If none is supplied then half of the value of staleTime is used /// If none is supplied then half of the value of staleTime is used
final Duration refetchInterval; final Duration refetchInterval;
const QueryBowlScope({ const QueryBowlScope({
required this.child, required this.child,
this.staleTime = Duration.zero, this.staleTime = Duration.zero,
this.cacheTime = const Duration(seconds: 5), this.cacheTime = const Duration(minutes: 5),
this.refetchInterval = Duration.zero, this.refetchInterval = Duration.zero,
this.refetchOnMount = false, this.refetchOnMount = false,
this.refetchOnReconnect = true, this.refetchOnReconnect = true,
@@ -199,8 +223,11 @@ class _QueryBowlScopeState extends State<QueryBowlScope> {
} }
} }
/// QueryBowl holds all the query related methods & properties. /// QueryBowl provides an imperative way to handle all the query &
/// Its responsible for creating/updating/delete queries /// mutation related methods & properties.
///
/// Its responsible or can be used for (not recommended) creating,
/// updating & deleting queries & mutations
class QueryBowl extends InheritedWidget { class QueryBowl extends InheritedWidget {
final Set<Query> _queries; final Set<Query> _queries;
final Set<Mutation> _mutations; final Set<Mutation> _mutations;
@@ -244,6 +271,7 @@ class QueryBowl extends InheritedWidget {
_addMutation = addMutation, _addMutation = addMutation,
super(child: child, key: key); super(child: child, key: key);
/// !⚠️**Warning** only for internal library usage
@protected @protected
Future<T?> fetchQuery<T extends Object, Outside>( Future<T?> fetchQuery<T extends Object, Outside>(
QueryJob<T, Outside> options, { QueryJob<T, Outside> options, {
@@ -292,6 +320,7 @@ class QueryBowl extends InheritedWidget {
return await query.fetch(); return await query.fetch();
} }
/// !⚠️**Warning** only for internal library usage
@protected @protected
Query<T, Outside> addQuery<T extends Object, Outside>( Query<T, Outside> addQuery<T extends Object, Outside>(
Query<T, Outside> query, { Query<T, Outside> query, {
@@ -332,6 +361,7 @@ class QueryBowl extends InheritedWidget {
return query; return query;
} }
/// !⚠️**Warning** only for internal library usage
@protected @protected
Mutation<T, V> addMutation<T extends Object, V>( Mutation<T, V> addMutation<T extends Object, V>(
Mutation<T, V> mutation, { Mutation<T, V> mutation, {
@@ -359,18 +389,25 @@ class QueryBowl extends InheritedWidget {
} }
} }
/// Get a query by providing queryKey only
///
/// Useful for optimistic update or single query refetch
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>>();
} }
/// Get a mutation by providing mutationKey only
///
/// Useful for mutation resets
Mutation<T, V>? getMutation<T extends Object, V>(String mutationKey) { Mutation<T, V>? getMutation<T extends Object, V>(String mutationKey) {
return _mutations.firstWhereOrNull((mutation) { return _mutations.firstWhereOrNull((mutation) {
return mutation.mutationKey == mutationKey && mutation is Mutation<T, V>; return mutation.mutationKey == mutationKey && mutation is Mutation<T, V>;
})?.cast<Mutation<T, V>>(); })?.cast<Mutation<T, V>>();
} }
/// Returns the number of query is currently fetching or refetching
int get isFetching { int get isFetching {
return _queries.fold<int>( return _queries.fold<int>(
0, 0,
@@ -381,6 +418,7 @@ class QueryBowl extends InheritedWidget {
); );
} }
/// Provides the number of mutations that are running at the moment
int get isMutating { int get isMutating {
return _mutations.fold<int>( return _mutations.fold<int>(
0, 0,
@@ -391,11 +429,16 @@ class QueryBowl extends InheritedWidget {
); );
} }
/// Sets [Query]'s data manually
///
/// Mostly used in combination with [onMutate] callback of
/// [MutationBuilder] & [useMutation] for optimistic updates
void setQueryData<T extends Object, Outside>( void setQueryData<T extends Object, Outside>(
String queryKey, QueryUpdateFunction<T> updateCb) { String queryKey, QueryUpdateFunction<T> updateCb) {
getQuery<T, Outside>(queryKey)?.setQueryData(updateCb); getQuery<T, Outside>(queryKey)?.setQueryData(updateCb);
} }
/// resets all the queries matching the passed List of queryKeys
void resetQueries(List<String> queryKeys) { void resetQueries(List<String> queryKeys) {
for (final query in _queries) { for (final query in _queries) {
if (!queryKeys.contains(query.queryKey)) continue; if (!queryKeys.contains(query.queryKey)) continue;
@@ -403,6 +446,7 @@ class QueryBowl extends InheritedWidget {
} }
} }
/// makes all the queries matching the passed List of queryKeys stale
void invalidateQueries(List<String> queryKeys) { void invalidateQueries(List<String> queryKeys) {
for (final query in _queries) { for (final query in _queries) {
if (!queryKeys.contains(query.queryKey)) continue; if (!queryKeys.contains(query.queryKey)) continue;
@@ -410,6 +454,7 @@ class QueryBowl extends InheritedWidget {
} }
} }
/// refetches all the queries matching the passed List of queryKeys
Future<void> refetchQueries(List<String> queryKeys) async { Future<void> refetchQueries(List<String> queryKeys) async {
for (final query in _queries) { for (final query in _queries) {
if (queryKeys.contains(query.queryKey)) { if (queryKeys.contains(query.queryKey)) {
@@ -421,7 +466,9 @@ class QueryBowl extends InheritedWidget {
static QueryBowl of(BuildContext context) => static QueryBowl of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<QueryBowl>()!; context.dependOnInheritedWidgetOfExactType<QueryBowl>()!;
/// !⚠️**Warning** only for internal library usage
@override @override
@protected
bool updateShouldNotify(QueryBowl oldWidget) { bool updateShouldNotify(QueryBowl oldWidget) {
return oldWidget.staleTime != staleTime || return oldWidget.staleTime != staleTime ||
oldWidget._queries != _queries || oldWidget._queries != _queries ||
+1 -1
View File
@@ -1,6 +1,6 @@
name: fl_query name: fl_query
description: A new Flutter package project. description: A new Flutter package project.
version: 0.0.1 version: 0.1.0
homepage: https://github.com/KRTirtho/fl-query homepage: https://github.com/KRTirtho/fl-query
environment: environment: