Flutter URL strategy not woring on Web Release

1k views Asked by At

Flutter web debug works fine when manually entering the url, and i am using "pathUrlStrategy" for example http://localhost:14143/secondPage. But trying the same thing in release mode its just return 404 page for example http://localhost/secondPage when using xampp, github page, and when trying http://localhost/#/secondPage it redirects to home page http://localhost/home.

2

There are 2 answers

0
Going Bananas On

When you run the built binary of your flutter-web in prod (e.g. on a python http server) you need to configure the web server to route your other paths to your flutter web's index.html.

See Configuring your web server for more details.

Using python3 http server example script:

import http.server
import socketserver

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=".", **kwargs)

    def do_GET(self):
        if self.path == '/':
            self.path = '/index.html'
        elif self.path == '/home':
            self.path = '/index.html'
        elif self.path == '/secondPage':
            self.path = '/index.html'

        return http.server.SimpleHTTPRequestHandler.do_GET(self)


with socketserver.TCPServer(("0.0.0.0", 8080), Handler) as httpd:
    print("web server running..")
    httpd.serve_forever()
0
Armand Fourie On

I have improved upon this answer.

You can add the web folder, to the root of the file containing the .py script. To do so, you'll have to run flutter build web --release within your flutter project. Then you'll be able to copy the web folder from ../build/web to the other folder containing the .py file.

Change the directory argument in __init__, to the location of your web folder that was copied over. Running the script and opening localhost:8080 in your browser will then run your project build.

Note: The web folder can be any flutter build, form code magic, or from the project itself.

import http.server
import socketserver


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory="../script/web", **kwargs)

    paths = ["/", "/first-page", "/second-page"]

    def do_GET(self):
        if self.paths.__contains__(self.path):
            self.path = '/index.html'

        return http.server.SimpleHTTPRequestHandler.do_GET(self)


with socketserver.TCPServer(("localhost", 8080), Handler) as httpd:
    print("web server running..")
    httpd.serve_forever()