5

I'm not sure what i'm missing i have this simple method with a Consumer class that returns a Dialog, but the problem is the following

The return type 'Future' isn't a 'Widget', as required by the closure's context.

it points to the line indicated below.

  func() {
    Consumer(builder: (context, ref, _) {
      return showDialog(     // <- [ERROR HERE]
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              content: unrelatedfunc(),
              actions: [
                TextButton(
                    child: const Text('Share'),
                    onPressed: () {
                      submit();
                      _TextFieldController.clear();
                      Navigator.of(context).pop();
                    })
              ],
            );
          });
    });
  }

i'm not sure why but i have been investigating and i haven't seen an example like this

ImEsteban
  • 63
  • 2
  • 5

2 Answers2

7

If you are trying to display a dialog that has a Consumer (to use ref inside), move your Consumer inside the builder inside the builder:

showDialog is like Navigator.push, you should only call it in onPressed, onTap or initState, not in a build method as you don't control how many times your widget will rebuild. It doesn't build a widget (like the other widgets), it pushes a new dialog page in the history (like Navigator.push).

// Here you are in a `onPressed` of a button (for example):
showDialog(
  context: context,
  builder: (BuildContext context) {
    return Consumer(builder: (context, ref, _) {
      return AlertDialog(
        content: unrelatedfunc(),
        actions: [
          TextButton(
            child: const Text('Share'),
            onPressed: () {
             submit();
             _TextFieldController.clear();
             Navigator.of(context).pop();
            },
          ),
        ],
      );
    });
  },
);

If you need to use ref in the same method that is displaying the dialog (calling showDialog) (let's say the onPressed of a button), you can wrap the button with the Consumer:

Consumer(
  builder: (context, ref, _) {
    return TextButton(
      child: Text('My button'),
      onPressed: () {
        // You can use `ref` here.
        showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(/* ... */);
          },
        );
      },
    );
  },
);
Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73
0

Use NavigatorState().push... when you were trying to go to the screen that contains showDialog instead of Navigator.of(....).push...