0Pricing
Flutter Mobile Development · Leçon

Géolocalisation et plugins d’appareil photo

Intégrez des fonctionnalités courantes de l’appareil, comme les services de géolocalisation et l’accès à l’appareil photo, à l’aide de plugins Flutter éprouvés.

Géolocalisation et plugins d’appareil photo est une leçon Flutter Mobile Development gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Flutter Mobile Development, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Flutter Mobile Development comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Device Features & Plugins

Modern mobile apps often need to interact with device hardware like the camera or GPS. Flutter makes this easy using plugins.

Plugins are special packages that bridge Flutter (Dart) code with platform-specific (Android/iOS) native code. They let your app access device functionalities.

In this lesson, we'll integrate geolocation services and camera access into a Flutter app using popular, well-established plugins.

Accessing Device Location

To get the device's location, we'll use the geolocator plugin. It provides a simple API to access GPS, Wi-Fi, and cellular data for location information.

First, add the geolocator dependency to your pubspec.yaml file:

dependencies:
flutter:
sdk: flutter
geolocator: ^11.0.0 # Use the latest version

Then run flutter pub get in your terminal.

Requesting Location Permissions

Accessing a user's location requires their explicit permission. You need to declare these permissions in your app's native configuration files:

  • Android: Add ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION to AndroidManifest.xml.
  • iOS: Add NSLocationWhenInUseUsageDescription to Info.plist, explaining why your app needs location access.

The geolocator plugin will then handle requesting these permissions at runtime.

Building a Location Widget

Let's create a simple Flutter app structure to display location data. We'll use a StatefulWidget to manage and update the location text.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Location App',
      home: Scaffold(
        appBar: AppBar(title: const Text('My Location')),
        body: const Center(
          child: LocationDisplay(),
        ),
      ),
    );
  }
}

class LocationDisplay extends StatefulWidget {
  const LocationDisplay({super.key});

  @override
  State<LocationDisplay> createState() => _LocationDisplayState();
}

class _LocationDisplayState extends State<LocationDisplay> {
  String _locationMessage = 'Fetching location...';

  @override
  Widget build(BuildContext context) {
    return Text(_locationMessage);
  }
}

Fetching Current Position

Now, let's add the geolocator logic to our _LocationDisplayState. We'll use getCurrentPosition to get the device's coordinates.

Remember to handle potential service and permission issues before trying to get the location.

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Location App',
      home: Scaffold(
        appBar: AppBar(title: const Text('My Location')),
        body: const Center(
          child: LocationDisplay(),
        ),
      ),
    );
  }
}

class LocationDisplay extends StatefulWidget {
  const LocationDisplay({super.key});

  @override
  State<LocationDisplay> createState() => _LocationDisplayState();
}

class _LocationDisplayState extends State<LocationDisplay> {
  String _locationMessage = 'Fetching location...';

  @override
  void initState() {
    super.initState();
    _determinePosition();
  }

  Future<void> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      setState(() {
        _locationMessage = 'Location services are disabled.';
      });
      return;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        setState(() {
          _locationMessage = 'Location permissions are denied.';
        });
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      setState(() {
        _locationMessage = 'Location permissions denied forever.';
      });
      return;
    }

    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    setState(() {
      _locationMessage =
          'Lat: ${position.latitude}, Lon: ${position.longitude}';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(_locationMessage, textAlign: TextAlign.center),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: _determinePosition,
            child: const Text('Refresh Location'),
          ),
        ],
      ),
    );
  }
}

Capturing Photos & Videos

To interact with the device's camera or photo gallery, we'll use the image_picker plugin. It allows you to pick images/videos from the gallery or capture new ones.

Add image_picker to your pubspec.yaml:

dependencies:
flutter:
sdk: flutter
image_picker: ^1.0.0 # Use the latest version

Then run flutter pub get.

Camera & Gallery Permissions

Similar to geolocation, camera and gallery access require specific permissions. You need to configure these in your native project files:

  • Android: Add CAMERA and READ_EXTERNAL_STORAGE permissions to AndroidManifest.xml.
  • iOS: Add NSPhotoLibraryUsageDescription and NSCameraUsageDescription to Info.plist.

