繁体   English   中英

在 Flutter 中使用 URL 启动器无法打开 Google 地图

[英]Google maps wont open using URL launcher in Flutter

我对 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'),
        ),
      ],
    ),
  ),
);
}
}

这是因为您错误地调用了 function。 您正在使用await canLaunch(googleUrl); 而不是await launch(googleUrl); if部分。

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

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<void>因此,将 function 名称更改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM