Thiết lập dự án Flutter

Trước khi thiết lập một dự án Flutter, hãy đảm bảo bạn đã hoàn tất các bước tiên quyết trong phần Trước khi bắt đầu. Sau khi bật tính năng thanh toán và tạo khoá API, bạn có thể thiết lập dự án Flutter mà bạn dùng để phát triển ứng dụng.

Bước 1: Cài đặt phần mềm cần thiết

Để xây dựng một dự án bằng gói Google Maps dành cho Flutter, bạn phải cài đặt SDK Flutter và thiết lập môi trường phát triển cho nền tảng mục tiêu. Hãy xem Hướng dẫn cài đặt Flutter để biết thông tin chi tiết.

Bước 2: Cài đặt gói Google Maps dành cho Flutter trong một dự án mới

Flutter cung cấp gói Google Maps dành cho Flutter dưới dạng một trình bổ trợ Flutter.

Tạo dự án Flutter rồi thêm trình bổ trợ Maps.

  1. Tạo một dự án Flutter mới bằng tính năng "flutter create" ("tạo flutter create"):
      flutter create google_maps_in_flutter --platforms=android,ios,web
      
      Creating project google_maps_in_flutter...
      [Listing of created files elided]
      Wrote 127 files.
    
      All done!
    Mã xử lý ứng dụng của bạn nằm trong google_maps_in_flutter/lib/main.dart. Để chạy ứng dụng, hãy nhập:
      cd google_maps_in_flutter
      flutter run
    Ứng dụng này nhắm đến iOS, Android và Web. SDK Google Maps không hỗ trợ các ứng dụng dành cho máy tính bên ngoài trình duyệt tại thời điểm này.
  2. Thêm trình bổ trợ gói Google Maps dành cho Flutter vào dự án này.
    flutter pub add google_maps_flutter
      
      Resolving dependencies...
      [Listing of dependencies elided]
    
      Changed 14 dependencies!

Bước 3: Đặt phiên bản nền tảng

Android

Thiết lập phiên bản SDK tối thiểu cho Android.

  1. Mở tệp cấu hình android/app/build.gradle trong IDE ưa thích của bạn.
  2. Thay đổi giá trị của android.defaultConfig.minSdkVersion thành 21:
      android {
        //...
        defaultConfig {
            applicationId "com.example.google_maps_in_flutter"
            minSdkVersion 21     // Set to 21
            targetSdkVersion flutter.targetSdkVersion
            versionCode flutterVersionCode.toInteger()
            versionName flutterVersionName
        }
        //...
      }
  3. Khi định cấu hình defaultConfig, hãy chỉ định ApplicationID duy nhất của riêng bạn.
  4. Lưu tệp và đồng bộ hoá các thay đổi của dự án với Gradle.

iOS

Đặt phiên bản nền tảng iOS tối thiểu.

  1. Mở tệp cấu hình ios/Podfile trong IDE ưa thích của bạn.
  2. Thêm các dòng sau vào đầu Podfile này:
      # Set platform to 14.0 to enable latest Google Maps SDK
      platform :ios, '14.0'

Bước 4: Thêm khoá API vào dự án

Trong phần Trước khi bắt đầu, bạn đã tạo một khoá API cho ứng dụng của mình. Bây giờ, hãy thêm khoá đó vào dự án Flutter. Đối với Flutter, bạn nên thêm khoá API này vào tất cả các nền tảng đích: iOS, Android và Web.

Trong các ví dụ sau, hãy thay thế YOUR_API_KEY bằng khoá API.

Android

Để đơn giản hoá tác vụ này, bạn nên sử dụng Trình bổ trợ Bí mật cho Gradle cho Android.

