我想在_buildProductCard小部件中访问我的模型:
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()),
);
},
)
],
如您所见,我使用ScopedModelDescendant包装了我的脚手架,但我无法访问_buildProductCard方法中的模型。如果我使用ScopedModelDescendant包装my_buildProductCard,我当然可以获得访问权限,但是它使得函数工作非常慢,因为它只是构建了两次,我确信有更好的方法
在您的项目构建器上,您可以执行以下操作:
itemBuilder: (BuildContext context, int index) {
return _buildProductCard(context, index, model);
})
并在你_buildProductCard中添加一个额外的参数ConnectedProductModel模型。因此签名将是Widget _buildProductCard(BuildContext context, int index, ConnectedProductModel model)
只是不要忘记itemBuilder里面的返回。 希望这有帮助。