Json 如何在颤振上使用API

Json 如何在颤振上使用API,json,flutter,flutter-dependencies,Json,Flutter,Flutter Dependencies,我想在颤振上使用这个api 有人能给我举个如何使用它的例子吗 谢谢您需要使用http包。官方文件始终是最佳来源: 链接网站中的完整示例,但有最关键的代码: import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; Future<Album> fetchAlbum() async { fi

我想在颤振上使用这个api 有人能给我举个如何使用它的例子吗


谢谢

您需要使用http包。官方文件始终是最佳来源:

链接网站中的完整示例,但有最关键的代码:

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'],
    );
  }
}
导入'dart:async';
导入“dart:convert”;
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
Future fetchAlbum()异步{
最后答复=
等待http.get('https://jsonplaceholder.typicode.com/albums/1');
如果(response.statusCode==200){
//如果服务器确实返回了200 OK响应,
//然后解析JSON。
返回Album.fromJson(jsonDecode(response.body));
}否则{
//如果服务器没有返回200 OK响应,
//然后抛出一个异常。
抛出异常(“加载相册失败”);
}
}
班级相册{
最终int用户标识;
最终int id;
最后的字符串标题;
相册({this.userId,this.id,this.title});
factory Album.fromJson(映射json){
返回相册(
userId:json['userId'],
id:json['id'],
标题:json['title'],
);
}
}
是的(如果可以的话)我是新来的,这可能会对你有所帮助。