flutter中的网络请求和下拉刷新上拉加载,toast的案例

添加依赖

  pull_to_refresh: ^1.5.6
  dio: ^2.1.0
  fluttertoast: ^3.0.1

DioUtil

import ‘package:dio/dio.dart‘;

class DioUtil {

  static DioUtil _instance;
  final Dio _mDio =
      Dio(BaseOptions(baseUrl: "http://192.168.0.60:8080"));
  Dio get mDio => _mDio;
  DioUtil._();
  static DioUtil getInstance() {
    if (_instance == null) {
      _instance = DioUtil._();
      _instance._init();
    }
    return _instance;
  }

  _init() {}
}

Urls

  class Urls {
      static const String getUserUrl = ‘/user/getAllUserByPage‘;
  }

LogUtils

class LogUtils {
  static const bool isRelease = const bool.fromEnvironment("dart.vm.product");

  static void d(String tag, Object message) {
    if (!isRelease) _printLog(tag, ‘D -> ‘, message);
  }

  static void i(String tag, Object message) {
    _printLog(tag, ‘I -> ‘, message);
  }

  static void e(String tag, Object message, {Exception e}) {
    _printLog(tag, ‘E -> ‘, message);
  }

  static void _printLog(String tag, String level, Object message) {
    StringBuffer sb = new StringBuffer();
    sb..write(level)..write(tag ?? ‘‘)..write(‘: ‘)..write(message);
    print(sb.toString());
  }
}

BaseNetResponseModel

class BaseNetResponseModel<T> {
  final int code;

  final String msg;

  final T data;

  const BaseNetResponseModel(
      {this.code,
      this.msg,
      this.data,
  });
}

DataBean

class DataBean {
  String userid;
  String job;

DataBean.fromJson(Map<String, dynamic> json) {
    userid = json[‘userid‘];

    job = json[‘job‘];
  }
}

DataRepository

import ‘./databean.dart‘;
import ‘BaseNetResponseModel.dart‘;

abstract class DataRepository {
  Future< BaseNetResponseModel<List<DataBean>>> getUserAll(
      String pageIndex,String pageSize
      );
}

NetDataRepository

import ‘package:dio/dio.dart‘;
import ‘package:futuredemo/BaseNetResponseModel.dart‘;
import ‘package:futuredemo/DataRepository.dart‘;
import ‘package:futuredemo/DioUtil.dart‘;
import ‘package:futuredemo/databean.dart‘;
import ‘Apis.dart‘;

class NetDataRepository extends DataRepository {
  Dio _dio = DioUtil.getInstance().mDio;
  List<DataBean> companyCustomerList;
  int code;
  String msg;
  Map<String, dynamic> data;
  @override
  Future<BaseNetResponseModel<List<DataBean>>> getUserAll(
      String pageIndex, String pageSize) async {
    Response response = await _dio.get(
        Urls.getUserUrl + "?pageIndex=" + pageIndex + "&pageSize=" + pageSize);
    print(response.data);
    print(response.data[‘data‘]);
    List userslist = response.data[‘data‘]["users"] as List;
    code = response.data[‘code‘];
    msg = response.data[‘msg‘];
    companyCustomerList = userslist.map((customer) {
      return DataBean.fromJson(customer);
    }).toList();

    return BaseNetResponseModel<List<DataBean>>(
        code: code, msg: msg, data: companyCustomerList);
  }
}

ToastUtils

import ‘package:flutter/material.dart‘;
import ‘package:fluttertoast/fluttertoast.dart‘;

class ToastUtils {
  static ToastUtils _instance;

  ToastUtils._();

  static ToastUtils getInstance() {
    if (_instance == null) {
      _instance = ToastUtils._();
    }
    return _instance;
  }

  Future _cancelPreToast() async {
    await Fluttertoast.cancel();
  }

  static void toastShort(String message) {
    getInstance()._cancelPreToast();
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.grey,
        textColor: Colors.white,
        fontSize: 14.0);
  }

  static void toastLong(String message) {
    getInstance()._cancelPreToast();
    Fluttertoast.showToast(
        msg: message,
        toastLength: Toast.LENGTH_LONG,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.blue[300],
        textColor: Colors.white,
        fontSize: 14.0);
  }
}

PageError

import ‘package:flutter/material.dart‘;

class PageError extends StatelessWidget {
  final VoidCallback callback;

  const PageError({Key key, this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: MaterialButton(
          child: Text(‘重新加载‘, style: TextStyle(color: Theme.of(context).primaryColor),),
          onPressed: () {
            if (callback != null) callback();
          }),
    );
  }
}

PageLoading

import ‘package:flutter/cupertino.dart‘;
import ‘package:flutter/material.dart‘;

class PageLoading extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          CupertinoActivityIndicator(),
        ],
      ),
    );
  }
}

JobPage

import ‘package:flutter/cupertino.dart‘;
import ‘package:flutter/material.dart‘;
import ‘package:futuredemo/log_utils.dart‘;
import ‘package:futuredemo/toast_utils.dart‘;
import ‘./page_error.dart‘;
import ‘./page_loading.dart‘;
import ‘package:pull_to_refresh/pull_to_refresh.dart‘;
import ‘BaseNetResponseModel.dart‘;
import ‘NetDataRepository.dart‘;
import ‘databean.dart‘;

class JobPage extends StatefulWidget {
  @override
  _JobPageState createState() => _JobPageState();
}

class _JobPageState extends State<JobPage> {
  NetDataRepository _netDataRepository = NetDataRepository();

  Future<Map<String, dynamic>> _futureBuilderFuture;
  List<DataBean> dataList = List();

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  void initState() {
    super.initState();

    _futureBuilderFuture = _loadData();
  }

  void _onRefresh() async {
    BaseNetResponseModel<List<DataBean>> model =
        await _netDataRepository.getUserAll("1", "10");
    dataList.clear();
    dataList.addAll(model.data);
    // 日志打印
    LogUtils.d("tag", model.code);
    _refreshController.refreshCompleted();
    _refreshController.loadComplete();
    if (mounted) setState(() {});
  }

  void _onLoading() async {
    await Future.delayed(Duration(milliseconds: 1000));
    if (dataList.length < 30) {
      dataList.add(dataList[0]);
    } else {
      _refreshController.loadNoData();
      return;
    }

    if (mounted) setState(() {});

    _refreshController.loadComplete();
  }

  Future<Map<String, dynamic>> _loadData() async {
    BaseNetResponseModel<List<DataBean>> model =
        await _netDataRepository.getUserAll("1", "10");
    dataList.clear();
    dataList.addAll(model.data);
    return {"data": 0};
  }

  _refresh() async {
    setState(() {
      _futureBuilderFuture = _loadData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      appBar: AppBar(
        elevation: 0.0,
        title: Text(‘职业‘),
        centerTitle: true,
      ),
      floatingActionButton: FloatingActionButton(
          backgroundColor: Theme.of(context).primaryColor,
          child: Icon(
            Icons.add,
            size: 28,
            color: Colors.white,
          ),
          elevation: 4,
          onPressed: () {
            //吐司提示
            ToastUtils.toastShort("点击了");
          }),
      body: FutureBuilder(
        builder: (BuildContext context,
            AsyncSnapshot<Map<String, dynamic>> snapshot) {
          Widget widget;
          switch (snapshot.connectionState) {
            case ConnectionState.none:
              widget = Container();
              break;
            case ConnectionState.active:
            case ConnectionState.waiting:
              widget = PageLoading();
              break;
            case ConnectionState.done:
              if (snapshot.hasError) {
                widget = PageError(
                  callback: _refresh,
                );
              } else if (snapshot.hasData) {
                widget = _buildBody(context);
              }
              break;
          }
          return widget;
        },
        future: _futureBuilderFuture,
      ),
    );
  }

  Column _buildBody(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            header: WaterDropMaterialHeader(
                // backgroundColor:Color(OxFF00),
                ),
            footer: CustomFooter(
              builder: (BuildContext context, LoadStatus mode) {
                Widget body;
                if (mode == LoadStatus.idle) {
                  body = Row(children: <Widget>[
                    Expanded(
                      flex: 3,
                      child: Divider(
                        indent: 40,
                        height: 1,
                      ),
                    ),
                    Expanded(
                      flex: 2,
                      child: Container(
                        height: 40.0,
                        child: Center(
                            child: Text("上拉加载更多",
                                style: TextStyle(
                                    color: Colors.grey, fontSize: 13))),
                      ),
                    ),
                    Expanded(
                      flex: 3,
                      child: Divider(
                        height: 1,
                        endIndent: 40,
                      ),
                    )
                  ]);
                } else if (mode == LoadStatus.loading) {
                  body = CupertinoActivityIndicator();
                } else if (mode == LoadStatus.failed) {
                  body = Text("加载失败!",
                      style: TextStyle(color: Colors.grey, fontSize: 13));
                } else {
                  body = Row(children: <Widget>[
                    Expanded(
                      flex: 3,
                      child: Divider(
                        indent: 40,
                        height: 1,
                      ),
                    ),
                    Expanded(
                      flex: 2,
                      child: Container(
                        height: 40.0,
                        child: Center(
                            child: Text("已经到底啦",
                                style: TextStyle(
                                    color: Colors.grey, fontSize: 13))),
                      ),
                    ),
                    Expanded(
                      flex: 3,
                      child: Divider(
                        height: 1,
                        endIndent: 40,
                      ),
                    )
                  ]);
                }
                return Container(
                  height: 50.0,
                  child: Center(child: body),
                );
              },
            ),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: GridView.builder(
                padding: EdgeInsets.all(10.0),
                shrinkWrap: true,
                itemCount: dataList.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    //纵轴间距
                    mainAxisSpacing: 10.0,
                    //横轴间距
                    crossAxisSpacing: 10.0,
                    //子组件宽高长度比例
                    childAspectRatio: 1.5),
                itemBuilder: (context, index) {
                  // Map<String, dynamic> entry = dataList[index];
                  return UserItemWidget(
                    title: ‘${dataList[index].job}‘,
                    onTap: () {},
                  );
                }),
          ),
        ),
      ],
    );
  }
}

class UserItemWidget extends StatefulWidget {
  String title = "";

  int type = 1;
  VoidCallback onTap;

  UserItemWidget({
    Key key,
    this.title,
    this.onTap,
  }) : super(key: key);

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

class _UserItemWidgetState extends State<UserItemWidget> {
  VoidCallback _onTap;

  @override
  void initState() {
    super.initState();
    _onTap = widget.onTap;
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: _onTap,
      child: Stack(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(8),
            decoration: new BoxDecoration(
              color: Colors.white,
              border: new Border.all(width: 1.0, color: Colors.grey[300]),
              borderRadius: new BorderRadius.all(new Radius.circular(2)),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 15, bottom: 10, left: 10),
                  alignment: Alignment.centerLeft,
                  child: Text(widget.title == "" ? "未知" : widget.title,
                      style: TextStyle(fontSize: 18)),
                ),
              ],
            ),
          ),
          Positioned(
              top: 0,
              right: 0,
              child: Container(
                color: getTypeColor(widget.type),
                padding: EdgeInsets.all(5),
                child: Center(
                  child: Text(getTypeText(widget.type),
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 13.0,
                      )),
                ),
              ))
        ],
      ),
    );
  }

  String getTypeText(int type) {
    switch (type) {
      case 1:
        return "黄金职业";
      case 2:
        return "夕阳职业";
      case 3:
        return "朝阳职业";
    }
  }

  Color getTypeColor(int type) {
    switch (type) {
      case 1:
        return Color(0xFFFF00FF);
      case 2:
        return Color(0xFFC6C6C6);
      case 3:
        return Color(0xFF7FC3FD);
    }
  }
}

效果:

原文地址:https://www.cnblogs.com/loaderman/p/11532723.html

时间: 2024-11-03 11:32:56

flutter中的网络请求和下拉刷新上拉加载,toast的案例的相关文章

最新Android ListView 下拉刷新 上滑加载

开发项目过程中基本都会用到listView的下拉刷新和上滑加载更多,之前大家最常用的应该是pull to refresh或它的变种版吧,google官方在最新的android.support.v4包中增加了一个新类SwipeRefreshLayout,地址 这个类的作用就是提供官方的下拉刷新,并且效果相当不错,而上拉加载更多则用我们自定义的listview,也是相当简单. 下拉刷新 简单的介绍下: 首先它是一个viewgroup,但是它只允许有一个子控件,子控件能是任何view,使用的时候,所在

十分钟实现ListView下拉刷新上滑加载更多

说到ListView下拉刷新几乎每个APP都会用到,所以ListView下拉刷新是很重要的,就像ListView优化一样是你必会的东西. ListView实现下拉刷新如果我们开发人员自己编写相对来说比较费事的,当我们使用第三方库之后我们再来开发这个功能就会省事很多.相比与自己实现可以少编写不少代码,Android-PullToRefresh库可以轻松实现ListView的下拉刷新功能. 要使用Android—PullToRefesh库对ListView实现下拉刷新要经过以下几个步骤: 1.下载A

