我有一个ListView,其中包含产品列表。在ListView中点击ListTile时,将显示一个AlertDialog,其中包含一个TextFormField,允许用户编辑产品名称。
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: _products.length,
itemBuilder: (context, index) {
Product product = _products[index];
return ListTile(
title: Text(product.name),
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) => AlertDialog(
title: Text("Edit name"),
content: TextFormField(
initialValue: product.name,
maxLines: 1,
),
actions: <Widget>[
FlatButton(
child: Text("Save"),
onPressed: () {
// Save logic
},
),
],
),
);
},
);
});
}
问题是,当点击TextFormField时,应用程序立即因以下错误而崩溃:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building Builder(dirty):
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable. To safely refer to a
widget's ancestor in its dispose() method, save a reference to the ancestor by calling
inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.
有人可以建议吗?
答案 0 :(得分:0)
从AlertDialog创建为单独的小部件,这应该可以解决问题
检查此代码:
class MyDialog extends StatefulWidget{
final String productName;
MyDialog({this.productName})
}
class MyDialodState extends State<MyDialog>{
@override
Widget build(BuildContext context) {
reutrn AlertDialog(
title: Text("Edit name"),
content: TextFormField(
initialValue: widget.productName,
maxLines: 1,
),
actions: <Widget>[
FlatButton(
child: Text("Save"),
onPressed: () {
// Save logic
},
),
],
),
);
}
}
// your onTap on ListTile should look something like this:
return ListTile(
title: Text(product.name),
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) => MyDialog(
productName:product.name
);
},
);