如何打开url并获取数据。例如,我在web浏览器上打开一个url,处理后我需要获取url。Url启动库只返回布尔值,我无法从html库中获取数据。
这是代码:
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';
}
}
我找到了这个解决方案或变通方法。在web目录中创建一个html文件,并添加如下代码:
<script>
var data = window.open("http://dart.dev");
//alert(window.location.href);
localStorage.setItem("url", window.location.href);
console.log(localStorage.getItem("url"));
</script>
我需要的url,但它是可能的存储从页面的任何数据。
从flutter使用本地存储:
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');
}
}
我尝试了shared_preferences,但它不起作用。现在使用url_launcher库:
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';
}
}