簡體   English   中英

從 Flutter (Dart) 中的快速 API 獲取 json 數據

[英]Get json Data from Rapid API in Flutter (Dart)

我設法從 Flutter 項目的本地 Json 文件中加載數據。 如果 API Url 像這樣,我也能夠從 Internet 獲取數據:

https://[API-Server][parameter1:xy][parameter2:abc][API-KEY:lasgoewrijeowfjsdfdfiia]

我用這個代碼示例歸檔了它:

  Future<String> _loadStringFixtures() async {
    return await rootBundle.loadString('assets/fixtures.json');
  }

  Future loadFixtures() async {
    String jsonString = await _loadStringFixtures();
    final jsonResponse = json.decode(jsonString);
    FixturesAPI value = new FixturesAPI.fromJson(jsonResponse);
    return value;
  }

到目前為止,一切都很好...

但是現在我遇到了 API Provider RapidAPI 的問題您可以在此處找到文檔等: https://rapidapi.com/api-sports/api/api-football/endpoints

如您所見,他們提供了一些代碼片段來連接到他們的 API。 There are some for C, C#, Java, Python etc. You can look into all of them with the link above. 遺憾的是,沒有 Flutter 的示例。 而且我看不到調整這些示例的方法。

通常您可以將您的 API 密鑰直接粘貼到 URL 中,但這似乎不可能? 或者也許是?

除了我所做的之外,Flutter 是否還有其他可能從 API 接收數據?

非常感謝您的幫助!

可以使用http package並且非常容易。 您可以在下面的示例中看到...

import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

class APIService {
  // API key
  static const _api_key = <YOU-API-KEY-HERE>;
  // Base API url
  static const String _baseUrl = "api-football-beta.p.rapidapi.com";
  // Base headers for Response url
  static const Map<String, String> _headers = {
    "content-type": "application/json",
    "x-rapidapi-host": "api-football-beta.p.rapidapi.com",
    "x-rapidapi-key": _api_key,
  };

  // Base API request to get response
  Future<dynamic> get({
    @required String endpoint,
    @required Map<String, String> query,
  }) async {
    Uri uri = Uri.https(_baseUrl, endpoint, query);
    final response = await http.get(uri, headers: _headers);
    if (response.statusCode == 200) {
      // If server returns an OK response, parse the JSON.
      return json.decode(response.body);
    } else {
      // If that response was not OK, throw an error.
      throw Exception('Failed to load json data');
    }
  }
}

然后得到你的要求:

//....
APIService apiService = APIService();
// You future
Future future;
//in the initState() or use it how you want...
future = apiService.get(endpoint:'/fixtures', query:{"live": "all"});

//....

是的,在 flutter 中是可能的。 在 flutter 中使用Dio Package ,這是一個強大的 Http 客戶端。 使用 dio 您可以設置攔截器以將 api 密鑰添加到 url ,因此您不必在每個請求中都添加 append 。 設置攔截器將對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM