2

I need the ability just to update the URL in the address bar, without pushing a named route. Is there maybe a plugin for it? It not, can I invoke JavaScript functions from the Flutter code?

Currently the one way I found to update the URL is the code below, which forces to "push" a new route, which I do not want to do. I just want to update the address bar.

Note: I am using flutter web to create cross platform apps, so using dart:html is not an option as it fails the build on mobile.

// Within the `FirstScreen` widget
onPressed: () {
  // Navigate to the second screen using a named route.
  Navigator.pushNamed(context, '/second');
}
David Somekh
  • 795
  • 3
  • 12
  • 33

1 Answers1

2

To update the URL without reloading the page in JavaScript, you can use the history API.

You can do the same for Flutter, using the window.history available from dart:html:

  • Note this only works for Flutter Web
import 'package:flutter/material.dart';
import 'dart:html' as html;

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: TextButton(
            onPressed: () {
              html.window.history.pushState({}, '', '/test');
            },
            child: Text('Update the URL address bar'),
          ),
        ),
      ),
    );
  }
}
MendelG
  • 14,885
  • 4
  • 25
  • 52