GithubHelp home page GithubHelp logo

flutter_api_demo's Introduction

flutter_api_demo

APIクライアントのデモ

API関連

リクエストパラメタのI/F(共通部)

abstract class RequestParameter {
  final String path = '/';
  final String key = 'XXXXXXXXXXX';
  final String format = 'json';
  final int count = 50;
}

個別のリクエストパラメタ

class GourmetRequestParameter extends Object with RequestParameter  {
  final String path = '/hotpepper/gourmet/v1';
  final String keyword;

  GourmetRequestParameter({this.keyword});

  Map<String, String> toJson() => {
    'key': key,
    'format': format,
    'keyword' : keyword,
    'count' : count.toString()
  };
}

APIクライアント

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_api_demo/models/api/GourmetRequestParameter.dart';
import 'package:flutter_api_demo/models/api/GourmetResponse.dart';

class APIClient {
  final endpoint = 'webservice.recruit.co.jp';
  final int timeoutTime = 10;

  /// グルメサーチAPIコール
  Future<GourmetResponse> getGourmet() async {
    final requestParameter = GourmetRequestParameter(keyword: '五反田');

    final response = await http
        .get(Uri.http(
            endpoint, requestParameter.path, requestParameter.toJson()))
        .timeout(Duration(seconds: timeoutTime));

    if (response.statusCode == 200) {
      final body = json.decode(response.body);
      GourmetResponse results = GourmetResponse.fromJSON(body);
      return results;
    } else {
      throw Exception(response.statusCode);
    }
  }
}

使い方

APIClient().getGourmet().then((response) {
      _shops.addAll(response.results.shop);
    }).catchError((err) {
      //エラー時の処理
      print(err.toString());
    }).whenComplete(() => isLoadingComplated = true);

レスポンスデータ

レスポンスデータ(最上位階層)

class GourmetResponse {

  final Results results;

  GourmetResponse({this.results});

  factory GourmetResponse.fromJSON(Map<String, dynamic> parsedJson) {

    return GourmetResponse(
        results: Results.fromJSON(parsedJson['results']));
  }
}

class Results {

  final String api_version;
  final String results_returned;
  final List<Shop> shop;

  Results({this.api_version, this.results_returned, this.shop});

  factory Results.fromJSON(Map<String, dynamic> json) {

    return Results(
        api_version: json['api_version'],
        results_returned: json['results_returned'],
        shop: parseShops(json)
    );
  }

  static List<Shop> parseShops(json) {
    var list = json['shop'] as List;
    List<Shop> shops = list.map((data) => Shop.fromJSON(data)).toList();
    return shops;
  }
}

レスポンスデータ(配列がネストしている場合)

class Shop {
  final String name;
  final String open;
  final String access;
  final String address;
  final Genre genre;
  final Photo photo;
  final Budget budget;

  Shop(
      {this.name,
      this.open,
      this.access,
      this.address,
      this.genre,
      this.photo,
      this.budget});

  factory Shop.fromJSON(Map<String, dynamic> json) {
    return Shop(
      name: json['name'],
      open: json['open'],
      access: json['access'],
      address: json['address'],
      genre: Genre.fromJSON(json['genre']),
      photo: Photo.fromJSON(json['photo']),
      budget: Budget.fromJSON(json['budget']),
    );
  }
}

レスポンスデータ(オブジェクト型がネストしている場合)

class Photo {
  final Mobile mobile;

  Photo({this.mobile});

  factory Photo.fromJSON(Map<String, dynamic> json) {
    return Photo(mobile: Mobile.fromJSON(json['mobile']));
  }
}

class Mobile {
  final String large;

  Mobile({this.large});

  factory Mobile.fromJSON(Map<String, dynamic> json) {
    return Mobile(large: json['l']);
  }
}

flutter_api_demo's People

Watchers

 avatar

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.