Home > other >  Flutter, break out private method to a helper class. Arguments problem
Flutter, break out private method to a helper class. Arguments problem

Time:12-28

I would like to break out this method and make it public in a helper class but I run into this error when trying and passing context to it? It wants two required contexts and BuildContext but I don't know how to implement this? I get this error. It seems to be a problem with two context arguments also:

"2 positional arguments required but found 0. Try to add missing arguments"

Or if I type the first context it is:

"1 positional argument required but found 0. Try to add missing arguments"

Private method:

_showDialog() {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Title'),
        content: Text('Body'),
        actions: <Widget>[
          OutlinedButton(
            child: Text('Close'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

Public method (with two context arguments):

class _LegendScreenState extends State<LegendScreen> {
  showDialog(context, BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Title'),
          content: Text('Body'),
          actions: <Widget>[
            OutlinedButton(
              child: Text('Close'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}

CodePudding user response:

The issue is coming because, you are defining showDialog method that is already defined on material.dart. It is overlapping with name. Try to rename the helper class something else like appDialog and pass context.

  appDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {

More about showDialog

CodePudding user response:

Remove one context argument. You only need one.

showDialog(context, BuildContext context) {

should be:

showDialog(BuildContext context) {
  • Related