import 'package:flutter/material.dart';
import 'package:http/http.dart';--http包文件
import 'dart:async';--异步操作
import 'dart:convert';--JSON转换
void main() => runApp(new MaterialApp(
home: new MyGetHttpDate(),
));
class MyGetHttpDate extends StatefulWidget {
@override
State<StatefulWidget> createState() => MyGetHttpDateState();
}
class MyGetHttpDateState extends State<MyGetHttpDate> {
final String url = "https://swapi.co/api/people";
List data;
Future<String> getJsonData() async {
var response =
await get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
print(response);
setState(() {
var dataConvertedToJSON = jsonDecode(response.body);
data = dataConvertedToJSON['results'];
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Center(
child: new Text("Retrieve JSON Data via HTTP GET"),
),
),
body: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new Container(
child: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Card(
child: new Container(
child: new Text(data[index]['name'],
style: new TextStyle(
fontSize: 20.0, color: Colors.lightBlueAccent)),
padding: EdgeInsets.all(15.0),
),
),
],
),
),
);
},
),
);
}
@override
void initState() {
super.initState();
this.getJsonData();
}
}
网友评论