我安装了flutter_webview_plugin。如果没有互联网连接,我试图启动自定义静态html页面而不是我的URL(我的网站'wwww.duevents.in'),因为“网页不可用”页面看起来不太专业。
我正在使用它检查设备上的互联网,它工作正常(连接互联网时'connectionStatus == true',反之亦然):
Future check() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
connectionStatus = true;
print("connected $connectionStatus");
}
} on SocketException catch (_) {
connectionStatus = false;
print("not connected $connectionStatus");
}
}
如果没有互联网连接,这是我要加载备用URL的代码:
WebviewScaffold(
url: connectionStatus == true ?"http://www.duevents.in" : Uri.dataFromString('
hello world', mimeType: 'text/html').toString())无论如何,无论设备是否具有互联网连接,它总是向我显示带有此代码的HTML页面。请告诉我这里有什么问题。
答案
我建议你改变check()方法直接返回URL。
Future getURL() async {
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
return "http://www.duevents.in";
}
} on SocketException catch (_) {
return Uri.dataFromString('
hello world', mimeType: 'text/html').toString();}
}
那么在FutureBuilder中你可以使用直接返回的URL。
FutureBuilder(
future: getURL(), // a previously-obtained Future or null
builder: (BuildContext context, String url) {
return SafeArea(
child: WebviewScaffold(
url: url))}
})
另一答案
@Mazin Ibrahim在上述评论中提供的解决方案为我工作。
所以我在这里发布解决方案:
FutureBuilder(
future: check(), // a previously-obtained Future or null
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (connectionStatus == true) {
//if Internet is connected
return SafeArea(
child: WebviewScaffold(
url: "http://www.duevents.in"))}
else{
//If internet is not connected
return SafeArea(
child: WebviewScaffold(
url: Uri.dataFromString('
hello world',mimeType: 'text/html').toString()) }})