我有一个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,
);
})
],
),
),
],
),
); }