Tom3652
Tom3652

Reputation: 2967

How to prevent caching images from network flutter?

I have tried all of the following Widget to load images from network :

And also their ImageProvider :

There is no bool to choose not to cache images. The only way i have found is to load the ImageProvider like in initState() and then call evict() right after.

I don't really know if this works actually or if this is the best way to do...

Is there any way to prevent caching from network "natively" ?

Upvotes: 9

Views: 9201

Answers (2)

luke77
luke77

Reputation: 3713

You can achieve that simply by adding ? followed by timestamp at the end of your image url.

Image.network(
   '${imgUrl}?${DateTime.now().millisecondsSinceEpoch.toString()}',
   fit: BoxFit.cover,
),

Upvotes: 18

Sajad Abdollahi
Sajad Abdollahi

Reputation: 1741

I have just created a widget that gets the image as a URL and then download it as Uint8List and show it in a Image.memory widget.

You can use it like this:

NonCacheNetworkImage('https://riverpod.dev/img/logo.png'),
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:http/http.dart';

class NonCacheNetworkImage extends StatelessWidget {
  const NonCacheNetworkImage(this.imageUrl, {Key? key}) : super(key: key);
  final String imageUrl;
  Future<Uint8List> getImageBytes() async {
    Response response = await get(Uri.parse(imageUrl));
    return response.bodyBytes;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Uint8List>(
      future: getImageBytes(),
      builder: (context, snapshot) {
        if (snapshot.hasData) return Image.memory(snapshot.data!);
        return SizedBox(
          width: 100,
          height: 100,
          child: Text("NO DATA"),
        );
      },
    );
  }
}

Upvotes: 7

Related Questions