I have a flutter app. I take images there over HTTP and want to cache them, because when scrolling everything loads again and takes time. How can I solve this problem? If you can give an example, please. It is necessary that it is not downloaded again. It is desirable that those products that have loaded have already been in the cache or at least pictures. How can I do this?
//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,
);
})
],
),
),
],
),
); }