【发布时间】:2021-04-09 06:05:09
【问题描述】:
我想在 Flutter 上使用这个 api https://vpic.nhtsa.dot.gov/api/ 谁能给我一个如何使用它的例子
谢谢
【问题讨论】:
-
是的(如果可以的话)我是 Flutter 新手
-
这个video tutorial可能对你有帮助。
标签: json flutter flutter-dependencies
我想在 Flutter 上使用这个 api https://vpic.nhtsa.dot.gov/api/ 谁能给我一个如何使用它的例子
谢谢
【问题讨论】:
标签: json flutter flutter-dependencies
你需要使用http包。官方文档永远是最好的来源:https://flutter.dev/docs/cookbook/networking/fetch-data
链接网站中的完整示例,但有最关键的代码:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/albums/1');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album({this.userId, this.id, this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
【讨论】: