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

Flutter新手求助:解决'String无法赋值给Uri参数'类型错误

解决Flutter调用Google Maps时的"The argument type 'String' can't be assigned to the parameter type 'Uri'"错误

这个错误是因为url_launcher包的新版本(v6.0.0及以上)对canLaunchUrl和launchUrl方法的参数类型做了变更——不再接受字符串格式的URL,必须传入Uri类型的对象。

修正后的代码

直接将字符串URL转换为Uri实例即可解决问题,以下是完整的修正代码:

import 'package:url_launcher/url_launcher.dart';

class MapsUtils {
  MapsUtils._();

  // 通过经纬度打开Google Maps
  static Future<void> openMapWithPosition(
      double latitude, double longitude) async {
    // 将字符串URL转换为Uri对象
    Uri googleMapUrl = Uri.parse(
        "https://www.google.com/maps/search/?api=1&query=$latitude,$longitude");

    if (await canLaunchUrl(googleMapUrl)) {
      await launchUrl(googleMapUrl);
    } else {
      throw "无法打开地图";
    }
  }

  // 通过地址打开Google Maps
  static Future<void> openMapWithAddress(String fullAddress) async {
    String query = Uri.encodeComponent(fullAddress);
    Uri googleMapUrl = Uri.parse(
        "https://www.google.com/maps/search/?api=1&query=$query");

    if (await canLaunchUrl(googleMapUrl)) {
      await launchUrl(googleMapUrl);
    } else {
      throw "无法打开地图";
    }
  }
}

更规范的Uri构造方式

除了用Uri.parse()解析字符串,还可以直接通过Uri类的构造方法来构建URL,这种方式能避免字符串拼接可能出现的编码问题:

// 经纬度方式的替代写法
Uri googleMapUrl = Uri(
  scheme: 'https',
  host: 'www.google.com',
  path: '/maps/search/',
  queryParameters: {
    'api': '1',
    'query': '$latitude,$longitude',
  },
);

// 地址方式的替代写法
Uri googleMapUrl = Uri(
  scheme: 'https',
  host: 'www.google.com',
  path: '/maps/search/',
  queryParameters: {
    'api': '1',
    'query': query,
  },
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:44:59