Flutter ,json格式处理, get post提交数据和第三方 Dio库实现网络请求

json格式处理

引入内置库

import 'dart:convert';

map和json类型转换

List<Map> videoInfo=[
     {
        "video_id":"aaa111",
        "name":"vue精选视频",
        "coverSrc":"https://www.baidu.com/img1"
      },
      {
        "video_id":"aaa112",
        "name":"python精选视频",
        "coverSrc":"https://www.baidu.com/img2"
      },
   ];
var a=json.encode(videoInfo);//map转为json字符串
var b=json.decode(a)//json字符串转为map
print(a is String);//true
print(b[0] is Map);//true

RESTful
安装http官方库
库地址

http: ^0.12.0+4

get获取数据

Widget build(BuildContext context) {
    return Container(
      child: RaisedButton(onPressed: () async{
        var url = 'http://192.168.1.14:8787/getUri';
        var result = await http.get(url);
        if (result.statusCode == 200) {//请求成功
            var jsonResponse = json.decode(result.body);
            print(jsonResponse);
        } else {//请求失败
          print('Request failed with status: ${result.statusCode}.');
        }
      },child: new Text('get请求数据'),),
    );
 }

post提交数据

RaisedButton(
        onPressed: () async {
          var url = 'http://192.168.1.14:8787/postUri';
          var body = {"name": "123", "age": '18'};
          var result = await http.post(url, body: body); 
          if (result.statusCode == 200) {
            //请求成功
            var jsonResponse = json.decode(result.body);
            print(jsonResponse);
          } else {
            //请求失败
            print('Request failed with status: ${result.statusCode}.');
          }
        },
        child: new Text('post提交数据'),
      )

Dio

下载第三方Dio库
官方介绍
dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等…
中文地址

dio: ^3.0.9 

引入方式

import 'package:dio/dio.dart';
 Widget build(BuildContext context) {
    return Column(children: <Widget>[
      RaisedButton(
        onPressed: () async {
          Response response = await Dio().post(
            'http://192.168.1.14:8787/postUri',
            data: {
              "name":"小明",
              "age":"18"
            }
          );
          print(response.data);
        },
        child: new Text('dio'),
      ),
    ]);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值