Mohale Nakana
Mohale Nakana

Reputation: 87

The argument type 'String' can't be assigned to the parameter type 'Route<Object?>'.dart(argument_type_not_assignable)

I am trying to get the name of the screen to navigate to as a string(in a custom class), when clicking a button.

class myButton extends StatelessWidget {
  String button_txt = '';
  String nextPage = '';
  double height_ = 39;

  myButton(button_txt) {
    this.button_txt = button_txt;
    this.nextPage = nextPage;
  }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.pushReplacement(context, '/$nextPage');
      },

Upvotes: 3

Views: 5392

Answers (2)

The Anonymous Koder
The Anonymous Koder

Reputation: 602

There are two ways to do this:

  • use Navigator.pushNamedReplacement(context, '/$nextPage')
  • use Navigator.pushReplacement(context, route); with a Route Parameter

If you want to use named routes, then use
Navigator.pushNamedReplacement(context, '/name/of/route).
If it still doesn't work, then you might not have set up navigation properly.

If you want to use non-named routes, then the approach will be different:

Navigator.pushReplacement(
  context,
  MaterialPageRoute( // Material page route makes it
    // slide from the bottom to the top
    // 
    // If you want it to slide from the right to the left, use 
    // `CupertinoPageRoute()` from the cupertino library.
    // 
    // If you want something else, then create your own route
    // https://flutter.dev/docs/cookbook/animation/page-route-animation
    builder: (context) {
      return NextPageWidget();
    },
  ),
);

Upvotes: 1

Mahmoud Hegab
Mahmoud Hegab

Reputation: 88

If you want to use named routes you should use it like this:

Navigator.pushReplacementNamed(context, 'nextPage');

but if you don't want to use named routes there is different way to navigate:

  Navigator.pushReplacement(
    context,
    MaterialPageRoute(
      builder: (context) {
        return routewidget;
      },
    ),
  );

Upvotes: 5

Related Questions