Flutter安卓内嵌网页视图插件flutter_inappwebview_android的使用

Flutter安卓内嵌网页视图插件flutter_inappwebview_android的使用

flutter_inappwebview_androidflutter_inappwebview 插件的Android实现。此插件允许你在Flutter应用中嵌入一个WebView组件,以便加载和展示网页内容。

使用方法

此包是被推荐的,这意味着你只需正常使用 flutter_inappwebview 即可。当你这样做时,此包会自动包含在你的应用中,因此你无需在 pubspec.yaml 文件中添加它。

然而,如果你导入此包以直接使用其API,你应该像往常一样将其添加到 pubspec.yaml 文件中。

以下是一个完整的示例Demo,展示了如何在Flutter应用中使用 flutter_inappwebview 插件来嵌入一个WebView组件。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter InAppWebView Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter InAppWebView Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late InAppWebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: InAppWebView(
        initialUrlRequest: URLRequest(url: Uri.parse("https://www.example.com")),
        onWebViewCreated: (InAppWebViewController controller) {
          _webViewController = controller;
        },
      ),
    );
  }
}

代码解释

  1. 导入必要的库:

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

    这些库分别用于构建Flutter界面和使用WebView组件。

  2. 创建主应用类:

    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter InAppWebView Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage(title: 'Flutter InAppWebView Demo'),
        );
      }
    }
    

    这里定义了应用的入口点和主题。

  3. 定义主页状态类:

    class MyHomePage extends StatefulWidget {
      MyHomePage({Key? key, required this.title}) : super(key: key);
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
  4. 初始化WebView并加载URL:

    class _MyHomePageState extends State<MyHomePage> {
      late InAppWebViewController _webViewController;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: InAppWebView(
            initialUrlRequest: URLRequest(url: Uri.parse("https://www.example.com")),
            onWebViewCreated: (InAppWebViewController controller) {
              _webViewController = controller;
            },
          ),
        );
      }
    }
    

更多关于Flutter安卓内嵌网页视图插件flutter_inappwebview_android的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter安卓内嵌网页视图插件flutter_inappwebview_android的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_inappwebview_android插件来嵌入网页视图的示例代码。这个插件允许你在Flutter应用中嵌入一个WebView并与之交互。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加flutter_inappwebview依赖(注意,虽然名字是flutter_inappwebview,但它包含了Android和iOS的支持)。

dependencies:
  flutter:
    sdk: flutter
  flutter_inappwebview: ^5.4.3+4  # 请检查最新版本号

2. 导入插件

在你的Dart文件中导入插件。

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

3. 创建WebView页面

接下来,创建一个包含WebView的页面。

class WebViewPage extends StatefulWidget {
  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  InAppWebViewController? webViewController;  
late ChromeSafariBrowser controller;
  late CookiesManager cookiesManager;

  @override
  void
 initState() {
    super.initState();
    cookiesManager = CookiesManager();
    controller = ChromeSafariBrowser();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(        title: Text("InAppWebView Example"),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: InAppWebView(
              initialUrlRequest: URLRequest(url: Uri.parse("https://www.google.com")),
              initialOptions: InAppWebViewGroupOptions(
                crossPlatform: InAppWebViewOptions(
                  debuggingEnabled: true,
                ),
                android: AndroidInAppWebViewOptions(
                  useHybridComposition: true,
                ),
                ios: IOSInAppWebViewOptions(
                  allowsInlineMediaPlayback: true,
                ),
              ),
              onWebViewCreated: (InAppWebViewController webViewController) {
                this.webViewController = webViewController;
              },
              onLoadStart: (InAppWebViewController controller, String url) {
                print("onLoadStart $url");
              },
              onLoadStop: (InAppWebViewController controller, String url) async {
                print("onLoadStop $url");
                // 获取网页标题
                String? title = await controller.getTitle();
                setState(() {
                  // 在这里更新你的UI,例如设置AppBar的标题
                });
              },
              onConsoleMessage: (InAppWebViewController controller, ConsoleMessage consoleMessage) {
                print("onConsoleMessage: ${consoleMessage.message}");
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // 示例:打开一个新的Chrome Custom Tabs窗口
          await controller.open(
            url: "https://www.flutter.dev",
            options: CustomTabsOptions(
              toolbarColor: Colors.blue,
              enableUrlBarHiding: true,
              showTitle: true,
              animation: CustomTabsAnimation.slide,
              enableDefaultShare: true,
              headers: {
                "My-Custom-Header": "custom_header_value",
              },
            ),
          );
        },
        tooltip: 'Open in Chrome Tabs',
        child: Icon(Icons.open_in_new),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }
}

4. 使用WebView页面

最后,在你的主应用中使用这个页面。

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter WebView Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WebViewPage(),
    );
  }
}

注意事项

  1. 权限:确保在你的AndroidManifest.xml文件中添加了必要的权限,如INTERNET
  2. 调试:如果debuggingEnabled设置为true,你可以使用Chrome DevTools进行调试。
  3. 版本兼容性:始终检查插件的最新版本和Flutter的版本兼容性。

这个示例代码展示了如何使用flutter_inappwebview插件在Flutter应用中嵌入一个WebView,并处理一些基本的事件,如页面加载开始和结束、控制台消息等。你可以根据需要进一步扩展和自定义。

回到顶部