Flutter中下拉刷新功能的实现

目录

前言

一、RefreshIndicator文档

二、简单的用法


前言

    最近研究Flutter源码的时候,发现Flutter中有一个refresh控件可以用来实现下拉刷新

效果。我们知道Flutter实现了两种风格的脚手架,一种是iOS风格的,一种是material风格的。刷新组件也一样,Flutter中Materi风格的widget名称叫做RefreshIndicator,iOS风格的widget名称叫做CupertinoSliverRefreshControl。官方文档也提供了两个例子:

 

 图1.RefreshIndicator效果图1                            图2.RefreshIndicator效果图1

  iOS风格的效果图如下图:

        

         图3.CupertinoSliverRefreshControl实现下拉刷新效果

        这里我使用的Flutter的版本号是3.7.7.

一、RefreshIndicator文档

        看下RefreshIndicator定义:

        

const RefreshIndicator({
  super.key,
  required this.child,
  this.displacement = 40.0,
  this.edgeOffset = 0.0,
  required this.onRefresh,
  this.color,
  this.backgroundColor,
  this.notificationPredicate = defaultScrollNotificationPredicate,
  this.semanticsLabel,
  this.semanticsValue,
  this.strokeWidth = RefreshProgressIndicator.defaultStrokeWidth,
  this.triggerMode = RefreshIndicatorTriggerMode.onEdge,
}) : assert(child != null),
     assert(onRefresh != null),
     assert(notificationPredicate != null),
     assert(strokeWidth != null),
     assert(triggerMode != null);       

        RefreshIndicator有两个必选方法:child和onRefresh。

        child表示子widget,onRefresh是下拉刷新完成之后的回调。

二、简单的用法

代码如下(示例):

        例如我们要实现一个下拉刷新的列表,刷新之后,改变背景颜色。

         实现起来也是非常的简单:把要加载的ListView设置成RefreshIndicator的child,然后在onRefresh的回调方法中实现数据源的刷新。

        

import 'dart:math' as math;

import 'package:flutter/material.dart';

class RefreshIndicatorDemoPage extends StatefulWidget {
  const RefreshIndicatorDemoPage({Key? key}) : super(key: key);

  @override
  State<RefreshIndicatorDemoPage> createState() => _RefreshIndicatorExampleState();
}

class _RefreshIndicatorExampleState extends State<RefreshIndicatorDemoPage> {
  final keyRefresh = GlobalKey<RefreshIndicatorState>();


  List<Widget> list = [];
  Color getRandomColor({int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : math.Random.secure().nextInt(r),
      g != 255 ? g : math.Random.secure().nextInt(g),
      b != 255 ? b : math.Random.secure().nextInt(b),
    );
  }

  Future generateWidgetList() async{
    // keyRefresh.currentState?.show();
    Future.delayed(const Duration(seconds: 1)).then((value){
      setState(() {
        list = List.generate(10, (index) => Container(
          margin: const EdgeInsets.all(20),
          decoration:  BoxDecoration(
              color: getRandomColor(),
              borderRadius: const BorderRadius.all(Radius.circular(10))
          ),
          height: 50,
          child: Center(child: Text('$index',style: TextStyle(fontSize: 12,color: getRandomColor()),)),
        ));
      });
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('RefreshIndicator',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 12),),
        actions: [
          ElevatedButton(onPressed: () {
            generateWidgetList();
          },child: const Icon(Icons.refresh),),
        ],
      ),
      body: RefreshIndicator(
        // key: keyRefresh,
        onRefresh: () async{
          generateWidgetList();
        },
        child: ListView.builder(itemBuilder: (BuildContext context, int index) {
          return list[index];
        },itemCount: list.length,),
      ),
    );
  }
}

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Flutter提供了一个名为RefreshIndicator的控件,可以用来实现下拉刷新功能。 使用RefreshIndicator很简单,大致步骤如下: 1.将需要下拉刷新的控件放在一个可滚动的容器,如ListView、GridView等。 2.在可滚动容器外层包裹一个RefreshIndicator控件。 3.在RefreshIndicator的onRefresh回调方法实现下拉刷新的逻辑。 下面是一个简单的示例代码,演示了如何使用RefreshIndicator来实现下拉刷新功能: ``` import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<String> _items = List.generate(20, (i) => "Item ${i + 1}"); Future<void> _refresh() async { // 模拟网络请求 await Future.delayed(Duration(seconds: 2)); setState(() { _items = List.generate(20, (i) => "Refreshed Item ${i + 1}"); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: RefreshIndicator( onRefresh: _refresh, child: ListView.builder( itemCount: _items.length, itemBuilder: (context, index) { return ListTile( title: Text(_items[index]), ); }, ), ), ); } } ``` 在上面的代码,ListView.builder是一个可滚动容器,RefreshIndicator是一个包裹在外面的控件,onRefresh回调方法模拟了一个网络请求,请求完成后重新生成了一组新的数据并更新界面。 需要注意的是,在下拉刷新的过程,用户可以看到一个圆形的进度条,这个进度条是系统自带的,无法自定义样式。如果需要自定义样式,可以使用第三方库,如flutter_easyrefresh、pull_to_refresh等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我叫柱子哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值