How to Read GET Parameters from URL in Flutter Web

Flutter Web is new and there are lots of difficulties while building simple functionality, the same way it is a bit difficult to grab URL attributes or parameters.   Anyway, we will show you how to grab parameters from URLs in Flutter web. See the example below:

To get Parameters from URL:

void main() {
  String myurl = Uri.base.toString(); //get complete url
  String para1 = Uri.base.queryParameters["para1"]; //get parameter with attribute "para1"
  String para2 = Uri.base.queryParameters["para2"]; //get parameter with attribute "para2"
}

See the example below to display these values in Scaffold() widget.

Full Dart Code:

Note: Flutter Web is not matured yet. There are other ways as well, if we get another best way to grab parameters, we will replace this guide.  

import 'package:flutter/material.dart';

void main() {

  String myurl = Uri.base.toString(); //get complete url
  String para1 = Uri.base.queryParameters["para1"]; //get parameter with attribute "para1"
  String para2 = Uri.base.queryParameters["para2"]; //get parameter with attribute "para2"

  runApp(MyApp(myurl: myurl, para1: para1, para2:para2)); //pass to MyApp class
}

class MyApp extends StatefulWidget{

  String myurl, para1, para2;
  MyApp({this.myurl, this.para1, this.para2}); //constructor of MyApp class

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: Scaffold( 
            appBar: AppBar( 
              title: Text("Get URL Parameter"),
              backgroundColor: Colors.redAccent,
            ),
            
            body: Container( 
              padding: EdgeInsets.all(20),
              alignment: Alignment.center,
              child: Column(
                children: [
                  //display parameters and URL here
                   Text(widget.para1 == null?"Parameter1 is null":"Parameter 1 = " + widget.para1),
                   Text(widget.para2 == null?"Parameter2 is null":"Parameter 2 = " + widget.para2),
                   Text(widget.myurl == null?"URl is null":"URL = " + widget.myurl)
                ],)
              )
        ),
    );
  }
}

Now run this in web, and pass parameters with attributes "para1" and "para2" to see the output:

Output Screenshot:

Here, we had passed http://localhost:33513/?para1=flutter&para2=campus URL, and we get the output above. You can try with your own parameters. This is the way you can read parameters from URLs in Flutter Web.

No any Comments on this Article


Please Wait...