Code Monkey home page Code Monkey logo

async_resource's Introduction

async_resource

Automatically cache network resources and use them when offline. Interface with local resources on any platform.

Examples

See also the working example.

Wrapping in a stream

// `res` is any AsyncResource.
final resource = StreamedResource(res);
resource.sink.add(false);

Flutter and native

Import FileResource.

import 'package:async_resource/file_resource.dart';

Define a resource.

// Flutter needs a valid directory to write to.
// `getApplicationDocumentsDirectory()` is in the `path_provider` package.
// Native applications do not need this step.
final path = (await getApplicationDocumentsDirectory()).path;

final myDataResource = HttpNetworkResource<MyData>(
  url: 'https://example.com/my-data.json',
  parser: (contents) => MyData.fromJson(contents),
  cache: FileResource(File('$path/my-data.json')),
  maxAge: Duration(minutes: 60),
  strategy: CacheStrategy.cacheFirst,
);

Basic usage

final myData = await myDataResource.get();
// or without `await`
myDataResource.get().then((myData) => print(myData));

Flutter pull-to-refresh example

class MyDataView extends StatefulWidget {
  @override
  _MyDataViewState createState() => _MyDataViewState();
}

class _MyDataViewState extends State<MyDataView> {
  bool refreshing = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: RefreshIndicator(
            onRefresh: refresh,
            child: FutureBuilder<MyData>(
              future: myDataResource.get(forceReload: refreshing),
              initialData: myDataResource.data,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return _buildView(snapshot.data);
                } else if (snapshot.hasError) {
                  return Text('${snapshot.error}');
                }
                return Center(child: CircularProgressIndicator());
              },
            )));
  }

  Future<Null> refresh() async {
    setState(() => refreshing = true);
    refreshing = false;
  }
}

Flutter Using MMKV

MMKV used is from https://pub.dartlang.org/packages/flutter_mmkv

MMKV is really fast and can get the data stored in just 3-5 milliseconds, really fast.

import MMKVResource.

import 'package:async_resource/mmkv_resource.dart';

Define a resource.

// Flutter needs a valid directory to write to.
// `getApplicationDocumentsDirectory()` is in the `path_provider` package.
// Native applications do not need this step.
final path = (await getApplicationDocumentsDirectory()).path;

final myDataResource = HttpNetworkResource<MyData>(
  url: 'https://example.com/my-data.json',
  parser: (contents) => MyData.fromJson(contents),
  cache: MMKVResource('my_key','$path/my_key'),
  maxAge: Duration(minutes: 60),
  strategy: CacheStrategy.cacheFirst,
);

Flutter using Shared Preferences

Import SharedPrefsResource.

import 'package:shared_prefs_resource/shared_prefs_resource.dart';

Definition

final themeResource = StringPrefsResource('theme');

Usage example

class ThemedApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ThemedAppState();
}

class _ThemedAppState extends BlocState<ThemedApp> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<MyData>(
        future: themeResource.get(),
        initialData: themeResource.data,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return MaterialApp(
                title: 'My themed app',
                theme: buildTheme(snapshot.data),
                home: HomePage());
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }
          return Center(child: CircularProgressIndicator());
        },
      );
  }
}

Web using service worker

Import browser-based resources.

import 'package:async_resource/browser_resource.dart';

Define the resource.

final myDataResource = ServiceWorkerResource<MyData>(
    cache: ServiceWorkerCacheEntry(
        name: config.cacheName,
        url: 'https://example.com/my-data.json',
        parser: (contents) => MyData.fromJson(contents),
        maxAge: Duration(minutes: 60)));

Usage

myDataResource.get();

Web using local/session storage

Import browser-based resources.

import 'package:async_resource/browser_resource.dart';

Define

final themeResource = StorageEntry('theme');
final sessionResource = StorageEntry('token', type: StorageType.sessionStorage);

Use

themeResource.get();
sessionResource.get();

async_resource's People

Contributors

jifalops avatar mclark4386 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

async_resource's Issues

compatibility with flutter_map

Whenever I add this library to my pubspec.yaml my flutter map is not working anymore in web mode. It's not showing any map tiles anymore.
I double and tipple check that this is the only change I made but somehow only adding it is enough to break my code.

Even more strangely, after removing it again I get can compiler error complaining about a missing rxdart. When I add this instead It still does not work but when I remove it again afterwards it compiles again and it works again as well.

Compatibility with rxdart ^0.23.1+

High im getting a dependency error, we are using rxdart version ^0.23.1, but your plugin depends on rxdart ^0.18.0.

Error:

Because async_resource >=0.1.4 depends on rxdart ^0.18.0 and hiro_insurance depends on rxdart ^0.23.1, async_resource >=0.1.4 is forbidden.

Using POST request, and meaning of maxAge.

Am using a flutter package async_resource. in my Mobile App using flutter, I can't really understand the documentation please there a parameter maxAge: Duration(minutes: 60) //Please what does this mean, Do they mean the duration for fetching and caching data? Or duration for the data to be expired?
Secondly, The url parameter: //Must it be .json url? because am trying to send data using POST(which means that I don't have .json url)

Here is my code, It neither create a file nor cache the data from the server

Future<HttpNetworkResource<Question>> fetchQuestion({String subject, int lastId})async{
    await Future.delayed(Duration(seconds: 1));
    var map = new Map<String, String>();
    map["subject"] = subject;
    map["lastid"] = lastId.toString();

    final path = (await getApplicationDocumentsDirectory()).path;
    final myDataResource = HttpNetworkResource<Question>(
      url: Base_URL().getQuestion,
      headers: map,
      parser: (contents) => Question.fromJson(contents),
      cache: FileResource(File('$path/JambQtz$subject.json')),
      maxAge: Duration(minutes: 1),
      strategy: CacheStrategy.cacheFirst,
    );

    return myDataResource;
  }
 Future<HttpNetworkResource<Question>> question = HttpAPI().fetchQuestion(subject: 'physics', lastId: 1);
    question.then((v){
      v.isExpired.then((b){
        print('Expired $b');
      });
      print('Location: ${v.location}');
      print(v.headers);
      print(v.hashCode);
    });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.