• flutter 网络


    代码:

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

    class HomePage extends StatefulWidget {
    HomePage({Key key}) : super(key: key);

    @override
    _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(
    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: 1,
    )

    ],
    ),
    ),
    ),
    );
    }
    void _choiceAction(){
    print('开始选择');
    if (typeController.text.toString() == '') {
    showDialog(
    context: context,
    builder: (context)=>AlertDialog(title: Text('类型不能为空'))
    );
    }else{
    getHttp(typeController.text.toString()).then(
    (val){//网络请求返回的数据 也就是Future
    setState(() {
    showText = val['data']['name'].toString();
    });
    }
    );
    }
    }
    //future 返回的对象 TypeText 文本框类型的String文本参数
    Future getHttp(String TypeText)async{
    try {
    Response res;
    var data = {'name' : TypeText};
    res = await Dio().get('https://www.easy-mock.com/mock/5c60131a4bed3a6342711498/baixing/dabaojian',
    queryParameters: data
    );
    return res;
     
    } catch (e) {
    return print(e);
    }
    }
    }
     
    总结:

     

    网络请求 引入dio

    在pubspec.yaml 下的dependencies发布环境 dio: ^xx  xx是版本号 :后有空格

    使用 dio

    async{ 异步请求

    try{

    Response res;

    res = await Dio().get(“https:xxxx”);//await 在 async 才可以使用 

    }catch(e){

     

    }

     

     

    } 

     

     

     

    通过网络请求获取到数据

    Future Methodxxx(yyyy) // Future 返回数据类型  xx方法名  yy 参数名

     

    Mehtodxxx().then(val){//val  就是Methodxx 方法中的返回类型Future

     

    }

     

    //类似OC Alert

    AlertDialog(title:Text(‘xxx’))

  • 相关阅读:
    BZOJ4821 SDOI2017相关分析(线段树)
    BZOJ3167/BZOJ4824 HEOI2013SAO/CQOI2017老C的键盘(树形dp)
    BZOJ4820 SDOI2017硬币游戏(概率期望+高斯消元+kmp)
    BZOJ4811 Ynoi2017由乃的OJ(树链剖分+线段树)
    BZOJ4810 Ynoi2017由乃的玉米田(莫队+bitset)
    Codeforces Round #522 Div. 1 没打记
    BZOJ4784 ZJOI2017仙人掌(树形dp+dfs树)
    43. Multiply Strings
    2. Add Two Numbers
    150. Evaluate Reverse Polish Notation
  • 原文地址:https://www.cnblogs.com/pp-pping/p/12221121.html
Copyright © 2020-2023  润新知