network 0.9.3

  • Readme
  • Changelog
  • Example
  • Installing
  • 84
Logo

Package including hooks for easy works with http package in dart.

Pub

Key FeaturesGetting StartedTodoCredits

Key Features #

  • Simple hooks for get / post
  • Specify response type (blob\json api)

Getting Started #

// Simplify usage
import 'package:network/hooks.dart' as network;
network.get(...);
network.post(...);

// Alternative usage
import 'package:network/network.dart';
final client = Network();
client.get(...);
client.post(...);
client.close();

For new users (0.8.0+) before all usages need disable backward compatibility

network.settings.disableLegacy();

Get request to API:

final restResponse = await network.get<network.JsonApiResponse>(
  'https://jsonplaceholder.typicode.com/todos/1',
  queryParameters: {'name': 'value'}
);
print(restResponse.toMap['title']);

Get request Blob:

final blobResponse = await network.get(
  'https://via.placeholder.com/300',
);
print(blobResponse.bytes);

Post request to API:

final postResponse = await network.post<network.JsonApiResponse>(
  'https://jsonplaceholder.typicode.com/todos',
  body: {'title': 'test'},
);
print(postResponse.toMap['id']);

Handle exceptions:

try {
  await network.get('https://jsonplaceholder.typicode.com/todos/202');
} on network.NetworkException catch (error) {
  print('Network exception called, status code: ${error.code}');
}

Add middleware:

import 'package:network/middlewares.dart';

network.settings.middleware.addAll([
  defaultErrors(),
  network.Middleware(
    onRequest: (request) {
      print('request on: ${request.url}');
      return request.copyWith(
        url: request.url + '/additional-link',
      );
    },
    onResponse: (response) {
      print('response status code: ${response.statusCode}');
      return response;
    },
    onError: (error) {
      if (error is UnauthorizedException) {
        signOut();
      }

      return error;
    },
  )
]);

And... all api docs available here

Credits #

This software uses the following open source packages:

0.9.3 #

  • Fixed client

0.9.2 #

  • Fixed middleware

0.9.1 #

  • Fixed error on empty middleware methods

0.9.0 #

  • Added optional http.Client argument Network(http.Client())
  • Added (local) middlewares for client Network().middleware.add()

0.8.0 #

  • Added global middleware! Usage example:
network.settings.middleware.add(
  network.Middleware(
    onRequest: (request) => request,
    onResponse: (response) => response,
    onError: (error) => error,
  )
);
  • Simplify usage settings (network.NetworkSettings()... -> network.settings...)
  • NetworkSettings.{exceptionDelegate, successfulDelegate, hasSuccessfulDelegate} marked as deprecated ann will be removed in 1.0.0
  • Usage as client available!
import 'package:network/network.dart';
final client = Network();
client.get(...);
client.post(...);
client.close();
  • Added network.head() method
  • Added Response.request
  • Added PaymentRequired & MethodNotAllowed http exceptions;

0.7.1 #

  • Fix default headers

0.7.0 #

  • Added property to use an external http-client

0.6.0 #

  • Added userAgent (available in Settings)
  • Added defaultHeaders (available in Settings)
  • Added default http exceptions (like a unauthorized, not found etc)

0.5.0 #

  • Refactoring

0.4.0 #

  • Added NetworkUnavailableException
  • Fixed exceptionDelegate

0.3.0 #

  • Added NetworkSettings
  • Added exceptionDelegate in NetworkSettings

0.2.0 #

  • Added toString() method for NetworkException and BinaryResponse
  • Added toJsonApiResponse() method for BinaryResponse

0.1.0 #

  • Added parameter queryParameters for all methods
  • Removed parameter jsonBody from post and put methods

0.0.2 #

  • Removed debug print
  • Added hooks for delete & put http methods

0.0.1 #

  • Initial release

example/main.dart

import 'package:network/network.dart' as network;

/// HTTP 400
class BadRequestException<T extends network.BinaryResponse>
    extends network.NetworkException<T> {
  BadRequestException(T response) : super(response);
}

/// HTTP 404
class NotFoundException<T extends network.BinaryResponse>
    extends network.NetworkException<T> {
  NotFoundException(T response) : super(response);
}

/// No connection to internet
class NoInternetConnection {}

main() async {
  network.settings
    ..middleware.add(network.Middleware(
      onRequest: (request) {
        print('\n request: ${request.url} \n');
        return request;
      },
      onError: (error) {
        if (error is network.NetworkException) {
          switch (error.code) {
            case 400:
              return BadRequestException(error.response);
            case 404:
              return NotFoundException(error.response);
            default:
              return error;
          }
        } else if (error is network.NetworkUnavailableException) {
          return NoInternetConnection();
        }

        return error;
      },
    ));

  try {
    final getResponse = await network.get<network.JsonApiResponse>(
        'https://jsonplaceholder.typicode.com/comments',
        queryParameters: {'postId': 1});
    print(getResponse.toList[1]['body']);

    // Post request to api
    final postResponse = await network.post<network.JsonApiResponse>(
        'https://jsonplaceholder.typicode.com/todos',
        body: {'title': 'test'});
    print(postResponse.toMap['id']);
  } on NoInternetConnection {
    print('No internet connection');
  }

  // Or post binary
  await network.post<network.JsonApiResponse>(
      'https://jsonplaceholder.typicode.com/todos',
      body: [0, 0, 0, 0, 0]);

  // Handle exceptions
  try {
    await network.get('https://jsonplaceholder.typicode.com/todos/202');
  } on network.NetworkException catch (error) {
    print('Network exception handled: ${error}');
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  network: ^0.9.3

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:network/network.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
69
Health:
Code health derived from static analysis. [more]
99
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
84
Learn more about scoring.

We analyzed this package on Dec 7, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.1
  • pana: 0.12.21

Platforms

Detected platforms: Flutter, other

Primary library: package:network/network.dart with components: io.

Health suggestions

Fix lib/src/network.dart. (-1 points)

Analysis of lib/src/network.dart reported 2 hints:

line 201 col 28: Unnecessary new keyword.

line 213 col 15: Unnecessary new keyword.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.2 <3.0.0
http ^0.12.0+2 0.12.0+2
meta ^1.1.0 1.1.8
Transitive dependencies
async 2.4.0
charcode 1.1.2
collection 1.14.12
http_parser 3.1.3
path 1.6.4
pedantic 1.9.0
source_span 1.5.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
Dev dependencies
test ^1.5.3