如何在Flutter中缓存图像?

3

我有一个Flutter应用程序,通过HTTP获取图像并希望对它们进行缓存,因为当滚动时会重新加载所有内容,需要时间。

我该如何解决这个问题?如果您可以提供示例,请。需要确保不会再次下载。最好是已经加载过的产品已在缓存中,或者至少是图片。我该怎么做呢?

//method gets products
Future<List<Product>> getProducts(int id) async {
var response = await http.get(Uri.parse('...'));
final products = jsonDecode(response.body).cast<Map<String, dynamic>>();

List<Product> list = products.map<Product>((json) => Product.fromJson(json)).toList();

return list;}
// parse json
factory Product.fromJson(Map<String, dynamic> data) {
return Product(
    id: data['id'] as int,
    title: data['name'] as String,
    description: data['description'] as String,
    imgUrl: data['images'][0]['src'] as String,
    price: num.tryParse(data['price'])
);}
//draw products
Widget build(BuildContext context) {
final product = Provider.of<Product>(context, listen: false);

return Container(
  width: 150,
  padding: const EdgeInsets.all(10.0),
  margin: const EdgeInsets.all(5.0),
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(15.0),
    color: Color(422),
  ),
  child: Column(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: <Widget>[

      GestureDetector(
        onTap: () {
          Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) =>
              ItemPage(productId: product.id.toString())),
          );
        },
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              height: 160,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15),
                  image: DecorationImage(
                    image: NetworkImage(product.imgUrl),
                    fit: BoxFit.cover,
                  )),
            ),
            Container(
                child: Text(
                  '${product.title}',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                )),
          ],
        ),
      ),

      Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text('${product.price} руб.'),
            IconButton(
                icon: Icon(Icons.add_circle_outline, color: Colors.black12),
                onPressed: () {
                  // print(product.price);
                  Provider.of<CartDataProvider>(context, listen: false)
                      .addItem(
                    productId: product.id.toString(),
                    price: product.price,
                    title: product.title,
                    imgUrl: product.imgUrl,
                  );
                })
          ],
        ),
      ),

    ],
  ),
);  }

请查看此链接 https://dev59.com/iFMI5IYBdhLWcg3wfbbN#56125206 - Ameer Amjed
1个回答

5
您可以使用 cached_network_image 包。 它使用 flutter_cache_manager 存储和检索文件。 您可以像这样简单地使用它:
    CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     ),

不要使用cached_network_image包,它会让你头疼的,相信我。看这个:https://dev59.com/JVMI5IYBdhLWcg3wk8a8 - SwiftiSwift

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接