How to bring an app from background to foreground in flutter - 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.

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'),
),
),
);
}
}

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.

if you work with flutter_local_notifications package
you can add this argument to AndroidNotificationAction
from here
hope this help (:

Related

how to view pptx file inside my app in flutter

I list all pptx files from storage now I want to display these files inside my app using a file path. I used different packages like power file view, flutter file reader. but engine load failed all time so i need a material related opening pptx files inside my flutter app
Add this in your pubspec.yaml
pdftron_flutter:
git:
url: git://github.com/PDFTron/pdftron-flutter.git
main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:pdftron_flutter/pdftron_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _version = 'Unknown';
#override
void initState() {
super.initState();
initPlatformState();
PdftronFlutter.openDocument("https://pdftron.s3.amazonaws.com/downloads/pdfref.pdf");
}
// Platform messages are asynchronous, so we initialize via an async method.
Future<void> initPlatformState() async {
String version;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
PdftronFlutter.initialize();
version = await PdftronFlutter.version;
} on PlatformException {
version = '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(() {
_version = version;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('PDFTron flutter app'),
),
body: Center(
child: Text('Running on: $_version\n'),
),
),
);
}
}
For more help read this blog

how to get mobile number in flutter

I am using "mobile_number(version - 1.0.3)" plugin to get mobile number in flutter app, am running in original device but i couldn't get mobile number.instead of errors i can get mobile number as null along with other sim details as shown in screen shot.
help me to resolve this problem, i had just copy pasted the example given by plugin that is the code
plugin link
It says:
Note: If the mobile number is not pre-exist on sim card it will not return te phone number.
I think mobile number does not pre-exist on the SIM if the SIM is not original (i.e. replaced)
If the phone number isn't stored on the sim (aka null), then you can't get it from anywhere else, in that case you probably want to forward the user to a different page where they can type the phone number using TextField and then store it somewhere
Use Mobile_number package to get mobile number and other details. For example
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mobile_number/mobile_number.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _mobileNumber = '';
List<SimCard> _simCard = <SimCard>[];
#override
void initState() {
super.initState();
MobileNumber.listenPhonePermission((isPermissionGranted) {
if (isPermissionGranted) {
initMobileNumberState();
} else {}
});
initMobileNumberState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initMobileNumberState() async {
if (!await MobileNumber.hasPhonePermission) {
await MobileNumber.requestPhonePermission;
return;
}
String mobileNumber = '';
// Platform messages may fail, so we use a try/catch PlatformException.
try {
mobileNumber = (await MobileNumber.mobileNumber)!;
_simCard = (await MobileNumber.getSimCards)!;
} on PlatformException catch (e) {
debugPrint("Failed to get mobile number because of '${e.message}'");
}
// 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(() {
_mobileNumber = mobileNumber;
});
}
Widget fillCards() {
List<Widget> widgets = _simCard
.map((SimCard sim) => Text(
'Sim Card Number: (${sim.countryPhonePrefix}) - ${sim.number}\nCarrier Name: ${sim.carrierName}\nCountry Iso: ${sim.countryIso}\nDisplay Name: ${sim.displayName}\nSim Slot Index: ${sim.slotIndex}\n\n'))
.toList();
return Column(children: widgets);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text('Running on: $_mobileNumber\n'),
fillCards()
],
),
),
),
);
}
}

How to generate Pre Launch report for Flutter App?

I have a login screen which uses phone authentication for creating account.
I have used Firebase Phone auth for login and also have stored one number for testing purpose.
But don't know how to pass the number and OTP to generate Pre Launch Report.
They are asking for Username, Username Resource ID, Password , Password Resource ID.
Where to find Resource ID for username and password fields in flutter code.
In the Google play console at the bottom of the left
Click on App content
Click on App access
Click on manage
Click on add new instructions
Add your all details here it should be test accounts
Try this :
dependencies:
flutter_runtime_env: ^0.0.4
Example:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_runtime_env/flutter_runtime_env.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isInFirebaseTestLab = false;
#override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
var result = await inFirebaseTestLab();
setState(() {
_isInFirebaseTestLab = result;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('is in FirebaseTest Lab'),
),
body: Center(
child: Text('is in FirebaseTest Lab: $_isInFirebaseTestLab\n'),
),
),
);
}
}

How to detect mock location in flutter for ios and android

