Flutter web cannot visit url

Issue

In flutter web, how can I open certain page via full address?

The scenario is:

  1. Open a classroom page route like
    await Navigator.pushNamed(context, "classroom/detail/$id", arguments: {"data": someData});
  2. Classroom page is opened and the address bar will contains URL like http://localhost/myschoolweb/classroom/detail/1
  3. I press F5 to refresh the page -> ERROR 404
  4. Open new tab and visit aforementioned address -> ERROR 404

This is my onGenerateRoute code:

onGenerateRoute: (RouteSettings settings) {
  List<String> routes = settings.name?.split("/") ?? [];
  final routeName = routes.isNotEmpty ? routes.first : null;
  final routeSub1 = routes.length > 1 ? routes[1] : null;
  final routeSub2 = routes.length > 2 ? routes[2] : null;

  final args = {
    ...(settings.arguments as Map<String, dynamic>? ?? {}),
    "sub1": routeSub1,
    "sub2": routeSub2,
  };

  Widget page = const SplashPage();
  switch (routeName) {
    case ROUTE_CLASS: page = ClassPage(args); break;
    // other routes ...
  }

  Future.microtask(() => FocusScope.of(context).requestFocus(FocusNode()));
  return MaterialPageRoute(
    settings: settings,
    builder: (context) {
      // other scripts ...
      return page;
    }
  );
},

I suspect it’ll be translated to classroom/detail/1/index.html which is of course non-existent on the server?

ps:
I use this library to simplify the web url: https://pub.dev/packages/url_strategy

Solution

Just in case anybody need it, I have solved this on apache server using .htaccess file.

RewriteEngine On
RewriteBase /
RewriteCond $1 !^(index\.html|assets|robots\.txt|favicon\.png)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ index.html [L]

So any URL will now defaults to index.html.

Answered By – Taufik Nur Rahmanda

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *