Skip to main content

The background and foreground state of the app itself in Flutter

About the background and foreground state of the app itself in Flutter .

This is different from widget state — this is about the lifecycle of the entire app.

🔹 Foreground vs Background in Flutter

  • Foreground state → your app is visible on screen (user is actively using it).

  • Background state → user pressed Home, switched to another app, or screen is off (your app is running but not visible).

  • Terminated → user killed the app or system closed it.

🔹 Detecting App Lifecycle in Flutter

Flutter provides WidgetsBindingObserver or the AppLifecycleState enum.

Example: 

import 'package:flutter/material.dart';

class AppLifecycleExample extends StatefulWidget {
  @override
  _AppLifecycleExampleState createState() => _AppLifecycleExampleState();
}

class _AppLifecycleExampleState extends State<AppLifecycleExample>
    with WidgetsBindingObserver {
  AppLifecycleState? _lastState;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // start observing
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // stop observing
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _lastState = state;
    });

    if (state == AppLifecycleState.resumed) {
      print("App in FOREGROUND ✅");
      // resume API calls, restart timers, etc.
    } else if (state == AppLifecycleState.paused) {
      print("App in BACKGROUND 📴");
      // stop heavy tasks, pause audio/video, etc.
    } else if (state == AppLifecycleState.inactive) {
      print("App is inactive (e.g. during a phone call)");
    } else if (state == AppLifecycleState.detached) {
      print("App is detached (still running but UI detached)");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("Last state: $_lastState"),
      ),
    );
  }
}


🔹 AppLifecycleState Values

  1. resumed → App is visible & interactive (foreground).

  2. inactive → App is running but not in focus (e.g., during call, multitasking).

  3. paused → App is not visible (background).

  4. detached → App is still running in background, but UI is gone (rare case, before termination).


🔹 Example Use Cases

  • Foreground (resumed):

    • Resume API polling

    • Restart animations

    • Resume camera/video

  • Background (paused/inactive):

    • Stop API calls (save battery)

    • Pause music/video

    • Save form data locally

    • Cancel timers


Summary

  • Foreground → App is open & visible (resumed).

  • Background → App hidden but still running (paused).

  • Use WidgetsBindingObserver + didChangeAppLifecycleState to detect transitions.


Comments

Popular posts from this blog

How to write a code of Encode and Decode json data in Dart language

 Encode and decode JSON data in dart language import 'dart:convert'; void main() {   // Original data as a Dart map   Map<String, dynamic> originalData = {     'field1': 'value1',     'field2': 42,     'field3': true,   };   // Encode the Dart map to JSON string   String jsonString = jsonEncode(originalData);   print('Original JSON String:');   print(jsonString);   // Encode the JSON string to base64   String base64EncodedString = base64.encode(utf8.encode(jsonString));   print('\nBase64 Encoded String:');   print(base64EncodedString);   // Decode the base64 string to JSON string   String decodedJsonString = utf8.decode(base64.decode(base64EncodedString));   print('\nDecoded JSON String:');   print(decodedJsonString);   // Decode the JSON string to a Dart map   Map<String, dynamic> decodedData = jsonDecode(decodedJsonString);   print('\nDecoded Dart Ma...

About of Free Learning Tech Point

  Welcome to Free Learning Tech Point , where knowledge meets accessibility. Our platform is dedicated to providing high-quality educational resources and e-learning opportunities to learners around the world, completely free of charge. Our Mission: At Free Learning Tech Point, we believe that education is a fundamental right, and everyone should have access to valuable learning materials. Our mission is to break down barriers to education by offering a diverse range of courses, tutorials, and resources across various subjects and disciplines. What Sets Us Apart: - Free Access: Our commitment is to make learning accessible to all. No subscription fees, no hidden costs – just free, open access to knowledge.    - Quality Content: We curate and create content that is both engaging and informative. Whether you're a student, professional, or lifelong learner, our resources are designed to cater to various learning styles and levels. - Diverse Subjects: From tech and science...

Privacy Policy Of Free Learning Tech Point

  Thank you for visiting Free Learning Tech Point . You can use our website, services, and products with the awareness that this Privacy Policy describes how we gather, use, disclose, and protect your personal information. 1- Information We Collect: We may collect personal information that you provide directly to us, such as your name, email address, and any other information you choose to provide when using our Services. We may also collect non-personal information, such as aggregated data and usage patterns. 2- How We Use Your Information: We may use the information we collect for various purposes, including but not limited to: Providing and improving our Services. Responding to your inquiries and requests. Analyzing usage patterns and trends. Sending you updates, newsletters, and other communications. Personalizing your experience on our platform. 3- Cookies and Similar Technologies: We may use cookies and similar technologies to collect information about your interactions with...