Network request result

Related tags

Templates session
Overview

Pub support

session

Network request result

json to dart https://javiercbk.github.io/json_to_dart/

Getting Started

Add dependency

dependencies:
  session: ^1.0.3+2  #latest version

Example

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:session/session.dart';

export 'package:session/session.dart' show Result;

Config configAPI(String baseURL) {
  return Config(
    baseUrl: baseURL ?? "https://www.httpbin.org/",
//    proxy: 'PROXY localhost:8888',
    connectTimeout: 10,
    receiveTimeout: 10,
  );
}

SessionInterceptorSendHandler _onRequest = (options) async {
  var headers = {
    'os': Platform.isIOS ? 'ios' : 'android',
  };
  options.headers.addAll(headers);
  // if (UserStore.store.getState().isLogin) {
  //   options.headers['id'] = UserStore.store.getState().user.userId;
  // }
  // options.contentType = Headers.formUrlEncodedContentType;
  // options.responseType = ResponseType.plain;
  return options;
};

/// 响应结果拦截处理
Result _onValidResult(Result result, bool validResult, BuildContext context) {
  // 拦截处理一些错误
  if (validResult) {
    switch (result.code) {
      case "${-3}":
        // do something...
        break;
      case "${-2}":
        // do something...
        break;
    }
  }
  return result;
}

///
/// 发送请求并解析远程服务器返回的result对应的实体类型
///
/// baseUrl: 主机地址
/// path: 请求路径
/// queryParameters: URL携带请求参数
/// connectTimeout: 超时时间
/// validResult: 是否检验返回结果
/// context: 上下文
///
Future<Result> getAPI(
    {String baseUrl,
    String path = '',
    Map<String, dynamic> queryParameters,
    int connectTimeout,
    bool validResult = true,
    BuildContext context}) async {
  return requestAPI(
      baseUrl: baseUrl,
      path: path,
      queryParameters: queryParameters,
      options: Options(method: 'get'),
      connectTimeout: connectTimeout,
      validResult: validResult,
      context: context);
}

///
/// 发送请求并解析远程服务器返回的result对应的实体类型
///
/// baseUrl: 主机地址
/// path: 请求路径
/// data: 请求参数
/// connectTimeout: 超时时间
/// validResult: 是否检验返回结果
/// context: 上下文
///
Future<Result> postAPI(
    {String baseUrl,
    String path = '',
    data,
    int connectTimeout,
    bool validResult = true,
    BuildContext context}) async {
  return requestAPI(
      baseUrl: baseUrl,
      path: path,
      data: data,
      options: Options(method: 'post'),
      connectTimeout: connectTimeout,
      validResult: validResult,
      context: context);
}

///
/// 发送请求并解析远程服务器返回的result对应的实体类型
///
/// baseUrl: 主机地址
/// path: 请求路径
/// data: 请求参数
/// validResult: 是否检验返回结果
/// context: 上下文
///
Future<Result> requestAPI(
    {String baseUrl,
    String path = '',
    data,
    Map<String, dynamic> queryParameters,
    Options options,
    int connectTimeout,
    bool validResult = true,
    BuildContext context}) async {
  Session session = Session(
    config: configAPI(baseUrl),
    onRequest: _onRequest,
  );
  Result result = await session.request(
    path,
    data: data,
    queryParameters: queryParameters,
    options: options,
    connectTimeout: connectTimeout,
  );
  return _onValidResult(result, validResult, context);
}

void example() async {
  getAPI(path: "ip").then((result) {
    print("======");
    print(result.code);
    print(result.message);
    print(result.body);
    print("======");
  });
}
You might also like...

Http request inspector for Flutter application

Http request inspector for  Flutter application

Alice Alice is an HTTP Inspector tool for Flutter which helps debugging http requests. It catches and stores http requests and responses, which can be

Dec 14, 2022

Unloc customizations of the Permission plugin for Flutter. This plugin provides an API to request and check permissions.

Flutter Permission handler Plugin A permissions plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to request and check perm

Nov 26, 2020

This repo contains a collection of permission related Flutter plugins which can be used to request permissions to access device resources in a cross-platform way.

Flutter Permission Plugins Deprecation Notice This repository has been replaced by the Flutter permission_handler plugin and will not longer be mainta

Dec 13, 2021

Hava Durumu Uygulaması - Temel Api Request

Hava Durumu Uygulaması - Temel Api Request

Hava Ne Durumda Bu uygulama temelde apilerle nasıl çalışılır, apiden veri nasıl GET edilir gibi işlemleri anlamak için yapılmıştır. Uygulama Fotoğrafl

Jun 14, 2022

Simple and hackable request for dart

Simple and hackable request for dart

Simple and hackable request for dart

Sep 22, 2022

📖 A Guide for your first pull request

 📖 A Guide for your first pull request

📖 A Guide for your first pull request This project has been excluded by Hacktoberfest 2022 ✨ This project will help you to make your first pull reque

Dec 2, 2022

A CLI tool to verify the test coverage of a pull request only, ignoring the rest of the project

A CLI tool to verify the test coverage of a pull request only, ignoring the rest of the project

This is a CI tool that analyzes the coverage rate of a pull request, ignoring the lines that were not changed in the PR. Motivation The coverage rate

Dec 15, 2022

App HTTP Client is a wrapper around the HTTP library Dio to make network requests and error handling simpler, more predictable, and less verbose.

App HTTP Client App HTTP Client is a wrapper around the HTTP library Dio to make network requests and error handling simpler, more predictable, and le

Nov 1, 2022

A 3rd party wallet for zenon.network

Notes Please don't use your main seed while testing until Cano is fully audited by the community Click Create Wallet to generate Prerequisites Flutter

Oct 26, 2022
Owner
null
Return a result ErrorOr with either a value T or an error Object.

ErrorOr Return a result ErrorOr with either a value T or an error Object. Features Always return a value ErrorOr from an async function. Let the calle

Erlend 6 Nov 6, 2022
A Flutter Result type that feels like a Freezed union.

Freezed Result A Result<Success, Failure> that feels like a Freezed union. It represents the output of an action that can succeed or fail. It holds ei

Day Logger, Inc. 2 Nov 24, 2022
will cover the GetX Named Route, GetX Route Transition, GetX Route Result, GetX Route Argument, GetX Route Parameter etc.

getx_playground 1-navigation #2-reactiv A new Fl 3-SimpleStateManagement 4-GetXControllerExample 5- DependencyExample 6-TranslationExample 7-ThemeExam

null 4 Nov 11, 2022
Ruqe brings the convenient types and methods found in Rust into Dart, such as the Result, Option, pattern-matching, etc.

ruqe Ruqe brings the convenient types and methods found in Rust into Dart, such as the Result, Option, pattern-matching, etc. Additionally, the librar

Alexander Nitiola 12 Dec 28, 2022
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

dio_http A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout

null 46 Dec 19, 2021
Youtube API in Dart app. Used for downloading media and search request.

Youtube API Youtube API made by using Dart and Flutter in a cross-platform app. Used for downloading media and search request. For an idea of how the

Avian Silviu-Gabriel 0 Nov 4, 2021
A Flutter plugin to request the device unlock screen.

device_unlock A Flutter plugin to request the device unlock screen on Android and iOS. How does it work The following attempts and fallbacks are made:

Cíngulo 19 Sep 7, 2022
A sample app of using the image_picker + path_provider and permission_handler package to request permission and store photos on mobile

image_picker_example A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you sta

iang12 4 Apr 19, 2022
A powerful Http client for Dart, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.

Language: English | 中文简体 dio A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File

Flutter中国开源项目 11.2k Jan 3, 2023
Permission plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API to request and check permissions.

Flutter permission_handler plugin The Flutter permission_handler plugin is build following the federated plugin architecture. A detailed explanation o

Baseflow 1.7k Dec 31, 2022