本篇文章記錄我在使用Flutter開發中如何請求後端接口獲取數據, 使用到的包有http
用來發送請求,async
提供Future
抽象類以及convert
用來將json數據轉換爲dart裏面的對象。git
首先使用flutter create xxx
命令或者 IDEA 新建一個Flutter項目,去掉示例代碼,將須要的依賴引入github
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
複製代碼
根據接口返回數據定義好須要的數據類,例如接口返回的數據爲一個數據列表json
[
{
"mal_id": 199,
"rank": 4,
"url": "https://myanimelist.net/anime/199/Sen_to_Chihiro_no_Kamikakushi",
"image_url": "https://myanimelist.cdn-dena.com/r/100x140/images/anime/6/79597.jpg?s=63a85532fc52356a938354277201d43c",
"title": "Sen to Chihiro no Kamikakushi",
"type": "Movie",
"score": 8.91,
"members": 730646,
"airing_start": "Jul 2001",
"airing_end": "Jul 2001",
"episodes": 1
}
]
複製代碼
根據須要的數據字段定義 Animate
類, Animate.fromJson
方法使用json數據生成一個Animate
實例後端
class Animate {
final int rank;
final String imgUrl;
final String title;
final double score;
final String url;
final String airingStart;
final String airingEnd;
Animate({
this.rank,
this.imgUrl,
this.title,
this.score,
this.url,
this.airingStart,
this.airingEnd,
});
factory Animate.fromJson(Map<String, dynamic> json) {
return Animate(
rank: json['rank'] as int,
imgUrl: json['image_url'] as String,
title: json['title'] as String,
score: json['score'] as double,
url: json['url'] as String,
airingStart: json['airing_start'] as String,
airingEnd: json['airing_end'] as String,
);
}
}
複製代碼
以後使用http
發送請求,定義一個StatefulWidget
以及它的State
類,定義一個變量存儲數據,定義獲取數據的方法,而後重寫類的initState
方法,在initState
方法裏面調用請求數據的方法 less
StatelessWidget
類來做爲列表中的每一項,這個類須要一個
Animate
類的實例來填充數據
最後使用
ListView.builder
方法生成ListView
完成效果如圖 async
github地址ui