Future based HTTP client for the Dart and Flutter

Related tags

Utilities dart flutter
Overview

codecov CI License: MIT pub package GitHub stars

Uno

Future based HTTP client for the Dart and Flutter.

Uno, inspired by Axios, bringing a simple and robust experience to the crossplatform apps in Flutter and server apps in Dart.

Install

Add in your pubspec.yaml:

dependencies:
  uno: 
   

or use:

dart pub add uno

Usage

Uno is ready for the REST. Methods like GET, POST, PUT, PATCH, DELETE are welcome here!

Performing a GET request:

final uno = Uno();

// Make a request for a user with a given ID
uno.get('/users?id=1').then((response){
  print(response.data); // it's a Map
   
    .
   
}).catchError((error){
  print(error) // It's a UnoError.
});

// Optionally the request above could also be done as
uno.get('/users',params: {
  'id': '1',
}).then((response){
  print(response.data);
});

// Want to use async/await? Add the `async` keyword to your outer function/method.
Future<void> getUser() async {
  try {
    final response = await uno.get('/user?ID=12345');
    print(response.data;
  } on UnoError catch (error) {
    print(error);
  }
}

Performing a POST request:

  uno.post('/user', data: {
    'firstName': 'Fred',
    'lastName': 'Flintstone'
  })
  .then((response) {
    print(response);
  })
  .catchError((error) {
    print(error);
  });

uno API

Requests can be made by passing the relevant config to uno.

// Send a POST request
uno(
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
);
// Download image from server;
uno(
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: ResponseType.arraybuffer,
  onDownloadProgress: (total, current) {
    final percentCompleted = (current / total * 100).round();
    print('completed: $percentCompleted%');
  },
).then((response) async {
  await File('ada_lovelace.jpg').writeAsBytes(response.data);
});

Creating an instance

final uno = Uno(
  baseURL: 'https://some-domain.com/api/',
  timeout: Duration(second: 30),
  headers: {'X-Custom-Header': 'foobar'}
);

Interceptors

You can intercept requests or responses before they are handled by then or catch:

  // Add a request interceptor
  uno.interceptors.request.use((request) {
    // Do something before request is sent
    return request;
  }, onError: (error) {
    // Do something with request error
    return error;
  });

  // Add a response interceptor
  uno.interceptors.response.use((response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, onError: (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return error;
  });

If you need to remove an interceptor later you can.

final myInterceptor = uno.interceptors.request.use((request) {/*...*/});
uno.interceptors.request.eject(myInterceptor);

If you want to execute a particular interceptor based on a runtime check, you can add a runWhen function to the options object. The interceptor will not be executed if and only if the return of runWhen is false. The function will be called with the config object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an asynchronous request interceptor that only needs to run at certain times.

bool onGetCall(request) {
  return request.method == 'get';
}
uno.interceptors.request.use((request) {
  request.headers['test'] = 'special get headers';
  return request;
}, runWhen: onGetCall);

Handling Errors

uno.get('/user/12345')
  .catchError((error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      print(error.response.data);
      print(error.response.status);
      print(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      print(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      print('Error ${error.message}');
    }
  });

Using the validateStatus config option, you can define HTTP code(s) that should throw an error.

axios.get('/user/12345', {
  validateStatus: (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
});

Multipart/FormData

You can use the form-data:

final form = FormData();

form.add('my_field', 'my value');
form.addBytes('my_buffer', <int>[]);
form.addFile('my_file', 'my_file.pdf');

uno.post('https://example.com', data: form);

Features and bugs

Please file feature requests and bugs at the issue tracker.

You might also like...

An example todo list back end project that uses gRPC for client-server communication and Firestore for data storage

An example todo list back end project that uses gRPC for client-server communication and Firestore for data storage

Apr 18, 2022

A Dart build script that downloads the Protobuf compiler and Dart plugin to streamline .proto to .dart compilation.

A Dart build script that downloads the Protobuf compiler and Dart plugin to streamline .proto to .dart compilation.

Oct 26, 2022

simplified man-pages, a tldr.sh client

simplified man-pages, a tldr.sh client

Report bug · Request feature Table of contents Overview Screenshots CI Build and run Bugs and feature requests Contributing Creators Copyright and lic

Dec 27, 2022

This is the client application for connecting to cptserver

This is the client application for connecting to cptserver. CPT stands for Course Participation Tracker.

Nov 2, 2022

A few handy Flutter tools, dead simple `UriRouter` for `Uri`-based navigator or `BuildTracker` to track widget rebuilds and what caused them to rebuild.

noob A few handy tools for Flutter apps. UriRouter Hooks Providers PointerIndicator BuildTracker PeriodicListenable UriRouter Dead simple Uri-based pa

Jan 18, 2022

Swagger/OpenAPI code generator based on Chopper and JsonAnnotation for Flutter

Swagger/OpenAPI code generator based on Chopper and JsonAnnotation for Flutter

Code partially generated with chopper 📣 Build dart types from Swagger/OpenAPI schemas SwaggerDartCodeGenerator is a code generator that looks for *.s

Jan 5, 2023

The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs.

The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs.

The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs. Inspired by SwiftGen. Motivation Using asset path str

Jan 6, 2023

A high-performance, web standards-compliant rendering engine based on Flutter.

A high-performance, web standards-compliant rendering engine based on Flutter.

A high-performance, web standards-compliant rendering engine based on Flutter.

Dec 30, 2022

A code generation tool based on Database. :construction: developing :construction:

A code generation tool based on Database. :construction:  developing :construction:

dbgen A code generation tool based on Database. Getting Started This project is a starting point for a Flutter application. A few resources to get you

Jun 8, 2022
Comments
  • Configuring Defaults

    Configuring Defaults

    Like in Axios-http, I'd like to be able to define defaults (like authorization bearer token) so I don't have to define it every time.

    I understand that this is possible with interceptors, but I think that Axio's solution is way simpler and cleaner. And since the interceptors are already there, would it be possible to use them under the hood with this requested functionality?

    opened by guplem 0
  • upload stream has error

    upload stream has error

    Hello, I had a problem uploading the stream

    Stream<List<int>>? data=...;
    
    
    final uno.Response response = await _client.post(path,
        data:
            await data?.fold<List<int>>(<int>[], (List<int> previous, List<int> element) => previous..addAll(element)),
        headers: _getHeader(options),
        responseType: ResponseType.stream,
        onDownloadProgress: onSendProgress);
    

    error

    Status 400
    
    opened by mbfakourii 0
  • Responsetype should just listen to the header content-type

    Responsetype should just listen to the header content-type

    I'm using Uno in my dart library. My API can either return an empty body (plain text) or return a JSON body. Right now that is not supported in the lib, because I have to define the responseType upfront.

    Which doesn't make a lot of sense, since it can just listen to the content-type header

    opened by Terandium 0
An http request client, which supports Manageable Requests Cancellation, Request Policy (Timeout and Retry), Easier Multipart Requests, etc.

A wrapper around Dart's http package, which supports Manageable Requests Cancellation, Request Policy (Timeout and Retry), Easier Multipart Requests, Error Handling, etc.

Iandi Santulus 5 Oct 10, 2021
Flutter_socks_proxy is a dart package, HTTP/Socks4/Socks5 proxy

flutter_socks_proxy flutter_socks_proxy is a dart package, HTTP/Socks4/Socks5 proxy Usage Use global import 'dart:convert';

null 12 Oct 23, 2022
Dio Package in Flutter - HTTP Requests and Interceptors.

Dio Package in Flutter - HTTP Requests and Interceptors. Learn how to use Flutter Dio package to make http requests, deal with interceptors and take care of unexpected server responses and failures in Flutter apps.

Sandip Pramanik 14 Nov 18, 2022
A simple, unofficial AWS Polly client in dart. Supports generating a URL given an input text and voice identifier.

Flutter AWS Polly Plugin This plugin is a Flutter wrapper for AWS Polly which is a cloud service that converts text into lifelike speech. Getting Star

null 4 Aug 20, 2022
A JMAP client library in Dart to make JMAP method calls and process the responses

JMAP Dart client A JMAP client library to make JMAP method calls and process the responses. We most notably use it to write the TMail Flutter applicat

LINAGORA 18 Dec 19, 2022
A pure Dart implementation of the Pusher Channels Client

pusher_channels is a pure Dart pusher channels client. This client is work in progress and it is unstable. Usage A simple usage example: import 'packa

Indaband 7 Nov 6, 2022
Dart phone number parser, based on libphonenumber and PhoneNumberKit.

Dart library for parsing phone numbers. Inspired by Google's libphonenumber and PhoneNumberKit for ios.

cedvdb 39 Dec 31, 2022
Dart phone number parser, based on libphonenumber and PhoneNumberKit.

Phone Numbers Parser Dart library for parsing phone numbers. Inspired by Google's libphonenumber and PhoneNumberKit for ios. The advantage of this lib

cedvdb 39 Dec 31, 2022
AFINN-based sentiment analysis for dart

Dart Sentiment is a dart module that uses the AFINN-165 wordlist and Emoji Sentiment Ranking to perform sentiment analysis on arbitrary blocks of input text.

Akash Lilhare 7 Nov 2, 2022