Flutter增强URL启动插件enhanced_url_launcher_android的使用

Flutter增强URL启动插件enhanced_url_launcher_android的使用

本指南将展示如何在Flutter应用中使用增强的URL启动插件enhanced_url_launcher的Android实现。该插件允许你以多种方式启动URL,包括浏览器、内置WebView等。

使用方法

该插件被推荐为官方支持的插件,因此你可以直接使用enhanced_url_launcher,而无需手动将其添加到pubspec.yaml文件中。如果你需要导入此包以使用其API,则应将其添加到你的pubspec.yaml文件中。

dependencies:
  enhanced_url_launcher: ^x.x.x

完整示例代码

以下是一个完整的示例代码,展示了如何使用enhanced_url_launcher插件来启动不同类型的URL。

// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'URL 启动器',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'URL 启动器'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final UrlLauncherPlatform launcher = UrlLauncherPlatform.instance;
  bool _hasCallSupport = false;
  Future<void>? _launched;
  String _phone = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    // 检查是否支持电话呼叫。
    launcher.canLaunch('tel:123').then((bool result) {
      setState(() {
        _hasCallSupport = result;
      });
    });
  }

  Future<void> _launchInBrowser(String url) async {
    if (!await launcher.launch(
      url,
      useSafariVC: false,
      useWebView: false,
      enableJavaScript: false,
      enableDomStorage: false,
      universalLinksOnly: false,
      headers: {},
    )) {
      throw Exception('无法启动 $url');
    }
  }

  Future<void> _launchInWebView(String url) async {
    if (!await launcher.launch(
      url,
      useSafariVC: true,
      useWebView: true,
      enableJavaScript: false,
      enableDomStorage: false,
      universalLinksOnly: false,
      headers: {'my_header_key': 'my_header_value'},
    )) {
      throw Exception('无法启动 $url');
    }
  }

  Future<void> _launchInWebViewWithJavaScript(String url) async {
    if (!await launcher.launch(
      url,
      useSafariVC: true,
      useWebView: true,
      enableJavaScript: true,
      enableDomStorage: false,
      universalLinksOnly: false,
      headers: {},
    )) {
      throw Exception('无法启动 $url');
    }
  }

  Future<void> _launchInWebViewWithDomStorage(String url) async {
    if (!await launcher.launch(
      url,
      useSafariVC: true,
      useWebView: true,
      enableJavaScript: false,
      enableDomStorage: true,
      universalLinksOnly: false,
      headers: {},
    )) {
      throw Exception('无法启动 $url');
    }
  }

  Widget _launchStatus(BuildContext context, AsyncSnapshot<void> snapshot) {
    if (snapshot.hasError) {
      return Text('错误: ${snapshot.error}');
    } else {
      return const Text('');
    }
  }

  Future<void> _makePhoneCall(String phoneNumber) async {
    // 使用 `Uri` 确保 `phoneNumber` 被正确URL编码。
    // 直接使用 'tel:$phoneNumber' 可能在某些情况下创建无效的URL(例如输入包含空格),
    // 这会导致某些平台上的 `launch` 失败。
    final Uri launchUri = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    await launcher.launch(
      launchUri.toString(),
      useSafariVC: false,
      useWebView: false,
      enableJavaScript: false,
      enableDomStorage: false,
      universalLinksOnly: true,
      headers: {},
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    const String toLaunch = 'https://www.cylog.org/headers/';
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: TextField(
                    onChanged: (String text) => _phone = text,
                    decoration: const InputDecoration(
                        hintText: '输入要拨打电话的号码')),
              ),
              ElevatedButton(
                onPressed: _hasCallSupport
                    ? () => setState(() {
                          _launched = _makePhoneCall(_phone);
                        })
                    : null,
                child: _hasCallSupport
                    ? const Text('拨打电话')
                    : const Text('不支持拨打电话'),
              ),
              const Padding(
                padding: EdgeInsets.all(16.0),
                child: Text(toLaunch),
              ),
              ElevatedButton(
                onPressed: () => setState(() {
                  _launched = _launchInBrowser(toLaunch);
                }),
                child: const Text('在浏览器中打开'),
              ),
              const Padding(padding: EdgeInsets.all(16.0)),
              ElevatedButton(
                onPressed: () => setState(() {
                  _launched = _launchInWebView(toLaunch);
                }),
                child: const Text('在应用中打开'),
              ),
              ElevatedButton(
                onPressed: () => setState(() {
                  _launched = _launchInWebViewWithJavaScript(toLaunch);
                }),
                child: const Text('在应用中打开(启用JavaScript)'),
              ),
              ElevatedButton(
                onPressed: () => setState(() {
                  _launched = _launchInWebViewWithDomStorage(toLaunch);
                }),
                child: const Text('在应用中打开(启用DOM存储)'),
              ),
              const Padding(padding: EdgeInsets.all(16.0)),
              ElevatedButton(
                onPressed: () => setState(() {
                  _launched = _launchInWebView(toLaunch);
                  Timer(const Duration(seconds: 5), () {
                    launcher.closeWebView();
                  });
                }),
                child: const Text('在应用中打开并关闭(5秒后)'),
              ),
              const Padding(padding: EdgeInsets.all(16.0)),
              FutureBuilder<void>(future: _launched, builder: _launchStatus),
            ],
          ),
        ],
      ),
    );
  }
}

更多关于Flutter增强URL启动插件enhanced_url_launcher_android的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter增强URL启动插件enhanced_url_launcher_android的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用enhanced_url_launcher_android插件的示例代码案例。这个插件主要用于在Android平台上增强URL启动功能,比如支持自定义浏览器、处理权限请求等。

首先,确保你已经将enhanced_url_launcher_android插件添加到你的Flutter项目中。在你的pubspec.yaml文件中添加以下依赖项:

dependencies:
  flutter:
    sdk: flutter
  enhanced_url_launcher_android: ^最新版本号

然后运行flutter pub get来安装插件。

接下来,在你的Flutter项目中,你可以按照以下步骤使用enhanced_url_launcher_android插件:

  1. 导入插件

在你的Dart文件中(例如main.dart),首先导入插件:

import 'package:flutter/material.dart';
import 'package:enhanced_url_launcher_android/enhanced_url_launcher_android.dart';
  1. 请求权限(如果需要):

在Android 6.0(API 级别 23)及更高版本中,你需要请求INTERNET权限才能在应用中打开URL。确保在你的AndroidManifest.xml文件中已经添加了INTERNET权限:

<uses-permission android:name="android.permission.INTERNET" />

此外,如果你希望使用自定义浏览器,可能需要请求其他权限,如QUERY_ALL_PACKAGES,这也需要在AndroidManifest.xml中声明:

<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />

注意:QUERY_ALL_PACKAGES权限在Android 12及以上版本中可能会受到限制,需要处理兼容性问题。

  1. 使用插件打开URL

在你的Flutter应用中,你可以使用以下代码来打开URL:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Enhanced URL Launcher Demo'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: _launchUrl,
            child: Text('Launch URL'),
          ),
        ),
      ),
    );
  }

  void _launchUrl() async {
    String url = "https://www.example.com";

    // 检查设备是否能处理该URL
    if (await canLaunchUrl(url)) {
      // 使用默认浏览器打开URL
      await launchUrl(url);
    } else {
      // 处理无法打开URL的情况
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Could not launch $url")),
      );
    }
  }
}

注意:上面的代码示例使用了canLaunchUrllaunchUrl函数,这些函数是enhanced_url_launcher_android插件提供的。不过,由于enhanced_url_launcher_android的具体API可能与标准的url_launcher插件有所不同,你可能需要查阅enhanced_url_launcher_android的官方文档来确认正确的API使用方法。如果enhanced_url_launcher_android提供了额外的自定义浏览器功能或权限处理功能,你可能还需要进一步配置和调用相关API。

另外,由于enhanced_url_launcher_android是一个特定于Android的插件,因此在iOS上可能无法正常工作或需要额外的处理。

注意:在实际使用中,请务必查阅enhanced_url_launcher_android插件的最新文档和示例代码,以确保你使用的是最新且正确的API。上面的代码示例是基于假设的API用法,并可能需要根据实际插件的API进行调整。

回到顶部