Flutter之get/post网络请求数据并渲染页面

1、Flutter Json与Map类型转换

import 'dart:convetr'

json.encode();//Map转Json
json.decode();//Json转Map

2、Utf8解决乱码

Utf8Decoder decode = new Utf8Decoder();
decode.convert(response.bodyBytes)

3、Http组件

http: ^0.12.0+4

4、Http之get、post请求数据渲染页面完整demo

get请求我们使用的ListView组件,post请求使用了ListView.builder 两者效果一样。

  import 'dart:convert';

  import 'package:flutter/material.dart';
  import 'package:http/http.dart' as http;

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

    @override
    _RequestPageState createState() => _RequestPageState();
  }

  class _RequestPageState extends State<RequestPage> {
    List getList = [];
    List postList = [];
    String name;
    String password;
    String login="登录";

    _getData() async {
      var response = await http.get("https://api.apiopen.top/videoHomeTab");
      if (response.statusCode == 200) {
        Map map = json.decode(response.body);
        List listJsonMap = map['result'];
        setState(() {
          getList = listJsonMap;
        });
      } else {
        getList = ['code', 500];
      }
    }

    _postData() async {
      var response = await http.post("https://api.apiopen.top/videoHomeTab");
      if (response.statusCode == 200) {
        Map map = json.decode(response.body);
        List listJsonMap = map['result'];
        setState(() {
          postList = listJsonMap;
        });
      } else {
        getList = ['code', 500];
      }
    }

    _login() async {
      var response = await http.post("http://localhost:8080/user/login", body: {"userName": name, "password": password});
      Utf8Decoder decode = new Utf8Decoder();
      if (response.statusCode == 200) {
        Map map = json.decode(decode.convert(response.bodyBytes));
        print(map);
        String code = map['code'];
        if(code=="E19999"){
          setState(() {
            login=map['msg'];
          });
        }else{
          setState(() {
            login="登录成功";
          });
        }

      } else {
        setState(() {
          login = "网络错误";
        });
      }
    }
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text("网络请求"),
        ),
        body: Container(
          child: Column(
            children: <Widget>[
              RaisedButton(
                child: Text("get请求数据"),
                onPressed: () {
                  _getData();
                },
              ),
              RaisedButton(
                child: Text("post请求数据"),
                onPressed: () {
                  _postData();
                },
              ),
              Text("get请求的数据"),
              Container(
                 child: getList.length>0?ListView(children:getList.map((e){return ListTile(title: Text(e['name']),subtitle: Text(e['apiUrl']),);}).toList(),):Text(""),
                height: 200,
              ),
              Divider(),
              Text("post请求的数据"),
              Container(
                child: postList.length>0?ListView.builder(itemBuilder: (context,index){
                  return ListTile(title: Text(postList[index]['name']),subtitle: Text(postList[index]['apiUrl']),);
                },itemCount: postList.length,):Text(""),
                height: 200,
              ),
              TextField(
                decoration: InputDecoration(hintText: "请输入用户名"),
                onChanged: (String userName) {
                  setState(() {
                    name = userName;
                  });
                },
              ),
              TextField(
                decoration: InputDecoration(hintText: "请输入密码"),
                obscureText: true,
                onChanged: (String passWord) {
                  setState(() {
                    password = passWord;
                  });
                },
              ),
              FlatButton(
                child: Text(login),
                onPressed: () => _login(),
              ),
            ],
          ),
        ),
      );
    }
  }

上边包括了一个get和post请求页面数据以及post请求登录的接口。post请求登录接口是我本地的springboot项目,代码在这github

 后端部分代码

package com.main.flutter.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author MrWang
 * @version v1.0
 * @date 2020/3/16
 * @Description
 */

@RestController
@RequestMapping("/user")
public class LoginController {

    @RequestMapping("/login")
    public Map<String,Object> login(String userName,String password){
        Map<String,Object> returnData = new HashMap<>(8);
        if (userName==null||password==null){
            returnData.put("code","E19999");
            returnData.put("msg","用户名或密码不能为空");
        }else if (!"admin".equals(userName)||!"admin".equals(password)){
            returnData.put("code","E19999");
            returnData.put("msg","用户名或密码错误");
        }else {
            returnData.put("code","S10000");
            returnData.put("msg","登录成功");
        }
        return returnData;
    }
}

5、更强大的Dio网络请求组件

简介:dio是一个强大的Dart Http请求库,支持Restful API FromData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等。

组件地址:https://pub.flutter-io.cn/packages/dio

使用起来和http类似,不过比http更加强大,这里不再过多介绍,demo示例移步点这里

猜你喜欢

转载自blog.csdn.net/u013600907/article/details/104896974