You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用qr_code_scanner包扫描二维码后自动打开链接的实现方法

实现方案

你可以按以下两种常用方案实现扫码后自动打开链接的需求:

方案1:调用系统默认浏览器打开链接

  • 先在项目中添加url_launcher依赖,完成对应平台的基础配置
  • 扫码后先校验扫描内容是否为合法URL,校验通过后直接调用打开逻辑即可

修改你的onQRViewCreated方法代码如下:

onQRViewCreated(QRViewController qrViewController) {
  qrViewController.scannedDataStream.listen((qrData) async {
    qrViewController.pauseCamera();
    final String? qrCode = qrData.code;
    // 校验内容不为空且是合法链接
    if (qrCode != null && Uri.tryParse(qrCode)?.hasAbsolutePath == true) {
      // 调用系统浏览器打开链接
      await launchUrl(Uri.parse(qrCode));
      // 打开完成后恢复相机扫码
      qrViewController.resumeCamera();
    } else {
      // 非链接内容走原有业务逻辑
      Get.to(const DocumentDetails())!.then(
        (value) => qrViewController.resumeCamera(),
      );
    }
  });
}

方案2:应用内置WebView打开链接

如果不想跳转到系统浏览器,可以在应用内嵌入WebView加载链接:

  • 先在项目中添加webview_flutter依赖,完成对应平台的基础配置
  • 新建一个WebView承载页面,示例代码如下:
class InnerWebViewPage extends StatelessWidget {
  final String loadUrl;
  const InnerWebViewPage({super.key, required this.loadUrl});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('页面加载')),
      body: WebView(
        initialUrl: loadUrl,
        javascriptMode: JavascriptMode.unrestricted,
      ),
    );
  }
}
  • 修改onQRViewCreated逻辑,检测到是链接时跳转到内置WebView页面:
onQRViewCreated(QRViewController qrViewController) {
  qrViewController.scannedDataStream.listen((qrData) {
    qrViewController.pauseCamera();
    final String? qrCode = qrData.code;
    if (qrCode != null && Uri.tryParse(qrCode)?.hasAbsolutePath == true) {
      // 跳转到内置WebView页打开链接
      Get.to(InnerWebViewPage(loadUrl: qrCode))!.then(
        (value) => qrViewController.resumeCamera(),
      );
    } else {
      // 非链接内容走原有业务逻辑
      Get.to(const DocumentDetails())!.then(
        (value) => qrViewController.resumeCamera(),
      );
    }
  });
}

内容的提问来源于stack exchange,提问作者Kevnlan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:09:01