06-Flutter移動電商實戰-dio基礎_Get_Post請求和動態組件協作


上篇文章中,我們只看到了 dio 的使用方式,但並未跟應用關聯起來,所以這一篇將 dio 網絡請求與應用界面結合起來,當然這也是為以后的實戰作基礎准備,基礎打牢,我們才能飛速前進。

1、案例說明

我們還是作去“大保健”選擇服務對象這個例子,不過這次我們使用按鈕和動態組件來實現。具體業務邏輯是這樣的:

  1. 我們制作一個文本框,用於輸入需要什么樣的美女為我們服務
  2. 然后點擊按鈕,相當於去后端請求數據
  3. 后端返回數據后,根據你的需要美女就會走進房間

一圖頂千言

2、生成動態組件

可以使用stful的快捷方式,在AndroidStudio里快速生成StatefulWidget的基本結構,我們只需要改一下類的名字就可以了,就會得到如下代碼.

class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage{
  @override
  Widget build(BuildContext context) {
    return Container(
       child: child,
    );
  }
}

3、加入文本框Widget

有了動態組件,咱們先把界面布局作一下。

Widget build(BuildContext context) {
    return Container(

        child: Scaffold(
          appBar: AppBar(title: Text('美好人間'),),
          body:Container(
            height: 1000,
            child: Column(
              children: <Widget>[
                TextField(
                  controller:typeController,
                  decoration:InputDecoration (
                    contentPadding: EdgeInsets.all(10.0),
                    labelText: '美女類型',
                    helperText: '請輸入你喜歡的類型'
                  ),
                  autofocus: false,
                ),
                RaisedButton(
                  onPressed:_choiceAction,
                  child: Text('選擇完畢'),
                ),

                Text(
                  showText,
                    overflow:TextOverflow.ellipsis,
                    maxLines: 2,
                ),
                ],
            ),
          ) 
        ),
    );
  }

4、Dio的get_post方法

布局完成后,可以先編寫一下遠程接口的調用方法,跟上節課的內容類似,不過這里返回值為一個Future,這個對象支持一個等待回掉方法then。具體代碼如下:

Future getHttp(String TypeText)async{
    try{
      Response response;
      var data={'name':TypeText};
      response = await Dio().get(
        "https://www.easy-mock.com/mock/5c60131a4bed3a6342711498/baixing/dabaojian",
          queryParameters:data
      );
      return response.data;
    }catch(e){
      return print(e);
    }
  }

post方法如上方幾乎一致,只是改變了請求方式:

 Future getHttp(String TypeText) async{
    try{
      Response response;
      var data={'name':TypeText};
      response = await Dio().post(
          "https://www.easy-mock.com/mock/5c60131a4bed3a6342711498/baixing/post_dabaojian",
          queryParameters:data
      );
      return response.data;
    }catch(e){
      return print(e);
    }
  }

為何要返回 Feature,只有返回 Feature 才能使用 then 回調。

5、得到數據后的處理

當我們寫完內容后,要點擊按鈕,按鈕會調用方法,並進行一定的判斷。比如判斷文本框是不是為空。然后當后端返回數據時,我們用setState方法更新了數據。

具體代碼如下:

void _choiceAction(){
    print('開始選擇你喜歡的類型............');
    if(typeController.text.toString()==''){
      showDialog(
        context: context,
        builder: (context)=>AlertDialog(title:Text('美女類型不能為空'))
      );
    }else{
        getHttp(typeController.text.toString()).then((val){
         setState(() {
           showText=val['data']['name'].toString();
         });
        });
    }

  }

6、案例全部代碼

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';


class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage{

  TextEditingController typeController = TextEditingController();
  String showText = '歡迎你來到美好人間';
  @override
  Widget build(BuildContext context) {
    return Container(

        child: Scaffold(
          appBar: AppBar(title: Text('美好人間'),),
          body:Container(
            height: 1000,
            child: Column(
              children: <Widget>[
                TextField(
                  controller:typeController,
                  decoration:InputDecoration (
                    contentPadding: EdgeInsets.all(10.0),
                    labelText: '美女類型',
                    helperText: '請輸入你喜歡的類型'
                  ),
                  autofocus: false,
                ),
                RaisedButton(
                  onPressed:_choiceAction,
                  child: Text('選擇完畢'),
                ),

                Text(
                  showText,
                    overflow:TextOverflow.ellipsis,
                    maxLines: 2,
                ),

                ],
            ),
          ) 
        ),
    );
  }

  void _choiceAction(){
    print('開始選擇你喜歡的類型............');
    if(typeController.text.toString()==''){
      showDialog(
        context: context,
        builder: (context)=>AlertDialog(title:Text('美女類型不能為空'))
      );
    }else{
        getHttp(typeController.text.toString()).then((val){
         setState(() {
           showText=val['data']['name'].toString();
         });
        });
    }

  }

  Future getHttp(String TypeText)async{
    try{
      Response response;
      var data={'name':TypeText};
      response = await Dio().get(
        "https://www.easy-mock.com/mock/5c60131a4bed3a6342711498/baixing/dabaojian",
          queryParameters:data
      );
      return response.data;
    }catch(e){
      return print(e);
    }
  }
}

7、總結

通過這節課的學習,我們應該掌握如下知識點

  1. 對Flutter動態組件的深入了解
  2. Future對象的使用
  3. 改變狀態和界面的setState的方法應用
  4. TextField Widget的基本使用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM