Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bring an app from background to foreground in flutter

Tags:

flutter

I have an app that is managing audio calls. When a call is made to the add and the app is running in the background I need to bring the app in the foreground state. I tried to use Navigator. push but without any result.

like image 418
Pricope Cosmin Avatar asked Jul 04 '19 21:07

Pricope Cosmin


2 Answers

You can use the package bringtoforeground. It's fairly in the early stages with respect to its version but it works.

iOS

But this only works on android, you have to keep in mind that iOS apps that are on the background are destroyed. you can read this do see details here

Android

So this implementation will only work on Android.

The best thing with this package is that you can use it with Firebase Cloud Messaging (FCM) or any other for that matter.

This is their example, Bringtoforeground.bringAppToForeground(); this is the piece of code you use to bring your app to the foreground.

import 'dart:async';

import 'package:bringtoforeground/bringtoforeground.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

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

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      Timer.periodic(Duration(seconds: 10), (t) {
        Bringtoforeground.bringAppToForeground(); //This is the only thing that matters
      });
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Running on: $_platformVersion\n'),
        ),
      ),
    );
  }
}
like image 131
Abel Tilahun Avatar answered Oct 21 '22 05:10

Abel Tilahun


Install flutter_foreground_task package here is

and use FlutterForegroundTask.minimizeApp() for app to background
and use FlutterForegroundTask.launchApp() for app to foreground that's all. I think it helps.

like image 1
Guray Meric Avatar answered Oct 21 '22 04:10

Guray Meric