I have a MaterialButton with the following onPressed field:
onPressed: () async {
final int intResult = await showMyDialog(context, provider.myArg) ?? 0;
//...
}
Here is the showMyDialog function:
Future<int?> showMyDialog(BuildContext context, Object someArg) async {
return showDialog<int>(
context: context,
builder: (BuildContext context) {
return ChangeNotifierProvider<MyProvider>(
create: (_) => MyProvider(someArg),
child: MyDialog(),
);
},
);
}
Now the problem I see is that in MyDialog (a StatelessWidget), I need to use Navigator.pop(...) to return a value for the awaited intResult. However, I can't seem to find a way to strongly type these calls, and so it's hard to be certain that no runtime type error will happen.
The best I have right now, which is admittedly a bit inconvenient, is to subclass StatelessWidget and wrap the Navigator functions in it:
abstract class TypedStatelessWidget<T extends Object> extends StatelessWidget {
void pop(BuildContext context, [T? result]) {
Navigator.pop(context, result);
}
}
Then in a TypedStatelessWidget<int> we can use pop(context, 0) normally, and pop(context, 'hi') will be marked as a type error by the editor. This still doesn't link the dialog return type and the navigator, but at least it avoids manually typing each navigator call.
Is there any better way to have this strongly typed ?