skip to Main Content

I know that base_href can be configured with below method.

command

flutter build web --base-href "/path/"

or

index.html

<base href="/path/">

ref: Setting base-href on build Flutter Web

How to get this information(/path/) in my Dart code?

Example:
--base-href "/foo/"
URL: http://localhost:8080/foo/some-route

I want: /foo/
Uri.base.path: /foo/some-route

2

Answers


  1. Uri.base says:

    The natural base URI for the current platform.

    When running in a browser, this is the current URL of the current page
    (from window.location.href).

    When not running in a browser, this is the file URI referencing the
    current working directory.

    Login or Signup to reply.
  2. I am not sure we can get this from the uri directly. You could try load the html and get the href attribute from the base tag. The below snippet shows how to do that:

    import 'dart:html' as html;
    
    String? getBaseHref() {
      final allBaseTags = html.document.getElementsByTagName('base');
      if (allBaseTags.isNotEmpty) {
        // Get the 'href' attribute directly from the first base tag
        final hrefValue = (allBaseTags.first as html.Element).getAttribute('href');
        return hrefValue;
      }
      return null;
    }
    

    We get the base tags, read the first one and get the href attribute. Where it is not available we return null. However, we should always have this available as it is always set as <base href="$FLUTTER_BASE_HREF"> to allow one pass the base href as an arg.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search