本篇教程聊一聊flutter中http的坑,閱讀本教程以前假設你已經掌握了flutter的一些基礎知識,好比環境搭建,簡單的dart語法,及flutter組件化思想。前端
由於我是前端,因此數據交互邏輯都是之前端的思想設計,若是有不對的地方,歡迎你們指正。python
先看效果圖ajax
整個頁面就是一個長list新聞列表,後臺是本身用django寫的,數據是python爬的,咱們先寫一個新聞的模板,效果如圖:django
咱們先新建一個模板的文件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中進行網絡請求,首先到導入兩個包:bash
import 'dart:io';網絡
import 'dart:convert';app
so異步
import 'package:flutter/material.dart';
import './News.dart';
import 'dart:io';
import 'dart:convert';
複製代碼
而後異步請求數據,代碼以下:async
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(),
);
}
}
複製代碼
代碼都是參考官網英文文檔擼的,可是本人是英語渣,因此若是有不對的地方,歡迎你們指正!