Android 下拉刷新上啦加载SmartRefreshLayout + RecyclerView

在弄android刷新的时候,可算是耗费了一番功夫,最后发觉有现成的控件,并且非常好用,这里记录一下. 原文是 https://blog.csdn.net/huangxin112/article/details/78781682 ,这里是看了之后,结合自己实际遇到的问题写的. 首先引入包. //下拉框 implementation 'com.android.support:recyclerview-v7:28.0.0-beta01' implementation 'com.scwang.smar

Android 下拉刷新上拉加载 多种应用场景 超级大放送(上)

转载请标明原文地址:http://blog.csdn.net/yalinfendou/article/details/47707017 关于Android下拉刷新上拉加载,网上的Demo太多太多了,这里不是介绍怎么去实现下拉刷新上拉加载,而是针对下拉刷新上拉加载常用的一些应用场景就行了一些总结,包含了下拉刷新上拉加载过程中遇到的一些手势冲突问题的解决方法(只能算是抛砖引玉). 去年9月的时候,那时自己正在独立做Android项目.记得刚刚写完那个ListView列表页面(木有下拉刷新,上拉加载)

vue10行代码实现上拉翻页加载更多数据,纯手写js实现下拉刷新上拉翻页不引用任何第三方插件

vue10行代码实现上拉翻页加载更多数据,纯手写js实现下拉刷新上拉翻页不引用任何第三方插件/库 一提到移动端的下拉刷新上拉翻页,你可能就会想到iScroll插件,没错iScroll是一个高性能,资源占用少,无依赖,多平台的javascript滚动插件.iScroll不仅仅是 滚动.它可以处理任何需要与用户进行移动交互的元素.在你的项目中包含仅仅4kb大小的iScroll,你的项目便拥有了滚动,缩放,平移,无限滚动,视差滚动,旋转功能.iScroll的强大毋庸置疑,本人也非常欢迎大家使用iScr

ListView的下拉刷新+上拉加载(已有demo)

1.XListView因为添加了Header,会导致存储的数据+1,所以赋值时需要position-1.补充:当去掉HeaderView时,position不用-1. 2.提个建议:上拉加载更多,最好在onCreate()中就执行setAdapter,然后不论是空数据.还是有数据,只用更新适配器就行了. 一.XListView 2.用法 导入图中的me.maxwin.view包 提供了两个接口: IXListViewListener:触发下拉刷新,上拉加载更多.实现此接口时,onLoadMore

Android 下拉刷新上拉载入 多种应用场景 超级大放送(上)

转载请标明原文地址:http://blog.csdn.net/yalinfendou/article/details/47707017 关于Android下拉刷新上拉载入,网上的Demo太多太多了,这里不是介绍怎么去实现下拉刷新上拉载入,而是针对下拉刷新上拉载入经常使用的一些应用场景即可了一些总结,包括了下拉刷新上拉载入过程中遇到的一些手势冲突问题的解决方法(仅仅能算是抛砖引玉). 去年9月的时候.那时自己正在独立做Android项目. 记得刚刚写完那个ListView列表页面(木有下拉刷新,上

IOS学习之UiTableView下拉刷新与自动加载更多,百年不变的效果

IOS学习之UiTableView下拉刷新与自动加载更多,百年不变的效果(五) 五一劳动节马上来临,小伙伴有妹有很激动哟,首先祝天下所有的程序猿节日快乐!这个五一对于我来说有点不一样,我的人生从这个五一就转弯了,爱情长跑8年的我结婚了,一会支付宝账号我会公布出去,请自觉打款!谢谢合作. 灯光闪起来: 舞蹈跳起来: 歌曲唱起来: -------------------------------------------------------------------------------------

ListView的下拉刷新上拉加载以及带列的横向滚动

相信有很人做的项目估计都用的到这个.就是ListView的下拉刷新上拉加载还有就是列的横向滚动; PS:横向滚动带表头与固定列(相信蛮多人都有这样的需求吧?就是在ListView上支持很多列,然而设备屏幕宽度有限) PS:这是我个人在网上找的两个示例demo结合而成的一个示例demo,还可以继续拓展,后续有时间就会更新,大家互相学习 ListView下拉刷新上拉加载示例demo原文出处: http://blog.csdn.net/limb99/article/details/18901513 L