Flutter发起http请求

1. 构建Http通用发起请求类

import 'dart:async';
import 'dart:convert' as Convert;
import 'dart:io';
import 'package:http/http.dart' as http;

typedef RequestCallBack = void Function(Map data);

class HttpRequest {
  final baseUrl;

  HttpRequest(this.baseUrl);

  Future get(String uri, {Map headers}) async {
    try {
      http.Response response = await http.get(baseUrl + uri, headers: headers);
      final statusCode = response.statusCode;
      final body = response.body;
      // print('[uri=$uri][statusCode=$statusCode][response=$body]');
      var result = Convert.jsonDecode(body);
      return result;
    } on Exception catch (e) {
      print('[uri=$uri]exception e=${e.toString()}');
      return '';
    }
  }

  Future getResponseBody(String uri, {Map headers}) async {
    try {
      http.Response response = await http.get(baseUrl + uri, headers: headers);
      final statusCode = response.statusCode;
      final body = response.body;
//      var result = Convert.jsonDecode(body);
      print('[uri=$uri][statusCode=$statusCode][response=$body]');
      return body;
    } on Exception catch (e) {
      print('[uri=$uri]exception e=${e.toString()}');
      return null;
    }
  }

  Future post(String uri, dynamic body, {Map headers}) async {
    try {
      http.Response response = await http.post(baseUrl + uri, body: body, headers: headers);
      final statusCode = response.statusCode;
      final responseBody = response.body;
      var result = Convert.jsonDecode(responseBody);
      print('[uri=$uri][statusCode=$statusCode][response=$responseBody]');
      return result;
    } on Exception catch (e) {
      print('[uri=$uri]exception e=${e.toString()}');
      return '';
    }
  }
}


欢迎加群讨论更多flutter相关问题(7天有效)如果失效,可加个人微信拉群

2. 发起请求加入loading框并渲染列表

import 'package:flutter/material.dart';
import 'package:flutter_app_demo/http_request.dart';
// 入口函数
void main() => runApp(MyApp());

// 入口widget
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    /* 
     * Material应用程序以MaterialApp widget开始 
     * 该widget在应用程序的根部创建了一些有用的widget,
     * 比如一个Theme配置了应用的主题,home配置初始页面
     * */
    return new MaterialApp(
      title:"应用程序标题",
      home:Application()
    );
  } 
}

class Application extends StatefulWidget {
  @override
  _ApplicationState createState() => _ApplicationState();
}

class _ApplicationState extends State {
  int _currentIndex = 0;
  List _bodyList = [
    HomePage(),
    MediaPage(),
    MinePage()
  ];
  List _bottomNavBarItemList = [
    BottomNavigationBarItem(
      icon:Image.asset(
        'assets/images/ic_tab_home_normal.png',
        width:30.0,
        height:30.0
      ),
      title:Text(
        "首页"
      ),
      activeIcon: Image.asset(
        'assets/images/ic_tab_home_active.png',
        width:30.0,
        height:30.0
      ),
    ),
    BottomNavigationBarItem(
       icon:Image.asset(
        'assets/images/ic_tab_subject_normal.png',
        width:30.0,
        height:30.0
      ),
      title:Text(
        "媒体"
      ),
      activeIcon: Image.asset(
        'assets/images/ic_tab_subject_active.png',
        width:30.0,
        height:30.0
      ),
    ),
     BottomNavigationBarItem(
       icon:Image.asset(
        'assets/images/ic_tab_profile_normal.png',
        width:30.0,
        height:30.0
      ),
      title:Text(
        "我的"
      ),
      activeIcon: Image.asset(
        'assets/images/ic_tab_profile_active.png',
        width:30.0,
        height:30.0
      ),
    ),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:this._bottomNavBarItemList[this._currentIndex].title
      ),
      body:this._bodyList[this._currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        items: this._bottomNavBarItemList,
        currentIndex: this._currentIndex,
        onTap:(int index){
          setState((){
            this._currentIndex = index;
          });
        },
        type:BottomNavigationBarType.fixed,
        fixedColor:Colors.green
      ),
    );
  }
}

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

class _HomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Container(
      child:FutureBuilder(
        builder:_buildFuture,
        future:this._getCityList("/adminApi/menu/account_group/1")
      )
    );
  }
  Future _getCityList(String url) async {
    final Map result = await HttpRequest("http://api.91vue.com:8081/shsApi").get(url,headers:{
        "Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiYWRtaW4iLCJfaWQiOjEsImlhdCI6MTU2MTU0MzgwNCwiZXhwIjoxNTYxNTQ3NDA0fQ.023ri_Ka8zeMo29GOXTovJ4xCiV5UP5zg5w1Sli0M84"
      });
    return result;
  }
}

// 媒体页面
class MediaPage extends StatefulWidget {
  @override
  _MediaPageState createState() => _MediaPageState();
}

class _MediaPageState extends State {
  @override
  Widget build(BuildContext context) {
    return Container(
      child:Center(child: Text("媒体页面"),)
    );
  }
}

// 我的页面
class MinePage extends StatefulWidget {
  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Container(
      child:Center(child: Text("我的页面"),)
    );
  }
}

///snapshot就是_calculation在时间轴上执行过程的状态快照
Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
  switch (snapshot.connectionState) {
    case ConnectionState.none:
      print('还没有开始网络请求');
      return Text('还没有开始网络请求');
    case ConnectionState.active:
      print('active');
      return Text('ConnectionState.active');
    case ConnectionState.waiting:
      print('waiting');
      return Center(
        child: CircularProgressIndicator(),
      );
    case ConnectionState.done:
      print('done');
      if (snapshot.hasError) return Text('Error: ${snapshot.error}');
      return _createListView(context, snapshot);
    default:
      return Text('还没有开始网络请求');
  }
}
 Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
   List list = snapshot.data['data'];
   return ListView.builder(
     itemBuilder: (context, index) => _itemBuilder(context, index, list),
     itemCount: list.length*2,
   );
 }

 Widget _itemBuilder(BuildContext context, int index, list) {
   if (index.isOdd) {
     return Divider();
   }
   index = index ~/ 2;
   return ListTile(
     title: Text(list[index]['name']??"N/A"),
     leading: Text(list[index]['id'].toString()),
     trailing: Text(list[index]['route']??"N/A"),
   );
 }

 

你可能感兴趣的:(flutter)