18-Flutter移動電商實戰-首頁_火爆專區商品接口製做

一、獲取接口的方法

在service/service_method.dart裏製做方法。咱們先不接收參數,先把接口調通。java

Future getHomePageBeloConten() async{

  try{
    print('開始獲取下拉列表數據.................');
    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('後端接口出現異常,請檢測代碼和服務器狀況.........');
    }
  }catch(e){
      return print('ERROR:======>${e}');
  }

}

簡單說一下 Future,在咱們平時開發中咱們是這樣用的,首先給咱們的函數後面加上 async 關鍵字,表示異步操做,而後函數返回值寫成 Future,而後咱們能夠 new 一個 Future,邏輯前面加上一個 await關鍵字,而後能夠使用future.then 等操做。web

二、進行調試接口

接口對接的方法寫好了,而後咱們進行測試一下接口是否能夠讀出數據,若是能讀出數據,就說明接口已經調通,咱們就能夠搞事情了。後端

由於這個新的類是由下拉刷新的,也就是動態的類,因此須要使用StatefulWidget。bash

代碼以下:服務器

class HotGoods extends StatefulWidget {
  _HotGoodsState createState() => _HotGoodsState();
}

class _HotGoodsState extends State<HotGoods{


   void initState() 
     super.initState();
      getHomePageBeloConten().then((val){
         print(val);
      });
   }

  @override
  Widget build(BuildContext context) {
    return Container(
       child:Text('1111'),
    );
  }
}

三、精簡代碼,來個通用接口

在寫service_method.dart的時候,你會發現咱們大部分的代碼都是相同的,甚至複製一個方法後,經過簡單的修改幾個地方,就能夠使用了。那就說明這個地方由優化的必要。讓代碼更通用更精簡。app

精簡代碼以下:異步

Future request(url,formData)async{
    try{
      print('開始獲取數據...............');
      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('後端接口出現異常,請檢測代碼和服務器狀況.........');
      }
    }catch(e){
        return print('ERROR:======>${e}');
    }

}

使用也是很是簡單的,只要傳遞一個接口名稱和相對參數就能夠了。async

request('homePageBelowConten',1).then((val){
    print(val);});
相關文章
相關標籤/搜索