These descriptions explain to the user why your app needs these permissions.

Selecting from Gallery

Let's create a new widget to demonstrate picking an image from the gallery using image_picker. We'll display the selected image.

Tap the button to open your device's photo gallery.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Picker App',
      home: Scaffold(
        appBar: AppBar(title: const Text('Pick Image')),
        body: const Center(
          child: ImagePickerDisplay(),
        ),
      ),
    );
  }
}

class ImagePickerDisplay extends StatefulWidget {
  const ImagePickerDisplay({super.key});

  @override
  State<ImagePickerDisplay> createState() => _ImagePickerDisplayState();
}

class _ImagePickerDisplayState extends State<ImagePickerDisplay> {
  File? _image;
  final ImagePicker _picker = ImagePicker();

  Future<void> _pickImage() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _image = File(image.path);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _image == null
            ? const Text('No image selected.')
            : Image.file(_image!, height: 200),
        const SizedBox(height: 20),
        ElevatedButton(
          onPressed: _pickImage,
          child: const Text('Pick Image from Gallery'),
        ),
      ],
    );
  }
}

Capturing with Camera

Now, let's modify our app to also allow taking a photo directly with the device's camera.

The ImageSource.camera option is used for this.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Camera App',
      home: Scaffold(
        appBar: AppBar(title: const Text('Take Photo')),
        body: const Center(
          child: CameraDisplay(),
        ),
      ),
    );
  }
}

class CameraDisplay extends StatefulWidget {
  const CameraDisplay({super.key});

  @override
  State<CameraDisplay> createState() => _CameraDisplayState();
}

class _CameraDisplayState extends State<CameraDisplay> {
  File? _image;
  final ImagePicker _picker = ImagePicker();

  Future<void> _takePhoto() async {
    final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
    if (photo != null) {
      setState(() {
        _image = File(photo.path);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _image == null
            ? const Text('No photo taken.')
            : Image.file(_image!, height: 200),
        const SizedBox(height: 20),
        ElevatedButton(
          onPressed: _takePhoto,
          child: const Text('Take Photo with Camera'),
        ),
      ],
    );
  }
}

Robust Plugin Usage

When using plugins, always consider error handling. Wrap plugin calls in try-catch blocks to gracefully manage scenarios like:

  • User denying permissions.
  • Location services being disabled.
  • Camera not being available.

Plugins often provide options, like desiredAccuracy for geolocator or imageQuality for image_picker, to fine-tune behavior and optimize performance.

Plugin Permissions Check

You've learned about integrating device features and the importance of permissions. Let's test your understanding.

Summary of Device Features

Well done! You've learned how to integrate powerful device features into your Flutter apps:

  • Geolocation: Using geolocator to get the device's current position.
  • Camera/Gallery: Using image_picker to select images from the gallery or capture new photos.

Remember the importance of declaring and requesting permissions for these features to ensure a smooth user experience. Continue exploring other plugins for even more device capabilities!

Questions Fréquemment Posées

La leçon « Géolocalisation et plugins d’appareil photo » est-elle gratuite ?

Oui — le texte complet de « Géolocalisation et plugins d’appareil photo » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Flutter Mobile Development, passe à CoddyKit PRO. Le cours Flutter Mobile Development comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Géolocalisation et plugins d’appareil photo » ?

Intégrez des fonctionnalités courantes de l’appareil, comme les services de géolocalisation et l’accès à l’appareil photo, à l’aide de plugins Flutter éprouvés. Tu pratiques Flutter Mobile Development avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Flutter Mobile Development ?

Aucune expérience préalable n'est requise. Flutter Mobile Development sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.

Combien de temps prend la leçon « Géolocalisation et plugins d’appareil photo » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Flutter Mobile Development ?

Oui. Chaque leçon Flutter Mobile Development inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Canaux de plateforme (MethodChannel)
  2. Géolocalisation et plugins d’appareil photo
  3. Intégration de l’interface native
  4. Autorisations et capteurs
← Retour à Flutter Mobile Development