06-Flutter mobile provider combat -dio basis _Get_Post request and dynamic components collaboration

The previous article, we only see the use dio, but did not associate it with the application, so this one will dio network request and application interfaces combined, of course, this is also prepared as a basis for future combat, to lay a solid foundation we can rapidly move forward.

1, case notes

We choose to serve as an example of this "great care", but this time we use buttons and dynamic components to achieve. Specific business logic is this:

  1. We make a text box for entering what kind of beauty for us
  2. Then click on the button, which is equivalent to the back-end data request
  3. After the back-end data is returned, according to your needs beauty will walk into the room

A view of the top thousand words

2, the dynamic component generated

You can use a shortcut stful quickly generate a basic structure StatefulWidget in AndroidStudio, we only need to change what kind of name on it, you will get the following code.

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

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

3, add text boxes Widget

With dynamic components, first make a few interface layout.

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 method of get_post

After the layout is complete, you can write about the method call remote interface, similar to keep up with the lesson content, but here the return value is a Future, this object supports a callback method to wait then. Specific code as follows:

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 almost the same method as above except for changing the way the request:

 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);
    }
  }

Why return to Feature, then only return Feature to use a callback.

5, the data obtained after processing

When we finished writing the content, to click a button, the button calls the method, and make certain judgments. Analyzing such as text box is not empty. Then when the data returned by the backend, we setState method to update the data.

Specific code as follows:

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, case all the code

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. Conclusions

By learning this lesson, we should have the following knowledge points

  1. In-depth understanding of the dynamic components of Flutter
  2. Future use of the object
  3. And changing the state of the interface of setState Methods
  4. The basic use of TextField Widget

Guess you like

Origin www.cnblogs.com/niceyoo/p/11028899.html