美文网首页Flutter
Flutter-实现列表下拉刷新和上拉加载

Flutter-实现列表下拉刷新和上拉加载

作者: StevenHu_Sir | 来源:发表于2019-08-19 09:29 被阅读0次

简介

下拉刷新
RefreshIndicator 下拉刷新的widget

上拉加载更多
①借助ScrollViewController监听列表滚动的位置,来实现加载更多的功能
②通过NotificationListeneronNotification回调监听列表滚动的位置,来实现加载更多的功能

刷新功能

import 'package:flutter/material.dart';

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

class _HomePageState extends State<HomePage> {
  List<String> _cityNames = [
    '北京',
    '郑州',
    '上海',
    '杭州',
    '北京',
    '上海',
    '泰康',
    '成都',
    '武汉'
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('下拉刷新和上拉加载更多功能'),
      ),
      body: RefreshIndicator(
        child: ListView(
          children: _buildList(),
        ),
        onRefresh: _handleRefresh,
      ),
    );
  }

  Future<Null> _handleRefresh() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      _cityNames = _cityNames.reversed.toList();
    });
    return null;
  }

  List<Widget> _buildList() {
    return _cityNames.map((city) => _item(city)).toList();
  }

  Widget _item(String city) {
    return Container(
      height: 80,
      margin: EdgeInsets.only(bottom: 5),
      alignment: Alignment.center,
      decoration: BoxDecoration(color: Colors.teal),
      child: Text(
        city,
        style: TextStyle(color: Colors.white, fontSize: 20),
      ),
    );
  }
}

刷新+加载更多功能

方案一:通过NotificationListeneronNotification回调监听

import 'dart:math';
import 'package:flutter/material.dart';

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

class _HomePageState extends State<HomePage> {
  List<String> _cityNames = [
    '北京',
    '郑州',
    '上海',
    '杭州',
    '北京',
    '上海',
    '成都',
  ];
  getRandomColor() {
    return Color.fromARGB(
        255,
        Random.secure().nextInt(255),
        Random.secure().nextInt(255),
        Random.secure().nextInt(255));
  }
  _loadData() async {
    await Future.delayed(Duration(milliseconds: 200));
    setState(() {
      List<String> list = List<String>.from(_cityNames);
      list.addAll(_cityNames);
      _cityNames = list;
    });
  }
  bool onNotification(Notification notification) {
    if (notification is! ScrollNotification) {
      // 如果不是滚动事件,直接返回
      return false;
    }
    ScrollNotification scroll = notification as ScrollNotification;
    // 当前滑动距离
    double currentExtent = scroll.metrics.pixels;
    double maxExtent = scroll.metrics.maxScrollExtent;
    if (currentExtent == maxExtent) {
    //加载更多操作
      _loadData();
    }
    // 返回false,继续向上传递,返回true则不再向上传递
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('下拉刷新和上拉加载更多功能'),
      ),
      body: new NotificationListener(
        onNotification: onNotification,
        child: RefreshIndicator(
          child: ListView(
            physics: const AlwaysScrollableScrollPhysics(),
            children: _buildList(),
          ),
          onRefresh: _handleRefresh,
        ),
      ),
    );
  }

  Future<Null> _handleRefresh() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      _cityNames = _cityNames.reversed.toList();
    });
    return null;
  }

  List<Widget> _buildList() {
    return _cityNames.map((city) => _item(city)).toList();
  }

  Widget _item(String city) {
    return Container(
      height: 80,
      margin: EdgeInsets.only(bottom: 5),
      alignment: Alignment.center,
      decoration: BoxDecoration(color: getRandomColor()),
      child: Text(
        city,
        style: TextStyle(color: Colors.white, fontSize: 20),
      ),
    );
  }
}

方案二、借助ScrollViewController监听列表滚动的位置

import 'dart:math';
import 'package:flutter/material.dart';

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

class _HomePageState extends State<HomePage> {
  List<String> _cityNames = [
    '北京',
    '郑州',
    '上海',
    '杭州',
    '北京',
    '上海',
    '成都',
  ];

  ScrollController _scrollController = new ScrollController();

  getRandomColor() {
    return Color.fromARGB(255, Random.secure().nextInt(255),
        Random.secure().nextInt(255), Random.secure().nextInt(255));
  }

  @override
  void dispose() {
    // TODO: implement dispose
    //为了避免内存泄露,需要调用_controller.dispose
    _scrollController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    // TODO: implement initState
    //监听滚动事件,打印滚动位置
    _scrollController.addListener(() {
      //maxScrollExtent 最大可滚动位置,到底部
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData();
      }
    });
  }

  _loadData() async {
    await Future.delayed(Duration(milliseconds: 200));
    setState(() {
      List<String> list = List<String>.from(_cityNames);
      list.addAll(_cityNames);
      _cityNames = list;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('下拉刷新和上拉加载更多功能'),
      ),
      body: RefreshIndicator(
        child: ListView(
          controller: _scrollController,
          physics: const AlwaysScrollableScrollPhysics(),
          children: _buildList(),
        ),
        onRefresh: _handleRefresh,
      ),
    );
  }

  Future<Null> _handleRefresh() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      _cityNames = _cityNames.reversed.toList();
    });
    return null;
  }

  List<Widget> _buildList() {
    return _cityNames.map((city) => _item(city)).toList();
  }

  Widget _item(String city) {
    return Container(
      height: 80,
      margin: EdgeInsets.only(bottom: 5),
      alignment: Alignment.center,
      decoration: BoxDecoration(color: getRandomColor()),
      child: Text(
        city,
        style: TextStyle(color: Colors.white, fontSize: 20),
      ),
    );
  }
}

效果图

下拉刷新和上拉加载更多.gif

补充

1.通过setState方式加载更多

int page = 1; //当前页数
List<Map> hotGoodsList = []; //火爆专区的商品列表数据

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getHotGoods();
  }
  //火爆商品接口
  void _getHotGoods() {
    var formPage = {'page': page};
    request('homePageBelowConten', formData: formPage).then((val) {
      var data = json.decode(val.toString());
      List<Map> newGoodsList = (data['data'] as List).cast();
      setState(() {
        hotGoodsList.addAll(newGoodsList);
        page++;
      });
    });
  }

相关文章

网友评论

    本文标题:Flutter-实现列表下拉刷新和上拉加载

    本文链接:https://www.haomeiwen.com/subject/vovjsctx.html