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?
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.
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 .
A query string is the portion of a URL where data is passed to a web application and/or back-end database.
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.
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With