【问题标题】:Google maps wont open using URL launcher in Flutter谷歌地图无法在 Flutter 中使用 URL 启动器打开
【发布时间】:2021-02-15 06:46:05
【问题描述】:

我是 Flutter 的新手。

我创建了一个应用程序,它应该在点击时打开谷歌地图,但它不会打开。 请帮帮我。

forMap.dart 文件(这是有启动谷歌地图方法的文件):

import 'package:url_launcher/url_launcher.dart';

class MapUtils {
  MapUtils._();

  static Future<void>openMap(double latitude,double longitude) async {
    String googleUrl = 'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude';
    if(await canLaunch(googleUrl) != null) {
      await canLaunch(googleUrl);
    } else {
      throw 'Could not open the map.';
   }
 }

}

main.dart 文件(这是将使用forMap.dart 文件的方法并启动它的文件):

import 'package:flutter/material.dart';

import 'forMap.dart';

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

 class MyApp extends StatelessWidget {
 // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
     title: 'Flutter Demo',
      theme: ThemeData(
      primarySwatch: Colors.blue,
      visualDensity: VisualDensity.adaptivePlatformDensity,
   ),
   home: MyHomePage(title: 'Flutter Demo Home Page'),
   );
 }
}

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

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

class _MyHomePageState extends State<MyHomePage> {


 @override
 Widget build(BuildContext context) {
   return Scaffold(
   appBar: AppBar(
    ),
   body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        InkWell(
          onTap: (){
            MapUtils.openMap(38.8977,77.0365);
          },
          child: Text('get map'),
        ),
      ],
    ),
  ),
);
}
}

【问题讨论】:

    标签: flutter google-maps dart url


    【解决方案1】:

    这是因为你错误地调用了一个函数。您在 if 部分使用 await canLaunch(googleUrl); 而不是 await launch(googleUrl);

    所以,你的代码应该是这样的:

    static Future<void> openMap(double latitude,double longitude) async {
      String googleUrl = 'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude';
      if(await canLaunch(googleUrl) != null) {
        await launch(googleUrl);
      } else {
        throw 'Could not open the map.';
      }
    }
    

    你可能不需要使用Future&lt;void&gt; 所以,把函数名改成:

    static void openMap(double latitude,double longitude) async {
      ...
    }
    

    【讨论】:

    • 你好,是否可以不使用经纬度,直接打开带有街道名称的启动器?感谢先进
    • 是的,可以直接用街道名称打开启动器。在此处查看docs 以获取信息。
    猜你喜欢
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    相关资源
    最近更新 更多