Cách cài đặt Trình bổ trợ Secrets Gradle cho Android trong dự án Google Maps:

  1. Trong Android Studio, hãy mở tệp build.gradle hoặc build.gradle.kts cấp cao nhất rồi thêm mã sau vào phần tử dependencies trong buildscript.

    Groovy

    buildscript {
        dependencies {
            classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1"
        }
    }

    Kotlin

    buildscript {
        dependencies {
            classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1")
        }
    }
    
  2. Mở tệp build.gradle ở cấp mô-đun và thêm mã sau vào phần tử plugins.

    Groovy

    plugins {
        // ...
        id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    }

    Kotlin

    plugins {
        id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")
    }
  3. Trong tệp build.gradle ở cấp mô-đun, hãy đảm bảo rằng targetSdkcompileSdk được đặt thành 34.
  4. Lưu tệp và đồng bộ hoá dự án của bạn với Gradle.
  5. Mở tệp secrets.properties trong thư mục cấp cao nhất của bạn, sau đó thêm mã sau. Thay thế YOUR_API_KEY bằng khoá API. Lưu trữ khoá của bạn trong tệp này vì secrets.properties không được phép kiểm tra trong một hệ thống quản lý phiên bản.
    MAPS_API_KEY=YOUR_API_KEY
  6. Lưu tệp.
  7. Tạo tệp local.defaults.properties trong thư mục cấp cao nhất, cùng thư mục với tệp secrets.properties, sau đó thêm mã sau.

    MAPS_API_KEY=DEFAULT_API_KEY

    Mục đích của tệp này là cung cấp vị trí sao lưu cho khoá API nếu không tìm thấy tệp secrets.properties để các bản dựng không bị lỗi. Điều này có thể xảy ra nếu bạn sao chép ứng dụng từ một hệ thống quản lý phiên bản, trong đó bỏ qua secrets.properties và bạn chưa tạo tệp secrets.properties cục bộ để cung cấp khoá API của mình.

  8. Lưu tệp.
  9. Trong tệp AndroidManifest.xml, hãy chuyển đến com.google.android.geo.API_KEY rồi cập nhật android:value attribute. Nếu thẻ <meta-data> không tồn tại, hãy tạo thẻ này làm thẻ con của thẻ <application>.
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="${MAPS_API_KEY}" />

    Note: com.google.android.geo.API_KEY is the recommended metadata name for the API key. A key with this name can be used to authenticate to multiple Google Maps-based APIs on the Android platform, including the Flutter SDK. For backwards compatibility, the API also supports the name com.google.android.maps.v2.API_KEY. This legacy name allows authentication to the Android Maps API v2 only. An application can specify only one of the API key metadata names. If both are specified, the API throws an exception.

  10. In Android Studio, open your module-level build.gradle or build.gradle.kts file and edit the secrets property. If the secrets property does not exist, add it.

    Edit the properties of the plugin to set propertiesFileName to secrets.properties, set defaultPropertiesFileName to local.defaults.properties, and set any other properties.

    Groovy

    secrets {
        // Optionally specify a different file name containing your secrets.
        // The plugin defaults to "local.properties"
        propertiesFileName = "secrets.properties"
    
        // A properties file containing default secret values. This file can be
        // checked in version control.
        defaultPropertiesFileName = "local.defaults.properties"
    
        // Configure which keys should be ignored by the plugin by providing regular expressions.
        // "sdk.dir" is ignored by default.
        ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
        ignoreList.add("sdk.*")       // Ignore all keys matching the regexp "sdk.*"
    }
            

Kotlin

secrets {
    // Optionally specify a different file name containing your secrets.
    // The plugin defaults to "local.properties"
    propertiesFileName = "secrets.properties"

    // A properties file containing default secret values. This file can be
    // checked in version control.
    defaultPropertiesFileName = "local.defaults.properties"

    // Configure which keys should be ignored by the plugin by providing regular expressions.
    // "sdk.dir" is ignored by default.
    ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
    ignoreList.add("sdk.*")       // Ignore all keys matching the regexp "sdk.*"
}
        

Lưu ý: Như đã trình bày ở trên, com.google.android.geo.API_KEY là tên siêu dữ liệu nên dùng cho khoá API. Khoá có tên này có thể dùng để xác thực nhiều API dựa trên Google Maps trên nền tảng Android, bao gồm cả SDK Flutter. Để có khả năng tương thích ngược, API cũng hỗ trợ tên com.google.android.maps.v2.API_KEY. Tên cũ này chỉ cho phép xác thực với API Android Maps phiên bản 2. Một ứng dụng chỉ có thể chỉ định một trong các tên siêu dữ liệu của khoá API. Nếu bạn chỉ định cả hai, thì API sẽ gửi ra một ngoại lệ.

iOS

Thêm khoá API vào tệp AppDelegate.swift.

  1. Mở tệp ios/Runner/AppDelegate.swift trong dự án Flutter bằng IDE mà bạn muốn.
  2. Thêm câu lệnh nhập sau để thêm gói Google Maps dành cho Flutter vào ứng dụng của bạn:
  3. import GoogleMaps
  4. Thêm API vào phương thức application(_:didFinishLaunchingWithOptions:), thay thế khoá API bằng YOUR_API_KEY:
    GMSServices.provideAPIKey("YOUR_API_KEY")
  5. Lưu rồi đóng tệp AppDelegate.swift.

Tệp AppDelegate.swift hoàn chỉnh sẽ có dạng như sau:

