本篇教程聊一聊flutter中http的坑,阅读本教程之前假设你已经掌握了flutter的一些基础知识,比如环境搭建,简单的dart语法,及flutter组件化思想。
因为我是前端,所以数据交互逻辑都是以前端的思想设计,如果有不对的地方,欢迎大家指正。
先看效果图
整个页面就是一个长list新闻列表,后台是自己用django写的,数据是python爬的,我们先写一个新闻的模板,效果如图:
我们先新建一个模板的文件News.dart,代码如下:
import 'package:flutter/material.dart';
class News extends StatefulWidget {
final String title,imglink;
News(this.title,this.imglink);
@override
createState() => new NewsState();
}
class NewsState extends State<News> {
@override
Widget build(BuildContext context){
return new Center(
child:new Container(
height: 120.0,
padding:new EdgeInsets.only(left:20.0,right:20.0),
decoration: new BoxDecoration(
border:new Border(
bottom: new BorderSide(width: 1.0,color:const Color(0xff999999))
)
),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new Expanded(
flex:2,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment:MainAxisAlignment.spaceBetween ,
children: <Widget>[
new Container(
padding:new EdgeInsets.only(top:15.0),
decoration: new BoxDecoration(
),
child:new Text(
widget.title,
style: new TextStyle(
fontSize: 18.0
),
),
),
new Container(
padding:const EdgeInsets.only(right:13.0,bottom:15.0),
decoration: new BoxDecoration(
),
child:new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Text(
'本地新闻',
),
new Text(
'2018-03-11',
),
],
)
),
],
),
),
new Expanded(
flex:1,
child: new Image.network(
widget.imglink,
scale: 1.0,
fit: BoxFit.cover,
),
),
],
),
),
);
}
}
关于这个模板页面,前面有教程,大家可以自行前去浅尝flutter中的flex布局查看
现在开始重点,我们在flutter中进行网络请求,首先到导入两个包:
import 'dart:io';
import 'dart:convert';
so
import 'package:flutter/material.dart';
import './News.dart';
import 'dart:io';
import 'dart:convert';
然后异步请求数据,代码如下:
List<Map <String,String>> newTitle=[];
_get() async {
var responseBody;
var url='http://127.0.0.1:8000/yt/getapp/';
var httpClient = new HttpClient();
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == 200) {
responseBody = await response.transform(utf8.decoder).join();
responseBody=JSON.decode(responseBody);
}else{
print("error");
}
await responseBody['msg'].map((Map item){
newTitle.add(item);
}).toList();
}
整个逻辑也不会麻烦,所以全部代码如下:
import 'package:flutter/material.dart';
import './News.dart';
import 'dart:io';
import 'dart:convert';
class TabPage3 extends StatefulWidget {
@override
createState() => new TabPage3States();
}
class TabPage3States extends State<TabPage3> {
@override
Widget build(BuildContext context) {
List<Map <String,String>> newTitle=[];
_get() async {
var responseBody;
var url='http://127.0.0.1:8000/yt/getapp/';
var httpClient = new HttpClient();
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == 200) {
responseBody = await response.transform(utf8.decoder).join();
responseBody=JSON.decode(responseBody);
}else{
print("error");
}
await responseBody['msg'].map((Map item){
newTitle.add(item);
}).toList();
}
_get();
return new ListView(
children: newTitle.map((Map item){
return new News(item['title'],item['imglinks']);//News接收2个参数(标题和图片url)
}).toList(),
);
}
}
这样run的话,肯定会抛错的,第一个坑:
var url='http://127.0.0.1:8000/yt/getapp/';
这个接口是我自己用django写的,ajax测试完全没有问题,但是在在模拟器上会报一个莫名其妙的错误,我明明是8000端口,它报错38588有毛病:
莫名其妙的错误让人防不胜防,但是我也不是一个错误就能吓到的,经过我多方查资料,大概意思就是Android底层是Linux内核,它本身就是一个操作系统,所以我们在模拟器的浏览器中输入127.0.0.1所代表的是Android模拟器(Android吸泥机),并不是你的电脑,所以在模拟器中会出错。在Android操作系统中,将本地电脑映射为10.0.2.2,所以只需要改成10.0.2.2就ok了。因为我这个接口是自己写的,所以还需要在django的settings中配置一下:
ALLOWED_HOSTS = [
'10.0.2.2',
'127.0.0.1'
]
第二个坑,因为我们_get()是异步操作,ListView里面newTitle的值始终是空
return new ListView(
children: newTitle.map((Map item){
return new News(item['title'],item['imglinks']);//item==>null
}).toList(),
);
解决这个问题的过程很曲折,花了两天时间,解决办法很简单,就是把_get()放到build外面去,还有个办法就是,获取future类型函数的返回值,传送门flutter实战3:制作新闻分类列表。
最后贴上全部代码:
import 'package:flutter/material.dart';
import './News.dart';
import 'dart:io';
import 'dart:convert';
class TabPage3 extends StatefulWidget {
@override
createState() => new TabPage3States();
}
class TabPage3States extends State<TabPage3> {
@override
List<Map <String,String>> newTitle=[];
_get() async {
// List<Map> _newTitle=new List();
var responseBody;
var url='http://10.0.2.2:8000/yt/getapp/';
var httpClient = new HttpClient();
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == 200) {
responseBody = await response.transform(utf8.decoder).join();
responseBody=JSON.decode(responseBody);
}else{
print("error");
}
await responseBody['msg'].map((Map item){
newTitle.add(item);
}).toList();
}
Widget build(BuildContext context) {
_get();
return new ListView(
children: newTitle.map((Map item){
return new News(item['title'],item['imglinks']);
}).toList(),
);
}
}
代码都是参考官网英文文档撸的,但是本人是英语渣,所以如果有不对的地方,欢迎大家指正!