Dart|Flutter之下拉刷新和上拉加载

一、下拉刷新
在Flutter中有一个RefreshIndicator,它是一个下拉刷新的widget,通过它我们可实现列表的下拉刷新的操作。

二、上拉加载
在Flutter中有一个ScrollController 列表支持设置controller参数,通过ScrollController监听列表滚动的位置,来实现加载更多的功能。

demo:

import 'package:flutter/material.dart'; void main() => runApp(MyApp()); List list = ['北京','上海','广州','深圳','杭州','苏州','成都','重庆','宁夏','银川']; int index = 0; class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() { return _MyAppState(); } }class _MyAppState extends State { ScrollController _scrollController = ScrollController(); @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 new MaterialApp( title: '下拉刷新', home: Scaffold( appBar: AppBar( title: Text("下拉刷新"), ), body: RefreshIndicator( child: ListView( controller: _scrollController, children: _buildList(), ), onRefresh: _refresh, ), ), ); }List _buildList(){ return list.map((city)=>_item(city)).toList(); } _loadData() async{ await Future.delayed(Duration(microseconds: 200)); setState(() { List newList = List.from(list); newList.addAll(list); list = newList; }); }Future _refresh() async{ await Future.delayed(Duration(seconds: 2)); setState(() { list.insert(0, "我是第${++index}下拉刷新加进来的"); }); return null; } Widget _item(String city){ return Container( height: 80, margin: EdgeInsets.only(bottom: 5), alignment: Alignment.center, decoration: BoxDecoration(color: Colors.blue), child: Text( city, style: TextStyle(color: Colors.white,fontSize: 20), ), ); } }


【Dart|Flutter之下拉刷新和上拉加载】

    推荐阅读