在 Flutter WebView 中检查连接并强制刷新

Posted

技术标签:

【中文标题】在 Flutter WebView 中检查连接并强制刷新【英文标题】:Checking connection and force refreshing in Flutter WebView 【发布时间】:2020-05-03 03:02:45 【问题描述】:

我对颤动和尝试一些新事物仍然很陌生。我正在继续我的颤振WebView 个人项目应用程序,它有 5 个选项卡顺便说一句,每个选项卡在脚手架中都包含一个 WebView。我想要的是:

    检测用户点击选项卡(例如:主页)的时间,然后将其保存到variable 当它被保存并且用户退出主页选项卡并重新进入时,应用程序将通过将其与variable 中存储的时间进行比较来检查用户离开该选项卡的时间是否超过 1 分钟 如果大于 1 分钟: 检查连接 如果连接可用,则执行 WebView 的强制刷新 如果没有可用的连接,则显示一个对话框,显示“无连接” 如果不超过 1 分钟: 应用程序继续运行,不会调用任何内容

到目前为止我尝试过的是

var lastloaded                  //the variable where the access time of the tab will be saved

  void tappingOnTab()          //the function that will store that data and check if its > 1 min
    final now = DateTime.now();
    if(lastloaded != null)
      if(now.difference(lastloaded).inMinutes > 1) 
        _checkConnection();
      
    lastloaded = now;
    
  


  _checkConnection() async       //the function that will check for connection if its greater than 1 min
    var result = await (Connectivity().checkConnectivity());
    if(result == ConnectivityResult.none) 
      _showDialog("No internet", "You are not connected to the internet");
     else if (result == ConnectivityResult.mobile) 
      _showDialog("Internet Access", "You are connected over mobile data");
     else if (result == ConnectivityResult.wifi) 
      _showDialog("Internet Access", "You are connected over wifi");
    
  

  _showDialog(title, text) 
    showDialog(
      context: context,
      builder: (context) 
        return AlertDialog(
          title: Text(title),
          content: Text(text),
          actions: <Widget>[
            FlatButton(
              child: Text("Ok"),
              onPressed: () 
                Navigator.of(context).pop();
              ,
            )
          ],
        );
      
    );
  

请检查我在代码中输入的 //cmets,我已经尝试创建一个 FlatButton 检查检查连接的功能是否正常工作,但在我退出时它在 WebView 中不起作用tab 超过 1 mint 并返回,函数不会被调用。

这是我的代码,但我认为没有必要,但如果你想看看,那么这里

import 'dart:async';
import 'dart:io';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:syncshop_webview/widgets/notification_widget.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:connectivity/connectivity.dart';


class HomePage extends StatefulWidget 
  // HomePage(Key key) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();


class _HomePageState extends State<HomePage> 
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  // WebViewController myController;
  final flutterWebviewPlugin = new WebView();
var lastloaded;

  _exitApp(BuildContext context, Future<WebViewController> controller) async 
    controller.then((data) async 
      WebViewController controller = data;
      var goBack = await controller.canGoBack();
      if (goBack == true) 
        print("onwill go back");
        controller.goBack();
       else 
        print("onwill not go back");
        Navigator.pop(context);
      
    );
  

  @override
  void initState() 
    super.initState();
    firebaseCloudMessagingListeners();
  

  void firebaseCloudMessagingListeners() 
    if (Platform.isios) iOSPermission();

    _firebaseMessaging.getToken().then((token) 
      print(token);
    );

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async 
        setState(() 
          print("$message['data']['url']");
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (BuildContext context) => NotificationClicked()));
        );
      ,
      onResume: (Map<String, dynamic> message) async 
        print("$message['data']['url']");
      ,
      onLaunch: (Map<String, dynamic> message) async 
        print("$message['data']['url']");
      ,
    );
  

  void iOSPermission() 
    _firebaseMessaging.requestNotificationPermissions(
        IosNotificationSettings(sound: true, badge: true, alert: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) 
      print("Settings registered: $settings");
    );
  



  Completer<WebViewController> _controller = Completer<WebViewController>();

  void tappingOnTab() 
    final now = DateTime.now();
    if(lastloaded != null)
      if(now.difference(lastloaded).inMinutes > 1) 
        _checkConnection();
      
    lastloaded = now;
    
  

  @override
  Widget build(BuildContext context) 
    return WillPopScope(
        onWillPop: () => _exitApp(context, _controller.future),
        child: SafeArea(
    child: Scaffold(
        body: WebView(
    initialUrl: 'https://syncshop.online/en/',
    javascriptMode: JavascriptMode.unrestricted,
    onWebViewCreated: (controller) 
    _controller.complete(controller);
    ,
    onPageFinished: (controller) async 
      //SOME INJECTION OF CODE HERE
    ,
          ),
      //floating action button here
      ),
        ),
      );
  
  _checkConnection() async 
    var result = await (Connectivity().checkConnectivity());
    if(result == ConnectivityResult.none) 
      _showDialog("No internet", "You are not connected to the internet");
     else if (result == ConnectivityResult.mobile) 
      _showDialog("Internet Access", "You are connected over mobile data");
     else if (result == ConnectivityResult.wifi) 
      _showDialog("Internet Access", "You are connected over wifi");
    
  

  _showDialog(title, text) 
    showDialog(
      context: context,
      builder: (context) 
        return AlertDialog(
          title: Text(title),
          content: Text(text),
          actions: <Widget>[
            FlatButton(
              child: Text("Ok"),
              onPressed: () 
                Navigator.of(context).pop();
              ,
            )
          ],
        );
      
    );
  

【问题讨论】:

您应该能够在 AlertDialog 中的同一 onPressed 方法上使用其控制器刷新您的 WebView。 【参考方案1】:

您可以通过调用 WebViewController 来刷新 WebView。

late WebViewController _webViewController;

WebView(
  onWebViewCreated: (controller) 
    _webViewController = controller;
  ,
  ...
)

/// Call reload on WebViewController to refresh the page displayed
_webViewController.reload()

【讨论】:

以上是关于在 Flutter WebView 中检查连接并强制刷新的主要内容,如果未能解决你的问题,请参考以下文章

Flutter 与 iOS 原生 webView 对比

检查是不是有互联网连接 webView 没有出现

如何在 Flutter 中重新加载 webview?

你如何在flutter.dart中连续检查互联网访问,而不是连接[重复]

如何使用 flutter_webview 插件在 Flutter 中启用位置?

**已解决** 在 dart、flutter 应用程序中检查或连续收听互联网连接/网络连接