Home > other >  Flutter Web Url Route Doesn't Work on Real domain
Flutter Web Url Route Doesn't Work on Real domain

Time:08-11

I'm trying to use a url where I get a parameter and assign that parameter to a variable inside the web file.

for example my domain is example.com and in this website i need an id for user. I want to make example.com/?id=123 and getting that 123 id and giving a variable 123 value

In flutter web device It works but when i host this files it doesnt work on real domain. And flutter giving me a

Could not navigate to initial route.
The requested route name was: "/[email protected]"
There was no corresponding route in the app, and therefore the initial route specified will be
ignored and "/" will be used instead.

Here is my code

void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      setPathUrlStrategy();
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
    
  runApp(const MyApp());
}

String myurl = Uri.base.toString(); //get complete url

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  @override
  void initState() {
    super.initState();
    getParams();
  }

  @override
  Widget build(BuildContext context) {
    getParams();

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'QR Numaratör',
      home: MyHomePage(id: mail),
    );
  }
}

void getParams() {
  var uri = Uri.dataFromString(window.location.href);
  Map<String, String> params = uri.queryParameters;
  var origin = params['id'];
  mail = origin;
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.id}) : super(key: key);
  String? id = Uri.base.queryParameters["id"];
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

CodePudding user response:

In your MaterialApp widget, you need to specify onGenerateRoute parameter. Something like this:

return MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'QR Numaratör',
  home: MyHomePage(id: mail),
  onGenerateRoute: (settings) {
            switch (kIsWeb? Uri.parse(settings.name).path : settings.name) {
              case'/':
                  Map args = settings.arguments as Map;
                  if(kIsWeb && args == null) {
                     args=Uri.parse(settings.name).queryParameters;
                   }
                  return MaterialPageRoute(builder: (_) => MyHomePage(id: args[id])); 
   }
  });
  • Related