I am using package of location and google maps flutter in my screen and I want to detect wether user using fake gps or not.. Is there a package that can detect mock location in flutter that available in android and ios? I have tried using TrustFall package but my app always close unexpectedly.. is there another way to detect mock location in flutter?
Use Geolocator and check the Position object's isMocked property.
you can use TrustLocation
permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
usage :
import 'package:trust_location/trust_location.dart';
/* Assuming in an async function */
/// query the current location.
LatLongPosition position = await TrustLocation.getLatLong;
/// check mock location on Android device.
bool isMockLocation = await TrustLocation.isMockLocation;
using steam:
// input seconds into parameter for getting location with repeating by timer.
// this example set to 5 seconds.
TrustLocation.start(5);
/// the stream getter where others can listen to.
TrustLocation.onChange.listen((values) =>
print('${values.latitude} ${values.longitude} ${values.isMockLocation}')
);
/// stop repeating by timer
TrustLocation.stop();
Example:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:trust_location/trust_location.dart';
import 'package:location_permissions/location_permissions.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _latitude;
String _longitude;
bool _isMockLocation;
/// initialize state.
#override
void initState() {
super.initState();
requestLocationPermission();
// input seconds into parameter for getting location with repeating by timer.
// this example set to 5 seconds.
TrustLocation.start(5);
getLocation();
}
/// get location method, use a try/catch PlatformException.
Future<void> getLocation() async {
try {
TrustLocation.onChange.listen((values) => setState(() {
_latitude = values.latitude;
_longitude = values.longitude;
_isMockLocation = values.isMockLocation;
}));
} on PlatformException catch (e) {
print('PlatformException $e');
}
}
/// request location permission at runtime.
void requestLocationPermission() async {
PermissionStatus permission =
await LocationPermissions().requestPermissions();
print('permissions: $permission');
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Trust Location Plugin'),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Center(
child: Column(
children: <Widget>[
Text('Mock Location: $_isMockLocation'),
Text('Latitude: $_latitude, Longitude: $_longitude'),
],
)),
),
),
);
}
}
for more information you can see https://pub.dev/packages/trust_location
github link : https://github.com/wongpiwat/trust-location
I think better to use safe_device. It's working on both Android and IOS

How to detect phone shakes in Flutter

Just started with Flutter this weekend and am making great progress.
I have an app that simply changes the image on screen when the image is tapped, or, if the phone is shaken. The first part was simple, and on tap, my images change. Struggling with the shake part.
Been looking at the Sensors package, but am not having much luck (possibly because i don't fully understand what i'm looking for!). Do I just want the app to listen for when a certain accelerometer change happens, and if so, run my change image function? If so, what is the best way to do this?
Any other ideas welcome!
Thanks all :)
Update: This is what I have so far, pretty much exactly what I read from the Shake documentation. But nothing is happening on shake.
import 'package:flutter/material.dart';
import 'package:shake/shake.dart';
void main() {
runApp(DemoPage());
}
String mytext = "Martini?";
class DemoPage extends StatefulWidget {
#override
_DemoPageState createState() => _DemoPageState();
}
class _DemoPageState extends State<DemoPage> {
#override
void initState() {
super.initState();
ShakeDetector detector = ShakeDetector.waitForStart(onPhoneShake: () {
mytext = "Shaken, not stirred";
print("hello");
});
detector.startListening();
// To close: detector.stopListening();
// ShakeDetector.waitForStart() waits for user to call detector.startListening();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Padding(padding: const EdgeInsets.all(50),child:
Text(
mytext,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 25,
),
)))));
}
}
Use this package for identifying a shake event and for performing some action.
To listen to phone shake:
ShakeDetector detector = ShakeDetector.autoStart(
onPhoneShake: () {
// Do stuff on phone shake
}
);
OR
ShakeDetector detector = ShakeDetector.waitForStart(
onPhoneShake: () {
// Do stuff on phone shake
}
);
detector.startListening();
To stop listening:
detector.stopListening();
In order to install this package in your pubspec.yaml file, follow this link.
Samples can be found on this link.
import 'package:flutter/material.dart';
import 'package:shake/shake.dart';
class DemoPage extends StatefulWidget {
#override
_DemoPageState createState() => _DemoPageState();
}
class _DemoPageState extends State<DemoPage> {
#override
void initState() {
super.initState();
ShakeDetector detector = ShakeDetector.autoStart(onPhoneShake: () {
// Do stuff on phone shake
});
// To close: detector.stopListening();
// ShakeDetector.waitForStart() waits for user to call detector.startListening();
}
#override
Widget build(BuildContext context) {
return Scaffold();
}
}
I was making a similar app like yours. You just want to change an image or do something else when we shake our phone, right?
The package 'package:shake/shake.dart' is right for this work. This package has some pre-defined functions which uses accelerometer reading from our phone and detect when we have shaked our phone and when we have stopped.
Instead of using:
ShakeDetector detector = ShakeDetector.waitForStart(onPhoneShake: () {
mytext = "Shaken, not stirred";
print("hello");
});
I have used:
ShakeDetector detector = ShakeDetector.autoStart(onPhoneShake: () {
setState(() {
//Code for changing image or something else.
});
});
This solved the problem and when I shook my phone and stopped, the image changes just after I stopped shaking.
I don't know about other functions given in this package like waitForStart() and stopListening() function. Just the above autoStart() function did what I wanted.
As per the document of Shake Plugin it depends upon Sensors Plugin
You will have to add sensors plugin in your dependencies list in pubspec.yaml.
This will make your shake plugin detect shakes.
P.S. Happy Coding ! Stay Safe.