Question

I have a page with links. These links all end in the same way. For example www.site.com/fruit/apples, www.site.com/fruit/bananas, www.site.com/fruit/oranges, etc. I want all these links to call the same Dart app and have the app do some processing and then redirect you wherever you need to go (the bananas page vs. the oranges page). This way, I avoid having an actual HTML file for every single fruit. I can instead have a single landing template that gets populated with variable fruit data.

The part I'm hung up on is passing the url into the Dart app so it can do the handling. I understand main() cannot receive arguments, so what's another way?

Was it helpful?

Solution

You can use the route package to handle the URL's for you.

For example:

import 'package:route/client.dart';

final fruitUrl = new UrlPattern(r'/fruit/(\w+)');

main() {
  var router = new Router()
    ..addHandler(fruitUrl, showFruit)
    ..listen();
}

void showFruit(String path) {
  var fruit = fruitUrl.parse(req.path)[0];
  // Display the page according to the fruit type
}

If you don't need to handle actual routes, and you just want to handle any query parameters passed of the form ?fruit=apple you don't have to use the routes package and can instead manually parse the URL:

Map params = {};

// If arguments were provided, decode them into params map
if(window.location.search.length > 1) {
  // Break all arguments into form: fruit=apple
  List<String> queryPairs = window.location.search.substring(1).split('&');
  for(String queryPair in queryPairs) {
    // Add arguments into params map: key=fruit, value=apple
    List<String> queryPairList = queryPair.split('=');
    params[queryPairList[0]] = queryPairList[1];
  }
}

// Handle the proper action based on the fruit
switch(params['fruit']) {
  case 'apple':
    // ...
    break;
    // ...
  case 'orange':
    // ...
    break;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top