I have a Dashboard homepage that allows me to access another page called Brand.
GoRoute(
name: DashboardPage.routeName,
path: DashboardPage.routeName,
builder: (context,state) => const DashboardPage(),
routes: [
GoRoute(
name: BrandPage.routeName,
path: BrandPage.routeName,
builder: (context,state) => const BrandPage(),
)
My goal is to be able to add a new brand on the Brand page, send the name of this brand to my database, and then have my page (in the form of a ListView) refresh instantly to show the newly added brand.
To optimize the functioning of this system, I have two functions,:
addBrand
to add a new brand to my database (in a file Db_helper):
static Future<void> addBrand(Brand brand) {
final doc = _db.collection(collectionBrand).doc();
brand.id = doc.id;
return doc.set(brand.toMap());
}
getAllBrands
to retrieve all the brands from my database and stock them in a list defined in my provider:
getAllBrands() {
DbHelper.getAllBrands().listen((snapshot) {
brandList = List.generate(snapshot.docs.length, (index) => Brand.fromMap(snapshot.docs[index].data()));
});
notifyListeners();
}
To try to solve my problem, it seems that I simply need to call my getAllBrands
function at the “right moment” and then display all the elements of the brandList
in my ListView
.
Consumer<TelescopeProvider>(
builder: (context, provider, child) =>
provider.brandList.isEmpty
? const Center(child: Text("Brand Not Found"))
: ListView.builder(
itemCount: provider.brandList.length,
itemBuilder: (context, index) {
final brand = provider.brandList[index];
return ListTile(
title: Text(brand.name),
);
},
),
)
To avoid constantly regenerating my data, I decided to refresh my data whenever there are changes in the dependencies of the Dashboard (I want to access other pages besides Brand, so I want to centralize everything in the Dashboard). Therefore, I wrote in DashboardPage
:
@override void didChangeDependencies() {
Provider.of<TelescopeProvider>(context, listen: false).getAllBrands(); super.didChangeDependencies();
}
However, every time I add an element in Brand, the page does not update immediately; I have to return to the Dashboard and then go back to Brand to see my new list.
I think I understand why this is happening because when I return to the Dashboard from Brands, the Dashboard is reconstructed, which calls the didChangeDependencies
function. However, when I stay on Brand and add my element, there is no change in context, and thus didChangeDependencies
is not triggered.
Yet, I saw a video doing the same thing, and Brand was updating directly. Therefore, I am a bit lost both on the conditions that cause didChangeDependencies
to be called and especially on how to solve my problem.