24

In Dart I am working on a web game. In this I would need a function where I can get data from the URL, in the same way that you would get it in PHP. How would I do this?

Say I, for example, append the following to my URL when I load my web game: ?id=15&randomNumber=3.14. How can I get them in Dart either as a raw string (preferred) or in some other format?

Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
Casper Bang
  • 793
  • 2
  • 6
  • 24

3 Answers3

52

You can use the Uri class from dart:core
https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-core.Uri

ie:

main() {
  print(Uri.base.toString()); // http://localhost:8082/game.html?id=15&randomNumber=3.14
  print(Uri.base.query);  // id=15&randomNumber=3.14
  print(Uri.base.queryParameters['randomNumber']); // 3.14
}
Xavier
  • 3,647
  • 24
  • 17
17
import 'dart:html';   

void doWork(){  
  var uri = Uri.dataFromString(window.location.href); //converts string to a uri    
  Map<String, String> params = uri.queryParameters; // query parameters automatically populated
  var param1 = params['param1']; // return value of parameter "param1" from uri
  var param2 = params['param2'];
  print(jsonEncode(params)); //can use returned parameters to encode as json
}
  • 2
    Add some explanation for your code would be preferred. – keikai May 12 '20 at 07:17
  • 3
    While this code may provide a solution to problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution. – palaѕн May 12 '20 at 07:25
  • 1
    Thanks for your suggestions guys, I will keep these things in mind next time – Muhammad Ali Raza May 13 '20 at 09:41
4

Import 'dart:html' then you can use window.location...

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567