Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get query parameters in the URL

Tags:

url

dart

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?

like image 365
Casper Bang Avatar asked Oct 28 '14 07:10

Casper Bang


People also ask

What are query parameters in URL?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

How do I know if a URL has a parameter query?

To check if a url has query parameters, call the indexOf() method on the url, passing it a question mark, and check if the result is not equal to -1 , e.g. url. indexOf('? ') !== -1 .

What part of the URL is the query?

A query string is the portion of a URL where data is passed to a web application and/or back-end database.

How will you get the Query Parameter search?

In the View column, click View Settings. Under Site Search Settings, set Site Search Tracking to ON. In the Query Parameter field, enter the word or words that designate internal query parameters, such as term,search,query,keywords. Sometimes query parameters are designated by just a letter, such as s or q.


2 Answers

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
}
like image 63
Xavier Avatar answered Oct 14 '22 21:10

Xavier


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
}
like image 39
Muhammad Ali Raza Avatar answered Oct 14 '22 22:10

Muhammad Ali Raza