You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter+Riverpod:如何自动化GET请求并实现徽章后台更新?

问题解答

一、实现徽章无需进入页面自动更新

可以实现。核心是让管理请求数据的Provider主动、定时刷新数据源,从而驱动徽章数值自动更新,无需依赖进入页面的操作。

具体实现方案

  1. 重构Provider为可自动刷新的异步状态管理类
    你当前的pendingLeaveProvider是FutureProvider,仅会在首次监听或手动刷新时执行请求。改用AsyncNotifierProvider结合定时器,就能实现定期自动拉取最新数据:

    import 'dart:async';
    import 'package:flutter_riverpod/flutter_riverpod.dart';
    
    class PendingLeaveNotifier extends AsyncNotifier<List<LeaveApproval>> {
      Timer? _refreshTimer;
    
      @override
      Future<List<LeaveApproval>> build() async {
        // 初始化时启动定时刷新,示例为每30秒请求一次
        _startAutoRefresh();
        return _fetchPendingLeaves();
      }
    
      // 封装GET请求逻辑
      Future<List<LeaveApproval>> _fetchPendingLeaves() async {
        final approvalLeave = ApprovalLeave();
        return approvalLeave.pendingLeave();
      }
    
      // 启动定时刷新任务
      void _startAutoRefresh() {
        _refreshTimer?.cancel();
        _refreshTimer = Timer.periodic(const Duration(seconds: 30), (_) async {
          state = const AsyncLoading();
          state = await AsyncValue.guard(_fetchPendingLeaves);
        });
      }
    
      // 销毁时清理定时器
      @override
      void dispose() {
        _refreshTimer?.cancel();
        super.dispose();
      }
    }
    
    // 声明最终的Provider
    final pendingLeaveProvider = AsyncNotifierProvider<PendingLeaveNotifier, List<LeaveApproval>>(
      PendingLeaveNotifier.new,
    );
    
  2. 更新徽章组件的状态监听
    直接监听重构后的pendingLeaveProvider,处理加载、错误、成功三种状态,确保徽章数值实时同步:

    Widget _buildTopBar(String greetingMessage) {
      return Consumer(builder: (context, ref, _) {
        final leaveApprovalsAsync = ref.watch(pendingLeaveProvider);
    
        return Container(
          padding: const EdgeInsets.all(10),
          decoration: const BoxDecoration(color: Colors.green),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 30),
              Padding(
                padding: const EdgeInsets.fromLTRB(30, 20, 0, 10),
                child: GestureDetector(
                  onTap: () => Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => const LeaveApprovalOP()),
                  ),
                  child: leaveApprovalsAsync.when(
                    loading: () => const Badge(
                      label: Text("0"),
                      child: Icon(CupertinoIcons.bell_solid, color: Colors.white),
                    ),
                    error: (_, __) => const Badge(
                      label: Text("0"),
                      child: Icon(CupertinoIcons.bell_solid, color: Colors.white),
                    ),
                    data: (leaveApprovals) => Badge(
                      label: Text(leaveApprovals.length.toString()),
                      child: const Icon(CupertinoIcons.bell_solid, color: Colors.white),
                    ),
                  ),
                ),
              ),
              // 其他组件代码...
            ],
          ),
        );
      });
    }
    

二、利用Riverpod自动化执行GET请求

除了上述定时刷新方案,还有两种常见的自动化触发GET请求的方式:

1. 监听应用生命周期触发

结合Flutter的生命周期监听,在应用从后台切回前台时自动拉取最新数据,避免不必要的定时请求:

import 'package:flutter/widgets.dart';

class PendingLeaveNotifier extends AsyncNotifier<List<LeaveApproval>> with WidgetsBindingObserver {
  @override
  Future<List<LeaveApproval>> build() async {
    WidgetsBinding.instance.addObserver(this);
    return _fetchPendingLeaves();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 应用回到前台时刷新数据
    if (state == AppLifecycleState.resumed) {
      ref.invalidateSelf();
    }
  }

  Future<List<LeaveApproval>> _fetchPendingLeaves() async {
    final approvalLeave = ApprovalLeave();
    return approvalLeave.pendingLeave();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}

2. 事件驱动触发

如果后端支持WebSocket或推送通知,可以在收到新请求的推送事件时,主动调用ref.invalidateSelf()触发GET请求更新状态,这种方式比定时刷新更高效,能做到数据实时同步。


内容的提问来源于stack exchange,提问作者Will Mwendwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:05:13