Flutter Webivew如何设置本地存储 [英] Flutter webivew how to set local storage

查看:550
本文介绍了Flutter Webivew如何设置本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Flutter应用程序流程如下:

My Flutter application flow works like this:

  1. 用户登录
  2. 如果登录成功,服务器将返回令牌
  3. 将令牌设置为webview中的本地存储
  4. 打开Webview 全屏到特定的URL
  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

我正在使用此Webview插件.该示例代码显示它支持本地存储(具有withLocalStorage选项),但没有显示如何使用它.

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.

我尝试过:

  1. 创建新的FlutterWebviewPlugin实例
  2. 通过调用方法evalJavascript
  3. 在新创建的实例上设置本地存储
  4. 在实例上调用launch,将withJavascriptwithLocalStorage设置为true并将其启动到URL;

  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);   

如果我正确设置了本地存储,则Webview将显示帐户页面;否则就是登录页面(发生了什么事)

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

我还注意到,evalJavascript调用似乎无效.另外,更改步骤2和步骤3的顺序也不会更改任何内容.

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.

请注意,我知道此问题.提供的答案也没有显示如何设置本地存储,也没有显示全屏显示的Webview,因此无法解决我的问题.

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.

推荐答案

在步骤#2中,代码在空白的about:blank页面中求值.因此,将已保存的属性分配给about:blank地址而不是SOMEURL地址.仅在.launch(...)返回的Future完成后,才尝试评估#2.

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.

例如

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");
});   

这篇关于Flutter Webivew如何设置本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