Javascript required
Skip to content Skip to sidebar Skip to footer

The Data for This Widget Is Currently Unavailable Please Try Again Later

Pub License: BSD-3-Clause

🧰 A packet that provides you a fashion to rails your request and avoid any errors. #

Nosotros use the NetworkBoundResources to make a request, process the response using then and centralize all errors of the awarding to a unique function that you inject and provide a friendly message to your users.


📄 Table of Contents #

  • Why should I utilise
  • Examples
  • Install
  • Usage
    • Setup
    • AppException
    • NetworkBoundResources
      • asFuture
      • asSimpleStream
      • asResourceStream
      • asStream
    • Resource
      • Executing a function with resource
      • States
      • Loading state
      • Success state
      • Failed land
    • ResourceMetaData
    • Widgets
      • ListViewResourceWidget
      • ResourceWidget
  • Writer
  • Contributing
  • Show your support
  • License

Resource Network Fetcher standardize your flutter project, making all your functions that can occur errors return a same value, that is the Resources<T>. This object helps you to pass the error for the view, making a default manner to know what message to brandish to the user. Other thing that it does is centralize the errors with the part called AppException errorMapper(e), that receives all errors of the application and map how you want to make the error readable.

Other thing that it provides is the Condition, that can be: Status.success<span/>, Condition.loading<bridge/> and Status.error<span/>

Examples of to-exercise apps that used resource_network_fetcher as base:

  • Example
  • Daily Nasa photograph
  • Todo clean
  • Todo modular
  • Example clean
  • Instance clean complete
  • Case MVC modular
  • Example MVC modular complete

Follow this tutorial: Installation tab

Add resource_network_fetcher to your pubspec.yaml file:

          dependencies:   resource_network_fetcher:                  

Import get in files that it volition exist used:

          import 'package:resource_network_fetcher/resource_network_fetcher.dart';                  

main.sprint file #

          import 'package:flutter/fabric.sprint'; import 'error_mapper.dart';  void primary() {   Resource.setErrorMapper(ErrorMapper.from);   runApp(MyApp()); }                  

This is an example of minimum configuration to utilize, you tin add together other parameters to map amend.

          import 'parcel:dio/dio.dart'; import 'package:resource_network_fetcher/resource_network_fetcher.dart';  abstruse class ErrorMapper {   static AppException from(dynamic due east) {     switch (e.runtimeType) {       case AppException:         return eastward;       case DioError:         return AppException(           exception: e,           message: _dioError(e),         );       default:         return AppException(           exception: east,           message: east.toString(),         );     }   }    static String _dioError(DioError error) {     switch (error.blazon) {       example DioErrorType.sendTimeout:       case DioErrorType.connectTimeout:       case DioErrorType.receiveTimeout:         return "Connection failure, verify your cyberspace";       case DioErrorType.abolish:         render "Canceled asking";       case DioErrorType.response:       instance DioErrorType.other:       default:     }     if (mistake.response?.statusCode != null) {       switch (mistake.response!.statusCode) {         case 401:           return "Authorization denied, check your login";         case 403:           return "There was an error in your asking, check the information and attempt again";         example 404:           render "Not found";         case 500:           return "Internal server error";         instance 503:           return "The server is currently unavailable, delight try again later";         default:       }     }     render "Request mistake, please try again subsequently";   } }                  

We use this exception to standardize the exceptions to the app

          throw AppException(     message: "Error bulletin",     exception: Exception("Error message"),     data: zilch, );                  

Is a conjunction of rules that run with the Resource.asFuture and transforms the response of the fetch to the model specified in the processResponse param. Another utilise for this is using for offline-outset or only to cache your requests. For that you need to use the other params of the method.

Nosotros have other options of methods, that returns a stream or a Future. Hither is an example of how to use in a simple mode:

          Future<Resources<UserEntity>> getUser() {   return NetworkBoundResources.asFuture<UserEntity, Map<String, dynamic>>(     createCall: _getUserFromNetwork,     processResponse: UserEntity.fromMap,   ); }  Future<Map<String, dynamic>> _getUserFromNetwork() async {   render {}; /// Fetch the api }                  
          Stream<Resource<UserEntity>> streamUser() {   return NetworkBoundResources.asSimpleStream<UserEntity, Map<String, dynamic>>(     createCall: _streamUserFromNetwork,     processResponse: UserEntity.fromMap,   ); }  Stream<Map<Cord, dynamic>> _streamUserFromNetwork() async* {   yield {}; /// Fetch the api }                  

The divergence of this and the asStream is that with this y'all can return your own Resource in createCall param.

          Stream<Resources<UserEntity>> streamUser() {   return NetworkBoundResources.asResourceStream<UserEntity, Map<String, dynamic>>(     createCall: _streamUserFromNetwork,     processResponse: UserEntity.fromMap,   ); }  Stream<Resource<Map<String, dynamic>>> _streamUserFromNetwork() async* {   yield Resource.loading();   yield Resource.success(information: {}); /// Fetch the api }                  
          Stream<Resources<UserEntity>> streamUser() {   return NetworkBoundResources.asStream<UserEntity, Map<String, dynamic>>(     createCall: _streamUserFromNetwork,     processResponse: UserEntity.fromMap,   ); }  Stream<Map<String, dynamic>> _streamUserFromNetwork() async* {   yield {}; /// Fetch the api }                  

Hither is an example of how to run a part with the Resource, because with that, any fault that occur inside volition be mapped with the ErrorMapper setted.

          concluding event = await Resource.asFuture(() async {   /// Here you execute wherever yous want and returns the result.   render ["one"]; }); print(result.isSuccess); /// Prints true print(effect.isFailed); /// Prints faux print(result.isLoading); /// Prints false print(consequence.data); /// Prints the effect: ["one"]                  

We take 3 basic states, the success, loading and failed land. But each land can storage an error so, in the total can have 6 states, that includes having or not the data.

          final resources = Resources.loading<T>({T information});                  

Loading without data land

          concluding resources = Resource.loading<List<String>>();                  

Loading with data state

          concluding resources = Resource.loading<Listing<Cord>>(information: ["one"]);                  
          final resource = Resources.success<T>({T data});                  

Success without data state

          final resource = Resources.success<List<String>>();                  

Success with data state

          concluding resources = Resources.success<List<String>>(information: ["one"]);                  
          final resource = Resource.failed<T>({dynamic fault, T data});                  

Failed without data land

          terminal resources = Resource.failed<List<String>>(mistake: AppException());                  

Failed with data state

          final resource = Resource.failed<List<Cord>>(error: AppException(), data: ["one"]);                  

Is an information about the final returns of the Resource, can exist very useful in streams, when you need to know the last result that was returned. If you employ the NetworkBoundResources.asSimpleStream(), NetworkBoundResources.asResourceStream() or NetworkBoundResources.asStream(), the add to the Resource.metaData is automated!

Hither is an example that show how y'all can get the MetaData of a Resource.

          var resource = Resource.success(information: <String>[]); resources = resource.addData(Status.success, ["newData"]);  // Prints the metadata of the resource print(resource.metaData);  // Prints the terminal data returned by this resources print(resource.metaData.data); /// ["newData"]  // Prints the list of the lasts 2 returns of the resource impress(resource.metaData.results); /// [ ["newData"], [] ]                  

We created widgets that helps yous to summarize your code and work better with Resource<T> object, treating all the states at your way!

          Widget build(BuildContext) {   return ListViewResourceWidget(     resources: Resource.success(information: []),     loadingTile: ListTile(),     tileMapper: (data) => ListTile(),     loadingTileQuantity: 2,     refresh: () async {},     emptyWidget: Container(),   ); }                  
          Widget build(BuildContext) {   return ResourceWidget(     resources: Resource.success(),     loadingWidget: CircularProgressIndicator(),     doneWidget: (data) => Container(),     refresh: () async {},     errorWithDataWidget: (e, data) => Container(),     loadingWithDataWidget: (information) => Container(),   ); }                  
  • Github: @LucazzP
  • Gitlab: @LucazzP
  • LinkedIn: @LucazzP

Contributions, issues and feature requests are welcome!
Feel free to check bug page. You can also take a expect at the contributing guide.

Requite a ⭐ and a like in Pub.dev️ if this project helped you!

Copyright © 2021 Lucas Henrique Polazzo.
This project is BSD-iii Clause licensed.

gullettgocielince71.blogspot.com

Source: https://pub.dev/packages/resource_network_fetcher