Rusiru Wijethilake
Rusiru Wijethilake

Reputation: 78

How to keep the Url parameters in Flutter web route path

I am building a flutter web app which requires a url parameter in the start.

Currently it needs a parameter like http://localhost:49844/?id=105897

But after the app catches the url it disappears (like http://localhost:49844/#/) from the web address bar causing the application to fail on refresh of the site. Is there a way to keep the parameter once in the Url path?

In my code I use code below to get the parameter value from the Url

String appUrl = Uri.base.queryParameters["id"].toString();

Also, I use home: instead of routes as I only have a single page to be displayed.

Upvotes: 5

Views: 4852

Answers (2)

Yash
Yash

Reputation: 427

Add flutter_web_plugins and execute flutter pub get command in the terminal.

// pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  flutter_web_plugins:
    sdk: flutter


  cupertino_icons: ^1.0.2
  timelines: ^0.1.0
  image: ^4.1.7
  touchable: ^1.0.2
  encrypt: ^5.0.1
  http: ^0.13.6
  ...

Next, call usePathUrlStrategy() inside main()

// main.dart

import 'package:flutter_web_plugins/flutter_web_plugins.dart';

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

Relaunch the project.

Upvotes: 0

MJ Studio
MJ Studio

Reputation: 4631

I think you need to try initialRoute and onGenerateRoute instead of home

This is just sample code, you can check docs for a more precise way. And this answer.

  MaterialApp(
    initialRoute: '/?id=105897',
    onGenerateRoute: (settings) {
      Uri uri = Uri.parse(settings.name);
      int id = int.parse(uri.queryParameters['id']);
      return const Home(id);
    },
  );

Upvotes: 1

Related Questions