首页 > 建站教程 > APP开发,混合APP >  Flutter实现上拉加载下拉刷新正文

Flutter实现上拉加载下拉刷新

Flutter通过ListView的controller属性配合ScrollController实现上拉加载,通过RefreshIndicator的onRefresh方法,实现下拉刷新。下面的代码通过:
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

List<String> cityNames = [
  '北京',
  '上海',
  '广东',
  '深圳',
  '南京',
  '合肥',
  '武汉',
  '拉萨',
  '天津',
  '沈阳'
];

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

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

class _MyAppState extends State<MyApp> {
  ScrollController _scrollController = ScrollController();
  final title = "高级功能列表下拉刷新与上拉加载";

  @override
  void initState() {
    //监听滚动,当滚动距离等于最大滚动距离,即触发上拉加载方法
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: RefreshIndicator(
            child: ListView(
              controller: _scrollController,
              children: _buildList(),
            ),
            onRefresh: _handleRefresh),
      ),
    );
  }

  //加载数据方法,用延迟来模拟请求数据
  _loadData() async {
    await Future.delayed(Duration(milliseconds: 200));
    setState(() {
      //复制数组
      List<String> list = List<String>.from(cityNames);
      list.addAll(cityNames);
      cityNames = list;
    });
  }

  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(city) {
    return Container(
      height: 80,
      margin: EdgeInsets.only(bottom: 5),
      alignment: Alignment.center,
      decoration: BoxDecoration(color: Colors.amber),
      child: Text(
        city,
        style: TextStyle(color: Colors.white, fontSize: 20),
      ),
    );
  }
}