How do I get value from a URL in flutter

Issue

In Flutter I am building a web app. 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 Javascript. How would I do this?

Say I, for example, append the following to my URL when I load my web app: /#/5a9c14ca-06bf-4c3d-b41e-a1317ea1ae79. How can I get them in Dart either as a raw string (preferred) or in some other format?

What I Have tried so far

  void initState() {
        GetUrl();
  }

  void GetUrl(){

    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
    print(jsonEncode(params));//can use returned parameters to encode as json
    setState(() {});
  }

but am not getting any result. Thank you in advance

Solution

The uuid that you are trying to get in this case is a path segment not a params
so to get it you can do

  var uri = Uri.dataFromString('http://localhost:59786/#/5a9c14ca-06bf-4c3d-b41e-a1317ea1ae79-0.6869740326627118');
  var uuid = uri.pathSegments[4];
  print(uuid); // 5a9c14ca-06bf-4c3d-b41e-a1317ea1ae79-0.6869740326627118

or you can use a package to help you with that like qlevar_router.
a full example

import 'dart:math';
import 'package:flutter/material.dart';
import 'package:qlevar_router/qlevar_router.dart';

void main() {
  runApp(MyApp());
}

class AppRoutes {
  final routes = <QRouteBase>[
    QRoute(
      path: '/',
      page: (c) => PageOne(),
    ),
    QRoute(path: '/:uuid', page: (c) => PageTwo(c))
  ];
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerDelegate: QR.router(AppRoutes().routes),
      routeInformationParser: QR.routeParser(),
    );
  }
}

class PageOne extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(children: [
          Text('This is page one'),
          TextButton(
              onPressed: () => QR.to(
                  '/5a9c14ca-06bf-4c3d-b41e-a1317ea1ae79-${Random().nextDouble()}'),
              child: Text('To uuid')),
        ]),
      ),
    );
  }
}

class PageTwo extends StatelessWidget {
  final QRouteChild child;
  PageTwo(this.child);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(children: [
          Text(QR.params['uuid'].toString()),
          TextButton(onPressed: () => QR.back(), child: Text('Back'))
        ]),
      ),
    );
  }
}

Answered By – Schaban

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.