一、添加依赖pubspec.yaml
dependencies: dio: ^3.0.9
二、dio封装
2.1、创建http_service.dart文件(/lib/service/http_conf.dart),用于dio请求封装
import 'package:dio/dio.dart'; import 'dart:async'; import 'dart:io'; import '../config/index.dart'; import '../config/http_conf.dart'; Future request(url,{formData})async{ try{ Response response; Dio dio = new Dio(); // dio.options.contentType = ContentType.parse('application/x-www-form-urlencoded'); if(formData == null){ response = await dio.post(servicePath[url]); }else{ response = await dio.post(servicePath[url],data:formData); } if(response.statusCode == 200){ return response; }else{ throw Exception('后端接口异常..'); } }catch(e){ return print('error:::${e}'); } }
2.2、创建index.dart文件(/lib/service/ index.dart)用于引入http_conf.dart配置
export 'http_conf.dart';
2.3、创建http_conf.dart文件(lib/config/ http_conf.dart)
const base_url="http://new.163.top/api/Index/"; //公共域名 const servicePath ={ 'gmovie':base_url + 'gmovie',//获取电影 };
三、使用方法:
定义一个方法请求数据request(请求方法,请求参数’)
void initState(){ super.initState(); _getvod(); } void _getvod(){ request('gmovie',formData: page).then((val){ var data = json.decode(val.toString()); List<Map> newvodList = (data['data'] as List).cast(); setState(() { vodList.addAll(newvodList); page++; }); }); }
四、demo以下以获取列表数据为例:
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../config/index.dart'; import '../service/http_service.dart'; import 'dart:convert'; import 'package:flutter_easyrefresh/easy_refresh.dart'; import 'detail_page.dart'; import 'package:date_format/date_format.dart'; class MoviePage extends StatefulWidget{ _MoviePageState createState() => _MoviePageState(); } class _MoviePageState extends State<MoviePage>{ //电影 int page=1; List<Map> vodList = []; //防止刷新处理 保持当前状态 @override bool get wantKeepAlive => true; GlobalKey<RefreshHeaderState> _headerKey = new GlobalKey<RefreshHeaderState>(); GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>(); @override void initState(){ super.initState(); _getvod(); } @override Widget build(BuildContext context){ // super.build(context); return Scaffold( backgroundColor: Color.fromRGBO(244, 245, 245, 1), appBar: AppBar( title: Text(KSting.movieTitle),), body: FutureBuilder( future: request('gmovie',formData: null), builder: (context,snapshot){ if(snapshot.hasData){ return EasyRefresh( refreshFooter: ClassicsFooter( key: _footerKey, bgColor: Colors.white, textColor: KColor.refreshTextColor, moreInfoColor: KColor.refreshTextColor, showMore: true, moreInfo: "${formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd,' ',HH, ':', nn,':', ss])}", //加载中 loadText: KSting.loadText, loadReadyText: KSting.loadReadyText, loadingText: KSting.loadingText, loadedText: KSting.loadedText, noMoreText: KSting.noMoreText, ), refreshHeader:ClassicsHeader( key: _headerKey, refreshText: KSting.loadText, refreshReadyText: KSting.refreshReadyText, refreshingText: KSting.refreshingText, refreshedText: KSting.refreshedText, moreInfo: "${formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd,' ',HH, ':', nn,':', ss])}", bgColor: Colors.white, textColor: KColor.refreshTextColor, moreInfoColor: KColor.refreshTextColor, showMore: true, ), child: ListView( children: <Widget>[ _vodBox(),//电影 ], ), loadMore: ()async{ _getvod(); }, onRefresh: _pullToRefresh, ); }else{ return Center( child: CircularProgressIndicator() ); // return Center( // child: Text('加载中'), // ); } }, ), ); } //获取电影数据 void _getvod(){ request('gmovie',formData: page).then((val){ var data = json.decode(val.toString()); List<Map> newvodList = (data['data'] as List).cast(); setState(() { vodList.addAll(newvodList); page++; }); }); } // 下拉刷新,必须异步async不然会报错 Future _pullToRefresh() async { print('正在刷新'); page = 1; vodList.clear(); _getvod(); return null; } //电影 Widget _warpvodList(){ List<Widget> listWiget =vodList.map((val){ return InkWell( onTap: (){ Navigator.of(context).push( MaterialPageRoute(builder: (context)=>DetailPage( eachVodId: val['id'], eachVodName: val['vod_name'], p:1 )) ); }, child: Container( width: ScreenUtil().setWidth(235), color: Colors.white, padding: EdgeInsets.only(bottom: 20.0,top: 15.0), child: Column( children: <Widget>[ Image.network( val['vod_pic'], width: ScreenUtil().setWidth(235), height: 150, fit: BoxFit.cover, ), Text( val['vod_name'], maxLines: 1, overflow: TextOverflow.ellipsis, style: Kfont.tvStyle, ), Text( val['vod_content'], maxLines: 1, overflow: TextOverflow.ellipsis, style: Kfont.mintvStyle ), ], ), ), ); }).toList(); return Wrap( spacing: 2, children: listWiget, ); } //电影组合 Widget _vodBox(){ return Container( child: Column( children: <Widget>[ _warpvodList() ], ), ); } }
文章评论(0)