Dart2 Router Implementation

Issue

I am trying to upgrade Dart1 application to Dart 2.4, I am facing a problem in Router my code is as shown below

import 'dart:async';
import 'dart:convert';
import 'package:angular/src/core/di/decorators.dart';
@Injectable()
class SpRouterImpl implements SpRouter {
 final Router _router;

 SpRouterImpl(this._router);
 @override
 void go(String routeName, Map<String, String> parameters,
  [bool openInNewWindow = false]) {
  if (openInNewWindow) {
  var url = _router.generate([routeName, parameters]).component.urlPath;
  window.open(url, "_blank");
 } else {
  _router.navigate([routeName, parameters]);
 }
}
}

I am getting error in this line

var url = _router.generate([routeName, parameters]).component.urlPath;

The method generate isn’t defined for the class Router

Second error is here

_router.navigate([routeName, parameters]);

The argument type List can’t be assigned to the parameter type ‘String’

The above function is working fine in Dart 1 but when I upgrade to Dart 2, I am getting the errors, don’t know how to solve it.

Can anyone help in this regard

Solution

You need a RoutePath instance to define your “route”.

final search = RoutePath(path: "search/:term"); // term is the parameter

Then use that path to navigate to that route.

_router.navigate(search.toUrl(parameters: {'term': searchTerm}));

So in your case it might look like this:

import 'dart:async';
import 'dart:convert';
import 'package:angular/src/core/di/decorators.dart';
@Injectable()
class SpRouterImpl implements SpRouter {
   final Router _router;

   SpRouterImpl(this._router);
   @override
   void go(String routeName, Map<String, String> parameters,
    [bool openInNewWindow = false]) {
     final path = RoutePath(routeName);
     final url = path.toUrl(parameters: parameters)
     if (openInNewWindow) {
       window.open(url, "_blank");
     } else {
       _router.navigate(url);
     }
   }
}

It might not drop in and work depending on how your routeName is defined but this is the general idea.

There are several other options for RoutePath check them out and see what works best for you!

Answered By – Brian Gorman

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *