我想在flutter上使用这个api https://vpic.nhtsa.dot.gov/api/ 有人可以给我一个如何使用它的例子
谢谢
答案 0 :(得分:1)
你需要使用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'],
);
}
}