I am trying to get access to my models at _buildProductCard widget:
Widget build(BuildContext context) {
return ScopedModelDescendant<ConnectedProductModel>(
builder:
(BuildContext context, Widget child, ConnectedProductModel model) {
return Scaffold(
drawer: Drawer(),
appBar: AppBar(),
body: Column(
children: <Widget>[
Container(
child: RaisedButton(
onPressed: () => model.addProduct('NaNa',
'https://cdn.pixabay.com/photo/2019/01/27/22/31/girl-3959203__340.jpg'),
child: Text('Add Product'),
),
),
Expanded(
child: ListView.builder(
//build the cards
itemBuilder: _buildProductCard,
//lengta of the list,
itemCount: model.product.length,
),
),
],
),
);
},
);
}
Widget _buildProductCard(BuildContext context, int index) {
return Card(
child: Column(
children: <Widget>[
Image.network(model.product[index].image),
Text(model.product[index].address),
ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
IconButton(
icon: Icon(Icons.location_on, color: Colors.blue, size: 40.0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductNavigation()),
);
},
),
IconButton(
icon: Icon(Icons.delete, color: Colors.blue, size: 40.0),
onPressed: () => model.deleteProduct(index),
),
IconButton(
icon: Icon(Icons.info, color: Colors.blue, size: 40.0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProductInfoPage(
model.product[index].address,
model.product[index].image,
model.product[index].id),
),
);
},
),
IconButton(
icon:
Icon(Icons.contact_mail, color: Colors.blue, size: 40.0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => FormPage()),
);
},
)
],
As you see, i wrapped my scaffold with ScopedModelDescendant, but i can't get access to my models inside _buildProductCard method. If i wrapped my_buildProductCard with ScopedModelDescendant i of course can get access, but it make the function work very slow cause it just build it twice, and i sure there is a better way of doing this
On your item builder you can do as follow:
itemBuilder: (BuildContext context, int index) {
return _buildProductCard(context, index, model);
})
And in you _buildProductCard add an extra parameter ConnectedProductModel model. So signature will be Widget _buildProductCard(BuildContext context, int index, ConnectedProductModel model)
Just don't forget the return inside itemBuilder.
Hope this help.