Flutter WebView(flutter_inappwebview)

Flutter WebView

WebView在flutter中的实现方法主要有三种,三种的对比可以参考这篇文章
https://pub.dev/上搜索webview
Flutter WebView(flutter_inappwebview)
我们选择的是第三种flutter_inappwebview
官方文档给出了在使用时的要求
Flutter WebView(flutter_inappwebview)

使用方法如下

  1. 添加依赖
dependencies:
  flutter_inappwebview: ^5.3.2

使用时在对应文件下导包

import 'package:flutter_inappwebview/flutter_inappwebview.dart';
  1. 把minSdkVersion改为17
    Flutter WebView(flutter_inappwebview)

  2. 添加网络权限
    <uses-permission android:name="android.permission.INTERNET"/>Flutter WebView(flutter_inappwebview)

  3. 使用

InAppWebView中有很多属性,这里我们只监听了加载进度onProgressChanged,通过监听加载进度,我们可以在还未加载出网页时显示一个进度圈,加载超过99.9%不显示加载圈显示链接网页内容

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _flag = true;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("WebView"),
        ),
        body: Column(
          children: [
            this._flag ? _getMoreWidget() : Text(""),
            Expanded(
                child: InAppWebView(
              //老版本:initialUrl    新版本:initialUrlRequest
              initialUrlRequest: URLRequest(
                  url: Uri.parse(
                      "https://blog.csdn.net/m0_46527751?spm=1018.2226.3001.5343")),
              onProgressChanged: (controller, progress) {
                if (progress / 100 > 0.9999) {
                  setState(() {
                    this._flag = false;
                  });
                }
              },
            ))
          ],
        ));
  }
//自定义加载中的组件
  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }
}

Flutter WebView(flutter_inappwebview)
Flutter WebView(flutter_inappwebview)

上一篇:Sage X3称重管理功能介绍


下一篇:swift 重定向时替换其他URL