Flutter webivew how to set local storage

2019-07-31 22:11发布

问题:

My Flutter application flow works like this:

  1. User logins
  2. If login successfully, server returns a token
  3. Set token to local storage in webview
  4. Open Webview fullscreen to a specific URL

I am using this Webview plugin. The sample code shows that it supports local storage (it has a withLocalStorage option) but does not show how to use it.

I tried:

  1. Create new FlutterWebviewPlugin instance
  2. Set local storage on the newly-created instance by calling method evalJavascript
  3. call launch on the instance, set withJavascript, withLocalStorage to true and launched it to a URL;

    //1
    final flutterWebviewPlugin = new FlutterWebviewPlugin();
    //2
    flutterWebviewPlugin.evalJavascript("window.localStorage.setItem('token','SOMETOKEN')");
    //3
    flutterWebviewPlugin.launch(
        "https://SOMEURL",
        withLocalStorage: true,
        withJavascript: true);   
    

If I correctly set the local storage, the Webview would show account page; otherwise a login page (which was what happened)

I also note that the evalJavascript invocation doesn't seem to work. Also, changing order of step 2 and step 3 doesn't change anything.

Note that I'm aware of this question. The answer provided doesn't show how to set the local storage either, and it doesn't show the Webview fullscreen so it won't solve my problem.

回答1:

In the step #2 the code evaluates in an empty about:blank page. Hence, saved property is assigned to about:blank address and not SOMEURL address. Try evaluating #2 only after the Future returned by .launch(...) completes.

e.g.

flutterWebviewPlugin.launch("https://SOMEURL",
  withLocalStorage: true,
  withJavascript: true
).whenComplete(() {
  final res = flutterWebviewPlugin.evalJavascript("(function() { try { window.localStorage.setItem('token', 'SOMETOKEN'); } catch (err) { return err; } })();");
  // Wrapped `setItem` into a func that would return some helpful info in case it throws.
  print("Eval result: $res");
});