Flutter Dio库实现网络请求 get post put delete

发布于 1周前 作者 phonegap100 来自 分享

Flutter Dio库简介:

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

https://pub.dev/packages/dio

https://github.com/flutterchina/dio/blob/master/README-ZH.md

Flutter Dio库的使用:

1、添加依赖

dependencies:
  dio: ^2.1.x  // 请使用pub上2.1分支的最新版本

2 引入库使用

import 'package:dio/dio.dart';
void getHttp() async {
  try {
    Response response = await Dio().get("http://www.baidu.com");
    print(response);
  } catch (e) {
    print(e);
  }
}

完整demo


import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:dio/dio.dart';

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

  _HttpDemoState createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {
  
  List _list=[];

  @override
  void initState() { 
    super.initState();
    this._getData();
  }

  _getData() async{
    var apiUrl="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
    Response result=await Dio().get(apiUrl);

    // print(json.decode(result.data)["result"]);
    setState(() {
     this._list=json.decode(result.data)["result"]; 
    });

    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("请求数据Dio Demo"),
      ),
      body: this._list.length>0?ListView(
        children: this._list.map((value){
          return ListTile(
            title: Text(value["title"]),
          );
        }).toList(),
      ):Text("加载中...")
    );
  }
}
回到顶部