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

Flutter分类图片重复加载问题:如何缓存API图片消除加载耗时?

解决分类图片重复加载的问题

以下是针对你的问题的具体解决方案:

1. 优化数据请求逻辑,避免重复拉取分类数据

当前每次进入页面都会调用getCategories(),导致分类数据被重新赋值,同时间接触发图片重新加载。修改CategoryProvider,先判断已有数据再决定是否请求接口:

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:service_pro_user/Models/category_model.dart';
import 'package:http/http.dart' as http;

class CategoryProvider extends ChangeNotifier {
  List<CategoryModel> _categories = [];

  List<CategoryModel> get categories => _categories;

  Future<void> getCategories() async {
    // 已有分类数据时直接返回,无需重复请求
    if (_categories.isNotEmpty) return;
    
    final response =
        await http.get(Uri.parse('http://20.52.185.247:8000/category'));
    if (response.statusCode == 200) {
      final categoryData = jsonDecode(response.body)['data'] as List;
      _categories = categoryData.map((e) => CategoryModel.fromJson(e)).toList();

      notifyListeners();
    } else {
      throw Exception('Failed to load categories');
    }
  }

  // 可选:提供手动刷新数据的方法,需要时调用
  Future<void> refreshCategories() async {
    final response =
        await http.get(Uri.parse('http://20.52.185.247:8000/category'));
    if (response.statusCode == 200) {
      final categoryData = jsonDecode(response.body)['data'] as List;
      _categories = categoryData.map((e) => CategoryModel.fromJson(e)).toList();

      notifyListeners();
    } else {
      throw Exception('Failed to refresh categories');
    }
  }
}

2. 完善CachedNetworkImage的缓存配置

默认缓存策略可能无法持久保存图片,显式配置缓存规则,确保图片被本地存储:

修改Category.dart中的CachedNetworkImage部分,同时优化布局嵌套(去掉多余的FittedBox,直接使用图片自身的fit属性):

Expanded(
  child: Container(
    width: 180,
    height: 150,
    child: ClipRRect(
      borderRadius: BorderRadius.circular(5),
      child: CachedNetworkImage(
        imageUrl: image,
        placeholder: (context, url) => Lottie.asset('assets/lotties_animation/loading.json'),
        errorWidget: (context, url, error) => Lottie.asset('assets/lotties_animation/error.json'),
        // 使用默认缓存管理器,配置缓存有效期为7天
        cacheManager: DefaultCacheManager(),
        maxAgeCacheObject: const Duration(days: 7),
        fit: BoxFit.fill,
      ),
    ),
  ),
),

3. 确保Provider在应用顶层初始化

将CategoryProvider放在应用的顶层(如main.dart的MultiProvider中),避免页面销毁时Provider实例被回收,导致数据丢失:

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => CategoryProvider()),
        // 其他业务Provider
      ],
      child: const MyApp(),
    ),
  );
}

通过以上三点修改,分类数据会被持久保存在Provider中,图片也会被本地缓存,重载页面或从其他页面返回时不会再重复加载。

内容的提问来源于stack exchange,提问作者Sajeet Gurung SG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:47:40