I'm trying to call a method in Stateless widget but it gives error.
X Class:
class X extends StatelessWidget {
const X({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
Divider(height: 5,),
ListTile(
title: Text('X').tr(),
leading: Container(
height: 30,
width: 30,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(5)
),
child: Icon("x", size: 20, color: Colors.white),
),
trailing: Icon("x", size: 20,),
onTap: _openDialog(context),//This line is problematic! If I remove this line, it does not give any error.
),
],
);
}
_openDialog(context) {
return showDialog(
barrierDismissible: true,
context: context,
builder: (context) {
return AlertDialog(
title: Text('title').tr(),
content: Text('subtitle').tr(),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('confirm').tr(),
),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('cancel').tr())
],
);
});
}
}
The code explains everything, my aim is clear, the code is clear... So how can I solve my problem? ...
Detailed error:
This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
CodePudding user response:
you are calling the function _openDialog
while building the widgets, which in turn builds its own widget which is the AlertDialog
, you want this dialog to be shown on tap so you should pass a function not call one.
i.e
onTap: () => _openDialog(context),
or
onTap: () {
_openDialog(context);
},