FlutterWebviewPlugin侦听器无法识别* .pdf为网址

时间:2020-06-30 21:58:30

标签: flutter dart

我在Flutter中有一个Webview,并且有一个指向http://mywebsite.com/dummy.pdf

的链接的页面

问题在于,当用户单击pdf链接时,webview侦听器不会侦听。

flutterWebviewPlugin.onUrlChanged.listen((String url) async {
      if (url.contains('.pdf')) {
        print(url); //This print is never done
      }
      if (url.contains('mailto:')) {
        print(url); //This print is ok
      }
      if (url.contains('txt')) {
        print(url); //This print is ok
      }
      if (url.contains('foobar')) {
        print(url); //This print is ok
      }
    }

如何解决这个问题?

更新1

此问题与指向“非托管”文件的网址有关。

flutterWebviewPlugin.onUrlChanged.listen((String url) async {
      if (url.contains('.pdf')) {
        print(url); //This print is never done
      }
      if (url.contains('.doc')) {
        print(url); //This print is never done
      }
      if (url.contains('mailto:')) {
        print(url); //This print is ok
      }
      if (url.contains('.txt')) {
        print(url); //This print is ok
      }
      if (url.contains('.mp3')) {
        print(url); //This print is ok
      }
    }

1 个答案:

答案 0 :(得分:0)

我不知道这是否是一种更好的方法,但是如果问题仅在于pdf,那么我们只能通过Dart编程方法来解决这个问题。

但是,我觉得您也必须对此进行检查:url.contains('pdf'),而不是去.pdf中去contains()

因此,现在的解决方法是执行以下操作:

1. Check the length of the url 
2. Since the pdf would come at the last, so we need the last three items
3. Check if it is `pdf` only or not, like pdfString = Substring of the String of last three chars // In this way you  get the last three elements of the url
4. Do a check whether pdfString == 'pdf', if yes, print('OK') else // do something

最终解决方案

// This is a workaround for pdf only, so writing the code for that only
flutterWebviewPlugin.onUrlChanged.listen((String url) async {
   // technically this should give you the last three chars, which is pdf in this case
   var pdfString = url.substring(url.length-3); 

   // now checking if the pdfString contains that pdf or not
   if(pdfString == 'pdf'){
     //print your url
     print(url); // OUTPUT WILL BE http://mywebsite.com/dummy.pdf
   }
}

我希望,您会发现它足够有用,可以被包含在代码中。这是一种可行的解决方案,如果pdf的网址始终以.pdf结尾。让我知道这是给你的,直到那时快乐的学习:)