18-Flutter移动电商实战-首页_火爆专区商品接口制作
1、獲取接口的方法
在service/service_method.dart里制作方法。我們先不接收參數(shù),先把接口調(diào)通。
Future?getHomePageBeloConten()?async{try{print('開始獲取下拉列表數(shù)據(jù).................');Response?response;Dio?dio?=?new?Dio();dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");int?page=1;response?=?await?dio.post(servicePath['homePageBelowConten'],data:page);if(response.statusCode==200){return?response.data;}else{throw?Exception('后端接口出現(xiàn)異常,請(qǐng)檢測(cè)代碼和服務(wù)器情況.........');}}catch(e){return?print('ERROR:======>${e}');}}簡(jiǎn)單說一下 Future,在我們平時(shí)開發(fā)中我們是這樣用的,首先給我們的函數(shù)后面加上 async 關(guān)鍵字,表示異步操作,然后函數(shù)返回值寫成 Future,然后我們可以 new 一個(gè) Future,邏輯前面加上一個(gè) await關(guān)鍵字,然后可以使用future.then 等操作。
2、進(jìn)行調(diào)試接口
接口對(duì)接的方法寫好了,然后我們進(jìn)行測(cè)試一下接口是否可以讀出數(shù)據(jù),如果能讀出數(shù)據(jù),就說明接口已經(jīng)調(diào)通,我們就可以搞事情了。
因?yàn)檫@個(gè)新的類是由下拉刷新的,也就是動(dòng)態(tài)的類,所以需要使用StatefulWidget。
代碼如下:
class?HotGoods?extends?StatefulWidget?{_HotGoodsState?createState()?=>?_HotGoodsState(); }class?_HotGoodsState?extends?State<HotGoods>?{void?initState()?{?super.initState();getHomePageBeloConten().then((val){print(val);});}@overrideWidget?build(BuildContext?context)?{return?Container(child:Text('1111'),);} }3、精簡(jiǎn)代碼,來個(gè)通用接口
在寫service_method.dart的時(shí)候,你會(huì)發(fā)現(xiàn)我們大部分的代碼都是相同的,甚至復(fù)制一個(gè)方法后,通過簡(jiǎn)單的修改幾個(gè)地方,就可以使用了。那就說明這個(gè)地方由優(yōu)化的必要。讓代碼更通用更精簡(jiǎn)。
精簡(jiǎn)代碼如下:
Future?request(url,formData)async{try{print('開始獲取數(shù)據(jù)...............');Response?response;Dio?dio?=?new?Dio();dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");if(formData==null){response?=?await?dio.post(servicePath[url]);}else{response?=?await?dio.post(servicePath[url],data:formData);}if(response.statusCode==200){return?response.data;}else{throw?Exception('后端接口出現(xiàn)異常,請(qǐng)檢測(cè)代碼和服務(wù)器情況.........');}}catch(e){return?print('ERROR:======>${e}');}}使用也是非常簡(jiǎn)單的,只要傳遞一個(gè)接口名稱和相對(duì)參數(shù)就可以了。
request('homePageBelowConten',1).then((val){print(val); });總結(jié)
以上是生活随笔為你收集整理的18-Flutter移动电商实战-首页_火爆专区商品接口制作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2/19 福建四校联考
- 下一篇: 如何优化网站页面提高网页的加载速度