import UIKit
import Flutter
import GoogleMaps  // Add this import

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)

    // TODO: Add your Google Maps API key
    GMSServices.provideAPIKey("YOUR_API_KEY")

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Web

Thêm khoá API vào tệp ứng dụng index.html.

  1. Mở tệp web/index.html trong dự án Flutter bằng IDE mà bạn muốn.
  2. Thêm thẻ tập lệnh sau đây vào thẻ <head>, thay thế khoá API bằng YOUR_API_KEY.
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "YOUR_API_KEY",
        v: "weekly",
        // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
        // Add other bootstrap parameters as needed, using camel case.
      });
    </script>
    
  3. Lưu rồi đóng tệp index.html.

    Phần head hoàn chỉnh của index.html sẽ có dạng như sau:

        <head>
          <base href="/">
          
          <meta charset="UTF-8">
          <meta content="IE=Edge" http-equiv="X-UA-Compatible">
          <meta name="description" content="A new Flutter project.">
          
          <!-- iOS meta tags & icons -->
          <meta name="apple-mobile-web-app-capable" content="yes">
          <meta name="apple-mobile-web-app-status-bar-style" content="black">
          <meta name="apple-mobile-web-app-title" content="google_maps_in_flutter">
          <link rel="apple-touch-icon" href="icons/Icon-192.png">
          
          <script>
            (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
              key: "YOUR_API_KEY",
              v: "weekly",
              // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
              // Add other bootstrap parameters as needed, using camel case.
              });
          </script>
          
          <title>google_maps_in_flutter</title>
          <link rel="manifest" href="manifest.json">
        </head>

Bước 5: Thêm bản đồ

Mã sau đây minh hoạ cách thêm một bản đồ đơn giản vào một ứng dụng Flutter mới.

  1. Mở tệp lib/main.dart trong dự án Flutter bằng IDE mà bạn muốn.
  2. Thêm hoặc cập nhật các phương thức trong phương thức chính mặc định của ứng dụng để tạo và khởi chạy một thực thể của mapController.
          import 'package:flutter/material.dart';
          import 'package:google_maps_flutter/google_maps_flutter.dart';
          
          void main() => runApp(const MyApp());
          
          class MyApp extends StatefulWidget {
            const MyApp({super.key});
          
            @override
            State<MyApp> createState() => _MyAppState();
          }
          
          class _MyAppState extends State<MyApp> {
            late GoogleMapController mapController;
          
            final LatLng _center = const LatLng(-33.86, 151.20);
          
            void _onMapCreated(GoogleMapController controller) {
              mapController = controller;
            }
          
            @override
            Widget build(BuildContext context) {
              return MaterialApp(
                home: Scaffold(
                  appBar: AppBar(
                    title: const Text('Maps Sample App'),
                    backgroundColor: Colors.green[700],
                  ),
                  body: GoogleMap(
                    onMapCreated: _onMapCreated,
                    initialCameraPosition: CameraPosition(
                      target: _center,
                      zoom: 11.0,
                    ),
                  ),
                ),
              );
            }
          }
  3. Khởi động trình mô phỏng hoặc thiết bị bất kỳ mà bạn muốn chạy ứng dụng.
  4. Chạy ứng dụng. Bạn sẽ thấy kết quả tương tự như sau:
      flutter run
    
       
        Multiple devices found:
        Android phone (mobile) • emulator-5554 • android-arm64  • Android 13 (API 33) (emulator)
        iPhone (mobile)  • ios • com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator)
        Chrome (web) • chrome • web-javascript • Google Chrome 108.0.5359.124
        [1]: Android phone
        [2]: iPhone
        [3]: Chrome
        
        Please choose one (To quit, press "q/Q"): 

    Nhập số nền tảng bạn muốn chạy. Mỗi lần bạn gọi flutter run, Flutter sẽ hiển thị cho bạn các lựa chọn này. Nếu hệ thống phát triển của bạn không có trình mô phỏng đang chạy hoặc thiết bị thử nghiệm được kết nối, Flutter nên chọn mở Chrome.

    Mỗi nền tảng phải hiển thị một bản đồ ở trung tâm Sydney, Úc. Nếu không thấy bản đồ, hãy kiểm tra để chắc chắn rằng bạn đã thêm khoá API vào dự án mục tiêu phù hợp.

Các bước tiếp theo

Giờ đây, khi đã có khoá API và một dự án Flutter, bạn có thể tạo và chạy các ứng dụng. Gói Google Maps dành cho Flutter cung cấp nhiều hướng dẫn và ứng dụng mẫu có thể giúp bạn bắt đầu. Để tìm hiểu thêm, hãy xem các tài nguyên sau: