Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 73 ยท Platform integration

Camera, Location, Permissions and Notifications

Use device features in Flutter: ask for permissions with permission_handler, pick photos, read location, show local and push notifications, and handle platform differences.

Phones are valuable because of what they can sense and do: take pictures, know where they are, and tap you on the shoulder with a notification. Each of these touches private data, so the operating system guards it with permissions, and each is wrapped in a Flutter plugin that talks to native code through platform channels.

This lesson shows the packages most apps use, the permission flow that all of them share, and how Android and iOS differ. The common idea is a small state machine, which you can try below.

Real vs stand-in. All Dart, XML and plist snippets are real and read-only here: the site cannot access a camera, GPS or notification center. The live examples are JavaScript stand-ins of the permission state machine and the notification scheduling logic, both plain logic you can test without a device. Package versions change often, so check pub.dev for current APIs.

Common packages

permission_handler Ask and check permissions.
image_picker Camera or gallery photo.
geolocator Position and updates.
flutter_local_notifications Notices from inside the app.
1 / 2

Permissions: the shared state machine

A permission is not a yes/no flag. With permission_handler, Permission.camera.status returns a PermissionStatus:

Status Meaning
denied Not granted yet, or refused once. You may ask again.
granted Allowed.
permanentlyDenied The user chose "don't ask again" (or Android refused twice). The system prompt will not appear: send them to settings.
restricted iOS: a parental or device policy blocks it.
limited iOS: partial photo access.
provisional iOS notifications delivered quietly.
DART
Future<bool> ensureCameraPermission(BuildContext context) async {
  var status = await Permission.camera.status;
  if (status.isGranted) return true;

  if (status.isPermanentlyDenied) {
    if (!context.mounted) return false;
    final open = await showDialog<bool>(
      context: context,
      builder: (_) => const AlertDialog(
        title: Text('Camera is off'),
        content: Text('Enable the camera for this app in Settings to scan codes.'),
        actions: [/* Cancel and Open settings */],
      ),
    );
    if (open == true) await openAppSettings();
    return false;
  }

  status = await Permission.camera.request();   // shows the system dialog
  return status.isGranted;
}

Two rules make users trust you: ask in context (when they tap "Scan", not at launch), and explain first when the reason isn't obvious. After await, check context.mounted as in Navigator and Routes.

Stand-in: the permission machine

JS Request, denial and permanent denial

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The third request never shows a dialog. A real app must not call request() in a loop expecting a prompt; it must branch on permanentlyDenied.

Platform setup is part of the job

Packages do nothing until the native projects declare what the app needs. A missing line is the number one reason "it works on Android but crashes on iOS".

Android (android/app/src/main/AndroidManifest.xml):

XML
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

iOS (ios/Runner/Info.plist): every permission needs a human-readable reason, and the App Store rejects vague or missing ones.

XML
<key>NSCameraUsageDescription</key>
<string>The camera is used to scan ticket codes.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Your location is used to show nearby stores.</string>

permission_handler on iOS also needs matching PERMISSION_* macros in the Podfile; the package README lists them. Android 13 and later asks for notification permission at runtime (POST_NOTIFICATIONS); older versions do not.

Camera and photos

For "pick a photo or take one", image_picker is the shortest path and does not need you to manage the camera yourself. It also does not need camera permission on most platforms, since it launches the system UI.

DART
final picker = ImagePicker();
final XFile? photo = await picker.pickImage(
  source: ImageSource.camera,   // or ImageSource.gallery
  maxWidth: 1600,
  imageQuality: 85,
);
if (photo == null) return;                    // user cancelled
setState(() => _file = File(photo.path));     // use Image.file(_file!) to show it

Resize on pick (maxWidth, imageQuality) so you do not upload 12-megapixel files. When you need a live preview, barcode scanning or custom controls, use the camera package, which gives a CameraController and a CameraPreview widget, and which does need camera permission. Always dispose the controller. On the web, the file picker is the browser's own.

image_picker can do more than one photo. Pick several images, a video, or recover from Android killing your app while the camera was open:

DART
final picker = ImagePicker();

final List<XFile> many = await picker.pickMultiImage(limit: 6, imageQuality: 80);
final XFile? clip = await picker.pickVideo(source: ImageSource.gallery, maxDuration: const Duration(seconds: 30));

// Android may destroy your Activity while the camera app is in front.
// On the next launch, ask whether a pick was in flight:
final LostDataResponse lost = await picker.retrieveLostData();
if (!lost.isEmpty && lost.file != null) {
  setState(() => _photos.add(lost.file!));
}

Show a gallery as a GridView of thumbnails, and decode them small. Passing cacheWidth to Image.file keeps a 12-megapixel picture from being decoded at full size for a 120-pixel tile (image caching):

DART
GridView.builder(
  gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 120, mainAxisSpacing: 4, crossAxisSpacing: 4),
  itemCount: _photos.length,
  itemBuilder: (_, i) => Image.file(File(_photos[i].path), fit: BoxFit.cover, cacheWidth: 240),
)

When you need a live preview, scanning or custom controls, use the camera package. Its lifecycle has four steps, and skipping one is the usual bug:

DART
class _ShooterState extends State<Shooter> with WidgetsBindingObserver {
  CameraController? _camera;

  Future<void> _start() async {
    final cameras = await availableCameras();
    final controller = CameraController(cameras.first, ResolutionPreset.medium, enableAudio: false);
    await controller.initialize();                      // permission prompt happens here
    if (!mounted) { await controller.dispose(); return; }
    setState(() => _camera = controller);
  }

  Future<void> _snap() async {
    final XFile shot = await _camera!.takePicture();
    // compress, upload or show shot.path
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    final controller = _camera;
    if (controller == null || !controller.value.isInitialized) return;
    if (state == AppLifecycleState.inactive) {
      controller.dispose();                            // release the camera in the background
      setState(() => _camera = null);
    } else if (state == AppLifecycleState.resumed) {
      _start();
    }
  }

  @override
  Widget build(BuildContext context) {
    final c = _camera;
    if (c == null || !c.value.isInitialized) return const Center(child: CircularProgressIndicator());
    return CameraPreview(c);
  }
}

Register the observer in initState with WidgetsBinding.instance.addObserver(this), remove it in dispose, and dispose the controller. A camera handed to the background without being released blocks other apps from using it. Large pictures should be resized or compressed before upload (see Projects: Fitness, Event Calendar, Image Compressor, Portfolio).

JS Camera controller lifecycle

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Location

DART
Future<Position?> currentPosition() async {
  if (!await Geolocator.isLocationServiceEnabled()) return null;   // GPS switched off

  var permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
  }
  if (permission == LocationPermission.denied ||
      permission == LocationPermission.deniedForever) {
    return null;
  }
  return Geolocator.getCurrentPosition(
    locationSettings: const LocationSettings(accuracy: LocationAccuracy.high),
  );
}

Stream<Position> track() => Geolocator.getPositionStream(
  locationSettings: const LocationSettings(accuracy: LocationAccuracy.high, distanceFilter: 25),
);

Three layers must agree: the device's location service must be on, the app must hold permission, and you must pick an accuracy suited to the job. High accuracy costs battery; distanceFilter limits updates to every 25 meters. "Always" (background) location is a separate, stricter permission with extra store review, so ask for "while in use" unless you truly need more. A position stream is consumed like any other stream (StreamBuilder); cancel the subscription in dispose.

Local notifications

A local notification is scheduled by the app itself on the device: reminders, timers, alarms. With flutter_local_notifications you initialize once, create an Android channel (user-visible category, importance), then show or schedule:

DART
final plugin = FlutterLocalNotificationsPlugin();

Future<void> init() async {
  const settings = InitializationSettings(
    android: AndroidInitializationSettings('@mipmap/ic_launcher'),
    iOS: DarwinInitializationSettings(),
  );
  await plugin.initialize(settings, onDidReceiveNotificationResponse: (r) {
    // user tapped: r.payload tells you where to navigate
  });
}

Future<void> remindIn(Duration delay, String text) => plugin.zonedSchedule(
  1,
  'Reminder',
  text,
  tz.TZDateTime.now(tz.local).add(delay),
  const NotificationDetails(
    android: AndroidNotificationDetails('reminders', 'Reminders', importance: Importance.high),
    iOS: DarwinNotificationDetails(),
  ),
  androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
  payload: '/tasks/42',
);

Scheduling uses time zones (timezone package) so a "9:00 daily" reminder stays at 9:00 after the clock changes. Exact alarms are a restricted capability on newer Android: prefer inexact unless the user expects precision.

JS Stand-in: a notification scheduler

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Push notifications

A push notification comes from a server through the platform's service: Firebase Cloud Messaging (FCM) on Android, and FCM relaying through Apple Push Notification service (APNs) on iOS. Your app gets a device token, sends it to your backend, and the backend sends messages to that token or to a topic. The setup is in Firebase: Auth, Firestore and Cloud Messaging.

Three states matter: the app in the foreground (you decide whether to display something yourself), in the background (the system shows the notification, tapping opens the app), and terminated (same, but you read the initial message on launch). On iOS you need an Apple developer account, push capability and an APNs key; simulators cannot receive real pushes on older setups.

Repeating reminders and background work

A daily reminder does not need a server. flutter_local_notifications repeats a scheduled notification when you tell it which part of the time to match:

DART
await plugin.zonedSchedule(
  7,
  'Time to stretch',
  'Two minutes is enough.',
  _nextInstanceOf(9, 0),                                  // the next 09:00 in the user's zone
  const NotificationDetails(android: AndroidNotificationDetails('daily', 'Daily reminders')),
  androidScheduleMode: AndroidScheduleMode.inexactAllowWhileIdle,
  matchDateTimeComponents: DateTimeComponents.time,       // repeat every day at this time
);

tz.TZDateTime _nextInstanceOf(int hour, int minute) {
  final now = tz.TZDateTime.now(tz.local);
  var when = tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, minute);
  if (when.isBefore(now)) when = when.add(const Duration(days: 1));
  return when;
}

DateTimeComponents.dayOfWeekAndTime repeats weekly. Android may hold back "inexact" alarms to save battery, and some manufacturers aggressively stop apps; scheduling after a reboot needs the plugin's boot receiver configured.

Background work is code that runs when your app is not on screen: syncing, uploading, cleanup. The workmanager package schedules it using Android WorkManager and iOS background tasks. The task runs in its own isolate, so it cannot touch your widgets or in-memory state:

DART
@pragma('vm:entry-point')                                // keeps the function from being tree-shaken
void callbackDispatcher() {
  Workmanager().executeTask((taskName, inputData) async {
    await SyncService().syncPending();                   // plain Dart, no UI
    return true;                                         // false asks the system to retry
  });
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Workmanager().initialize(callbackDispatcher);
  await Workmanager().registerPeriodicTask(
    'sync-1', 'syncPending',
    frequency: const Duration(hours: 1),
    constraints: Constraints(networkType: NetworkType.connected),
  );
  runApp(const MyApp());
}

Be realistic about guarantees. Android's minimum repeat interval is 15 minutes and the system picks the exact moment; iOS gives no promise at all, decides based on how often the user opens the app, and may skip runs. Do not depend on background tasks for anything time-critical: use a server push (Firebase) for that.

JS Next fire time and the 15-minute minimum

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Platform differences at a glance

  • Android asks for notification permission only from version 13; iOS always asks.
  • iOS lets the user pick limited photo access; Android uses the system photo picker.
  • iOS gives one prompt per permission, and later changes only happen in Settings; Android's second denial can become permanent.
  • Web and desktop support differs per package: always check the "platforms" badge on pub.dev and handle MissingPluginException.
  • Test on real devices. Emulators have fake sensors, no push on iOS simulators in older setups, and different permission behavior.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user tapped 'Don't ask again'. What does the permission status read, and what should the app do?

    The system prompt will not appear again. The only path is the settings screen, which openAppSettings() opens.
  2. 2. When is the best moment to request camera permission?

    Asking in context shows the reason and gets a better acceptance rate.
  3. 3. What must iOS projects contain for camera access?

    iOS requires a usage description string per permission; missing or vague text crashes the app or fails review.
  4. 4. What is the difference between a local and a push notification?

    A push needs a backend and a device token; a local one needs only the device.

Summary

  • Permissions are a state machine (denied, granted, permanently denied, restricted); ask in context and handle denial.
  • Android manifest entries and iOS Info.plist descriptions are required for every feature.
  • image_picker is the simple route for photos; camera is for live previews; geolocator needs service, permission and an accuracy choice.
  • Local notifications are scheduled on the device with channels and time zones; push comes from a backend through FCM or APNs.
  • Always test on real devices and handle platforms where a plugin is missing.

Next: Firebase: Auth, Firestore and Cloud Messaging