Flutter Webivew如何设置本地存储 [英] Flutter webivew how to set local storage
问题描述
我的Flutter应用程序流程如下:
My Flutter application flow works like this:
- 用户登录
- 如果登录成功,服务器将返回令牌
- 将令牌设置为webview中的本地存储
- 打开
Webview
全屏到特定的URL
- User logins
- If login successfully, server returns a token
- Set token to local storage in webview
- 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.
我尝试过:
- 创建新的
FlutterWebviewPlugin
实例 - 通过调用方法
evalJavascript
在新创建的实例上设置本地存储
-
在实例上调用
launch
,将withJavascript
,withLocalStorage
设置为true
并将其启动到URL;
- Create new
FlutterWebviewPlugin
instance - Set local storage on the newly-created instance by calling method
evalJavascript
call
launch
on the instance, setwithJavascript
,withLocalStorage
totrue
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屋!