Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass Navigator function as a parameter in Dart?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The argument type 'Future<Object?>' can't be assigned to the parameter type 'Function'.

>Solution :

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');
}),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading