I have a custom widget which represents a button and this widget is in a separated folder called "Widgets" inside the "lib" folder, and that is the button widget file
import 'package:flutter/material.dart';
Widget buttonWidget(String text, Function action) {
return ElevatedButton(
onPressed: () => action,
child: Text(text, style: const TextStyle(fontSize: 20),
);
}
now in the main.dart file I want the buttonWidget to use the Navigator.pushNamed function, so I called the buttonWidget like the
buttonWidget("Navigate", Navigator.pushNamed(context, '/screenTwo')),
but the buttonWidget call gives me this error
The argument type 'Future<Object?>' can't be assigned to the parameter type 'Function'.
CodePudding user response:
You need to create an anonymous function surrounding the call, just as you would if you were directly passing it to the onPressed
parameter.
buttonWidget("Navigate", () => Navigator.pushNamed(context, '/screenTwo')),
or
buttonWidget("Navigate", () {
Navigator.pushNamed(context, '/screenTwo');
}),