flutter library for fetching, caching and invalidating asynchronous data
quick features
- fetch asynchronous data
- data invalidation
- optimistic response
- reset cache
motivation
how to do api calls in flutter? probably, majority would answer by using dio.
but the real question would be, how to integrate api calls in flutter arhitecture seamless?
one way would be to use futurebuilder
or maybe bloc like most of the community do.
the thing is, both futurebuilder and bloc have flaws.
for example, futurebuilder is too simple. it does provide status of your query, but communicating with some futurebuilder is impossible outside of the scope of the current screen.
problem with bloc is that will include so many boilerplate code for a simple api call but again, talking to the bloc is impossible from other screens. bloc should be
number one choice for complicated workflows, but what if you don’t have any complex business logic?
flutter_requery to the rescue!
example
let’s start with this simple example.
/// define data and cache key
final list<string> data = ["hello"];
final string cachekey = 'strkey';
/// simulates api call, therefore response is delayed
future<list<string>> _getdata() async {
await future.delayed(duration(seconds: 1));
return data;
}
/// later, used in the build method
query<list<string>>(
cachekey,
future: _getdata,
builder: (context, response) {
if (response.error != null) {
return text('error');
}
if (response.loading) {
return text('loading...');
}
final children = response.data.map((str) => text(str)).tolist();
return listview(
children: children
);
},
);
/// and later when you want to invalidate your data
void _onpress() async {
await future.delayed(duration(seconds: 1));
data.add("world");
querycache.invalidatequeries(cachekey);
}
and that’s the gist of it. you can find complete example on pub.dev.
usage
cache key
every query needs a cache key.
under this key your data will be stored in cache.
it can be string, int or list of strings and ints.
/// good
const k1 = 'mykey';
const k2 = 1;
const k3 = ["data", 1]
/// bad
const k1 = 1.0;
const k2 = true;
const k3 = ["data", true];
idea behind having keys specified as list is that you can invalidate your queries more intelligently.
take a look at invalidation chapter for more details.
query
once the cache key is defined, next step is to write the query.
query takes 3 arguments:
- cachekey – look here for more info.
- future – async action which will be executed.
- builder – follows the flutter builder pattern. first parameter is
buildcontext
followed byqueryresponse
object.
queryresponse manages query status. it also has 3 properties:
- data – response received from the future or null if the exception occured.
- loading – boolean, true if the query is running. otherwise, it’s false.
- error – represents an error received from the future. if the future was successful,
error
will be null.
// use query widget in the build method
query<list<string>>(
'mycachekey',
future: ()async {
await future.delayed(duration(seconds: 1));
return ["hello"]
}
builder: (context, queryresponse response) {
/// error state
if (response.error != null) {
return text('error');
}
/// loading state
if (response.loading) {
return text('loading...');
}
final children = response.data.map((str) => text(str)).tolist();
return listview(
children: children
);
},
);
invalidation
data invalidation can come in two different forms.
you can either afford to wait for the api response or you simply need to show the newest data as soon as possible.
if you are interested in following, check the next chapter.
waiting for the api response is more common and flutter_requery supports this by using the querycache
instance.
it’s global and already defined by the library. invalidate your query by passing the cache keys.
// invalidates strkey query
querycache.invalidatequeries('strkey');
// support for bulk invalidation
querycache.invalidatequeries(['strkey1', 'strkey2']);
// if your keys are lists, end result would be similar to
querycache.invalidatequeries([
['strkey', 1],
['strkey2', 2]
]);
once query is invalidated, every query
widget subscribed for that query
will execute future
again and rebuild its children with the new data.
for cache-level invalidation use:
// invalidate every query stored in cache
querycache.invalidateall()
invalidation works in pair with the keys defined as lists.
cache keys defined as list must be looked upon in a hierarchical manner where the list elements defined before are ancestors of the elements that come after.
for example:
// requests is ancestor of 1
const key1 = ["requests", 1]
reasoning behind this is to support hierarchical invalidation.
sometimes it can get cumbersome managing invalidations and therefore developer can decide to cleverly name keys to support this.
for example:
const k1 = ["requests", 1]
const k2 = ["requests", 2]
const k3 = "requests"
// without hierarchical invalidation you need to call
querycache.invalidatequeries([
["requests", 1], ["requests", 2], "requests"
]);
// but with hierarchical invalidation you only need to call
querycache.invalidatequeries("requests");
optimistic response
sometimes waiting period for the api response to be available is too long.
therefore you can immediately update the cache data and rebuild your widget tree by using the optimistic response.
make sure to remove await
keyword before the api call since this will block the thread.
querycache.setoptimistic("requests", [...olddata, newdata]);
reset
in short, reset can be explained as cache-level invalidation without rebuilding the widget tree.
also, async actions won’t be ran immediately but only when the new query
widget is mounted or the cachekey
has changed.
this is particularly useful for the log out action.
querycache.reset();
summary
api | description |
---|---|
query | flutter widget used for data-fetching operations. |
querycache.invalidatequeries | invalidates query specified by cache key and rebuilds the widget tree. |
querycache.invalidateall | invalidates every query stored in cache and rebuilds the widget tree. |
querycache.setoptimistic | set cache data manually and rebuild the widget tree. |
querycache.reset | invalidates every query stored in cache without rebuilding the widget tree. |
Comments are closed.