20-flutter下拉刷新与上拉加载

1 RefreshIndicator 下拉刷新控件

下拉刷新的时候会回调 onRefresh 方法

RefreshIndicator(
    onRefresh: _handleRefresh,
    child: ListView(
        children: _buildList(),
    ),
),

2 上拉加载多

上拉加载更多的时候

@override 
    void initState() { 
      super.initState();
      _scrollController.addListener((){
          // 如果滑动到最大的可滚动位置
          if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent){
            // 加载更多数据
            _loadData();
          }
      });
    }
 
import 'dart:core';

import 'package:flutter/material.dart';

List city_names =  ["北京","上海","广州","深圳","南京","郑州","武汉","长江","黄河","哈尔滨","成都","重庆"];



void main() => runApp(MyApp());
  
class MyApp extends StatefulWidget {
  
  @override
  _MyAppState  createState() => _MyAppState();

}


class _MyAppState extends State
{ 

    // 监听上拉刷新 设置一个控制器
    ScrollController _scrollController = ScrollController();

    @override 
    void initState() { 
      super.initState();
      _scrollController.addListener((){
          // 如果滑动到最大的可滚动位置
          if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent){
            // 加载更多数据
            _loadData();
          }
      });
    }

    // 加载更多数据
    _loadData() async{
        await Future.delayed(Duration(seconds: 2));
        setState(() {
            List list = List.from(city_names);
            list.addAll(city_names);
            city_names = list;
        });
    }

    // 销毁
    void dispose(){
      _scrollController.dispose();
      super.dispose();      
    }

    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(fontSize: 30,color: Colors.white)),
        );
      }

    List _buildList(){
        return city_names.map((city) => _item(city)).toList();    
    }

    Future _handleRefresh() async {
      await Future.delayed(Duration(seconds: 2));
      setState(() {
          city_names = city_names.reversed.toList();
      });

      return null;
    }

    @override     
    Widget build(BuildContext context) {
      return MaterialApp(
        title: "刷新加载",
        home: Scaffold(
          appBar: AppBar(
          title: Text("下拉刷线"),
        ),
        body:RefreshIndicator(          
          onRefresh: _handleRefresh,
          child: ListView(
            // 设置一个监听控制器
            controller: _scrollController,
            children: _buildList(),
          ),
        ),
        )
      );
    }
  
}

20-flutter下拉刷新与上拉加载_第1张图片

你可能感兴趣的:(flutter基础,Flutter,基础)