Home > OS >  flutter web open url and get data
flutter web open url and get data

Time:07-18

How to open url and get data. For example I open an url on web browser and after processing I need to fetch the url. Url launcher lib only return boolean and I can't get data from html lib.

This is the code:

void main() {
  runApp(MaterialApp(
    home: new Scaffold(
      body: new Center(
        child: new ElevatedButton(
          onPressed: () {
            //_launchInBrowser(Uri(scheme: 'https', host: "dart.dev"));
            var data = html.window.open("https://dart.dev", "dart dev");
            print(data.location);
          },
          child: new Text('Show Flutter homepage'),
        ),
      ),
    ),
  ));
}

Future<void> _launchInBrowser(Uri url) async {
  if (!await launchUrl(
    url,
    mode: LaunchMode.externalApplication,
  )) {
    throw 'Could not launch $url';
  }
}

CodePudding user response:

I've found this solution or workaround. In the web directory create an html file and put a code like that:

<script>
    var data = window.open("http://dart.dev");
    //alert(window.location.href);
    localStorage.setItem("url", window.location.href);
    console.log(localStorage.getItem("url"));
</script>

I need the url but it is possible to store any data from the page.

From flutter use the local storage:

import 'dart:html' as html;

class LocalStorage {
  final html.Storage _localStorage = html.window.localStorage;

  Future save(String url) async {
    _localStorage['url'] = url;
  }

  Future<String?> getUrl() async => _localStorage['url'];

  Future invalidate() async {
    _localStorage.remove('url');
  }
}

I tried with shared_preferences but it doesn't work. Now with the url_launcher lib:

ElevatedButton(
          onPressed: () async {
            var rep = LocalStorage();
            await _launchInBrowser(Uri(path: "open_url.html"));
            print(await rep.getUrl());
          },
          child: Text('Show Flutter homepage'),
        ),    
    Future<void> _launchInBrowser(Uri url) async {
      if (!await launchUrl(
        url,
        mode: LaunchMode.externalApplication,
      )) {
        throw 'Could not launch $url';
      }
    }
  • Related