I am using a provider package to load products in an array by calling didChangeDependencies() method. This is working fine even when there is some change due to filters and new products are fetched then with the help of notifyListeners() this page rebuilds successfully. Although the problem arises when I tap on the product card to see product details screen and comes back to the all products screen, then didChangeDependencies is called again and whole page refreshes. Is there any way by which I can stop triggering didChangeDependencies() when I get back to this page or there is any other better way to implement what I am doing here?
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'loader.dart';
import '../screens/product_overview.dart';
import '../providers/user.dart';
class AllProducts extends StatefulWidget {
final double deviceHeight;
final double deviceWidth;
AllProducts(this.deviceHeight, this.deviceWidth);
@override
_AllProductsState createState() => _AllProductsState();
}
class _AllProductsState extends State<AllProducts> {
List _products = [];
bool _isLoading = true;
bool _gettingMoreProducts = false;
_loadMoreProducts() async {
print('Reached end of list');
if (_gettingMoreProducts) {
print('Already getting products');
return;
}
print('Firestore function called');
_gettingMoreProducts = true;
dynamic newProducts =
await Provider.of<User>(context, listen: false).getProducts();
_products.addAll(newProducts);
setState(() {});
print('New Products added');
_gettingMoreProducts = false;
}
@override
void didChangeDependencies() {
setState(() {
_isLoading = true;
});
print('Getting new products from init state');
Provider.of<User>(context).getProducts().then((products) {
setState(() {
_products = products;
_isLoading = false;
});
});
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 5),
height: widget.deviceHeight * 0.80,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
),
child: _isLoading
? Loader()
: ListView.builder(
itemCount: _products.length,
itemBuilder: (context, index) {
// if (index == _products.length - 1) {
// _loadMoreProducts();
// }
return Dismissible(
key: UniqueKey(),
onDismissed: (direction) {
setState(() {
_products.removeAt(index);
});
},
background: Container(
color: Colors.red,
child: Icon(
Icons.cancel,
color: Colors.white,
size: 50,
),
),
secondaryBackground: Container(
color: Colors.green,
child: Icon(
Icons.check,
color: Colors.white,
size: 50,
),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
// Product Overview builds a simple card for product and whenever I tap on card it moves to product detail screen which is just a simple screen with product details and when I press back button from that page all products rebuild again due to didchangedependencies.
child: ProductOverview(_products[index],
widget.deviceHeight, widget.deviceWidth),
),
);
},
));
}
}