运行效果
使用http 需要导入http 库【在pubspec.yaml文件中添加】
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(new MaterialApp(
home: new SampleAppPage(),
));
}
class SampleAppPage extends StatefulWidget {
SampleAppPage({Key key}) : super(key: key);
@override
State<StatefulWidget> createState() => new _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
List widgets = [];
@override
void initState() {
super.initState();
loadDate();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('SampleAppage'),
),
body: new ListView.builder(
itemBuilder: (BuildContext, int) {
return new ListTile(
dense: false,
title: new Text(
'${widgets[int]["title"]}',
maxLines: 1,
overflow: TextOverflow.fade,
),
subtitle: new Text(
'${widgets[int]["body"]}',
maxLines: 1,
),
trailing: new Text('trailing'),
leading: new CircleAvatar(
child: new Text('${widgets[int]["id"]}'),
backgroundColor: Colors.redAccent,
),
);
},
),
);
}
Widget getRow(int i) {
return new Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Padding(
padding: new EdgeInsets.all(5.0),
child: new Text('${widgets[i]["title"]}'),
),
new Divider(
indent: 10.0,
height: 10.0,
color: Colors.blue,
),
],
);
}
loadDate() async {
String dateUrl = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(dateUrl);
print(response.statusCode);
setState(() {
widgets = json.decode(response.body);
});
}
}
知识点
- flutter 异步支持 主要是 async await 关键字 ,详细参考dart语言异步
- as 关键字
指定库前缀
如果导入两个库是有冲突的标识符,那么你可以指定一个或两个库的前缀。例如,如果 library1 和 library2 都有一个元素类,那么你可能有这样的代码:
import 'package:lib1/lib1.dart'; import 'package:lib2/lib2.dart' as lib2; // ... var element1 = new Element(); // 使用lib1里的元素 var element2 = new lib2.Element(); // 使用lib2里的元素
listview 的 子 item 可以是任何wdiget,这里使用系统提供的一种ListTile控件
如图:
new ListTile(
dense: false,
title: new Text(//
'${widgets[int]["title"]}',标题
maxLines: 1,
overflow: TextOverflow.fade,
),
subtitle: new Text(//副标题
'${widgets[int]["body"]}',
maxLines: 1,
),
trailing: new Text('trailing'),//标题后面
leading: new CircleAvatar(//一般为CircleAvatar 一个圆形区域可以添加子控件
child: new Text('${widgets[int]["id"]}'),
backgroundColor: Colors.redAccent,
),
);