I was trying to pass argument to a button widget but I’m getting below error message.
Here is my argument:
ElevatedRegisterButton(
navigator: Navigator.of(context)
.push(MaterialPageRoute(builder: (context) {
return const RegisterPage1();
})))
Here is my widget where I was trying to pass argument:
import 'package:flutter/material.dart';
class ElevatedRegisterButton extends StatefulWidget {
const ElevatedRegisterButton({super.key, required this.navigator});
final String navigator;
@override
State<ElevatedRegisterButton> createState() => _ElevatedRegisterButtonState();
}
class _ElevatedRegisterButtonState extends State<ElevatedRegisterButton> {
@override
Widget build(BuildContext context) {
return ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () {
widget.navigator;
},
child: const Text('Register'),
);
}
}
Here is the error message I’m getting:
The argument type ‘Future’ can’t be assigned to the parameter type ‘String’.
2
Answers
You need to set the
navigator
member to typefinal void Function()
, because theonPressed
property ofElevatedButton
requires this type. You also need to pass it differently, becausepush
is another type of function. Lastly, simply setonPressed
towidget.navigator
.An example code is below based on your code snippet:
Problem 1
In your code:
you are accepting a
String navigator
; but you are passing to it aFuture
:problem 2
If you try running your code, you’ll get an error:
So, to fix the issues, refactor your code as follows:
See also
setState() or markNeedsBuild called during build