Flutter获取json数据

发布于2/1/2020 来自:「前端知否」微信公众号

在应用程序初始化时,我们进行json api调用并填充一个listview。

首先,将http依赖项添加到pubspec.yaml文件中。这类似于将依赖项添加到节点应用程序的package.json中。

name: apiJsonListview
description: An app to illustrate Listview with Http call for json.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
http: ^0.12.0+4

dev_dependencies:
flutter_test:
sdk: flutter

flutter:
uses-material-design: true

我们将从https://jsonplaceholder.typicode.com/users中提取用户数据,数据如下。

[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
...
]

让我们编写一个dart类,实现http请求逻辑。

import 'dart:async';
import 'package:http/http.dart' as http;

const baseUrl = "https://jsonplaceholder.typicode.com";

class API {
static Future getUsers() {
var url = baseUrl + "/users";
return http.get(url);
}
}

在这里您可以看到我编写了一个静态函数,该函数返回Future,相当于JS世界中的"Promise"

我们需要一个User类,用于接收并转换json数据:

class User {
int id;
String name;
String email;

User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}

User.fromJson(Map json)
: id = json['id'],
name = json['name'],
email = json['email'];

Map toJson() {
return {'id': id, 'name': name, 'email': email};
}
}

现在,让我们编写主要代码。

import 'dart:convert';
import 'package:apiJsonListview/API.dart';
import 'package:apiJsonListview/models/User.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
build(context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My Http App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyListScreen(),
);
}
}

class MyListScreen extends StatefulWidget {
@override
createState() => _MyListScreenState();
}

class _MyListScreenState extends State {
var users = new List<User>();

_getUsers() {
API.getUsers().then((response) {
setState(() {
Iterable list = json.decode(response.body);
users = list.map((model) => User.fromJson(model)).toList();
});
});
}

initState() {
super.initState();
_getUsers();
}

dispose() {
super.dispose();
}

@override
build(context) {
return Scaffold(
appBar: AppBar(
title: Text("User List"),
),
body: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return ListTile(title: Text(users[index].name));
},
));
}
}

在这里,我们创建主应用程序(第8行),其主界面为MyListScreen

在MyListScreen初始化时,通过API静态方法调用_getUsers方法,并设置用户状态(第32行)。状态更新后,会重新构建UI界面。

xxx