I am currently using the latest geolocator that is 'geolocator: ^9.0.1'and for some reason am not able to get any data from the position function when i run
bool isLoc = await Geolocator.isLocationServiceEnabled();
print(isLoc);
The result is true which i think means the location services are all enabled but when i run
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
print('position');
nothing is been returned i have tried all the accuracy values low, high, best,lowest, medium am really confused at what could be wrong i have also try it in the initState and also using a *button
Here is the full dart code
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class GeoLoc extends StatefulWidget {
const GeoLoc({Key? key}) : super(key: key);
#override
State<GeoLoc> createState() => _GeoLocState();
}
class _GeoLocState extends State<GeoLoc> {
#override
void initState() {
super.initState();
getLoc();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
ElevatedButton(onPressed: () {
getLoc();
},
child: const Text('Get Location'),
),
],
);
}
getLoc() async{
bool isLoc = await Geolocator.isLocationServiceEnabled();
print(isLoc);
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position);
}
}
Below is your code modified, pls try it. you forget to ask for geolocation permission
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class GeoLoc extends StatefulWidget {
const GeoLoc({Key? key}) : super(key: key);
#override
State<GeoLoc> createState() => _GeoLocState();
}
class _GeoLocState extends State<GeoLoc> {
#override
void initState() {
super.initState();
getLoc()
.then((value) => print("Location: " + value.toJson().toString()));
}
#override
Widget build(BuildContext context) {
return Column(
children: [
ElevatedButton(onPressed: () {
getLoc()
.then((value) => print("Location: " + value.toJson().toString()));
},
child: const Text('Get Location'),
),
],
);
}
getLoc() async{
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
Geolocator.openLocationSettings();
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
Geolocator.openAppSettings();
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}
}
Also make sure you have below permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Related
I am learning Fllutter to build a map based App. I am using the location pub.dev plugin for managing location permissions.
I have created a Location() object Location location = Location()
and when I call
await location.hasPermission()
and I don't have granted permission , it actually requests the permission , without me calling
await location.requestPermission()
This causes many problems , such as asking two permissions at once , something not permitted by Android , so the app crashes , or by removing await location.requestPermission(), the app ask for the user's permission but it does not wait for the result.
I tested it on my Pixel 5 via adb , running Android 12
What is going on? I have not found another reference of this issue.
Here is the full Code Sample:
class Gmap extends StatefulWidget {
const Gmap({ Key? key }) : super(key: key);
#override
State<Gmap> createState() => _GmapState();
}
class _GmapState extends State<Gmap> {
String _mapStyle = "";
late GoogleMapController mapController;
late Future<LatLng> ull ;
Location location = Location();
final LatLng _center = const LatLng(37.983810, 23.727539);
LatLng _userLocation = const LatLng(37.983810, 23.727539);
Future<LatLng> userLocation() async{
PermissionStatus _permissionGranted;
bool _serviceEnabled;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return _center;
}
}
_permissionGranted = await location.hasPermission(); //it requests permission here
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission()//it requests here again;
if (_permissionGranted != PermissionStatus.granted) {
return _center;
}
}
LocationData l = await location.getLocation();
setState((){
_userLocation = LatLng(l.latitude!, l.longitude!);
});
return _userLocation;
}
void centerLocation(){
CameraPosition userCamera = CameraPosition(
target: _userLocation,
zoom: 14.0,
);
CameraUpdate moveTo = CameraUpdate.newCameraPosition(userCamera);
mapController.animateCamera(moveTo);
}
void _onMapCreated(GoogleMapController controller) async{
mapController = controller;
mapController.setMapStyle(_mapStyle);
centerLocation();
}
#override
void initState() {
super.initState();
rootBundle.loadString('assets/style.txt').then((string) {
_mapStyle = string;
});
ull = userLocation();
}
Widget googleMap(userLocation){
return GoogleMap(
onMapCreated: _onMapCreated,
myLocationEnabled:true,
initialCameraPosition: CameraPosition(
target: userLocation,
zoom: 6.0,
),
zoomControlsEnabled: false, //dont show zoom buttons
compassEnabled: false,
myLocationButtonEnabled: false,
);
}
#override
Widget build(BuildContext context){
return Scaffold(
body: FutureBuilder<LatLng>(
future: ull,
builder: ( context , AsyncSnapshot<LatLng> snapshot){
Widget g;
if(snapshot.hasData){
g = googleMap(_userLocation);
}else if(snapshot.hasError){
g = googleMap(_center);
}else{
g = googleMap(_center);
}
return g;
}
),
floatingActionButton: Column(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
primary: ourGreen,
shape: const CircleBorder(),
padding: const EdgeInsets.all(15),),
child: const Icon(Icons.filter_alt_rounded, size: 27, color: ourDark),),
const SizedBox(height: 9),
ElevatedButton(
onPressed: () {centerLocation(); },
style: ElevatedButton.styleFrom(
primary: const Color(0xFF1A202C),
shape: const CircleBorder(),
padding: const EdgeInsets.all(15)),
child: const Icon(Icons.location_on,
size: 27, color: Colors.greenAccent)),
]),
);
}
}
You can use the permission_handler package and request the permission status like this:
var status = await Permission.camera.status;
if (status.isDenied) {
// We didn't ask for permission yet or the permission has been denied before but not permanently.
}
// You can can also directly ask the permission about its status.
if (await Permission.location.isRestricted) {
// The OS restricts access, for example because of parental controls.
}
See the documentation: https://pub.dev/packages/permission_handler
Update: I never got this to work for some reason following the documentation or the other comments. Here is what worked for me:
Future<LatLng> askPermissionAndGetLocation() async {
if (await Permission.locationWhenInUse.serviceStatus.isEnabled) { //this here checks
//if the permission is granted and if not , it requests it.
if (await Permission.location.request().isGranted) {
LocationData l = await Location().getLocation();
setState(() {
_userLocation = LatLng(l.latitude!, l.longitude!);
});
return _userLocation;
}
}
return Future.error("Location services disabled or restricted");
}
This is the only way I got it to work and I do not see a reason why. If anyone has any insight please leave a comment
I'm trying to track location in the background using flutter and to do so I'm using the background_locator plugin. It has been implemented in such a way that there are certain static callback functions that were registered. I've declared a class variable of File type to save the log in the background. The global variable is built at the very beginning of the class.
Issue: While invoking the callback method, the global variable built is becoming null. So though I could see the location log in my console, I couldn't write it to the file as the object is null.
Tries:
I've tried with the exact example provided in their documentation.
I've declared it as non static property and tried to access with the class object.
Tried it out declaring it as static property as well.
Tried building file object with the same path every time needed but it is throwing following issue.
No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider
Here is my complete source code for reference.
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'dart:ui';
import 'package:background_locator/background_locator.dart';
import 'package:background_locator/location_dto.dart';
import 'package:background_locator/settings/android_settings.dart';
import 'package:background_locator/settings/ios_settings.dart';
import 'package:background_locator/settings/locator_settings.dart';
import 'package:flutter/material.dart';
import 'package:location_permissions/location_permissions.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart' as ph;
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
ReceivePort port = ReceivePort();
String logStr = '';
bool isRunning = false;
LocationDto? lastLocation;
bool permissionsGranted = false;
static const String isolateName = 'LocatorIsolate';
static int _count = -1;
static File? finalFile;
void requestPermission() async {
var storageStatus = await ph.Permission.storage.status;
if (!storageStatus.isGranted) {
await ph.Permission.storage.request();
}
if (storageStatus.isGranted) {
permissionsGranted = true;
setPrerequisites();
}
setState(() {});
}
static Future<void> init(Map<dynamic, dynamic> params) async {
//TODO change logs
print("***********Init callback handler");
if (params.containsKey('countInit')) {
dynamic tmpCount = params['countInit'];
if (tmpCount is double) {
_count = tmpCount.toInt();
} else if (tmpCount is String) {
_count = int.parse(tmpCount);
} else if (tmpCount is int) {
_count = tmpCount;
} else {
_count = -2;
}
} else {
_count = 0;
}
print("$_count");
await setLogLabel("start");
final SendPort? send = IsolateNameServer.lookupPortByName(isolateName);
send?.send(null);
}
static Future<void> disposeLocationService() async {
await setLogLabel("end");
final SendPort? send = IsolateNameServer.lookupPortByName(isolateName);
send?.send(null);
}
static Future<void> callback(LocationDto locationDto) async {
await setLogPosition(_count, locationDto);
final SendPort? send = IsolateNameServer.lookupPortByName(isolateName);
send?.send(locationDto);
_count++;
}
static Future<void> setLogLabel(String label) async {
final date = DateTime.now();
await _MyAppState().writeToLogFile(
'------------\n$label: ${formatDateLog(date)}\n------------\n');
}
static Future<void> setLogPosition(int count, LocationDto data) async {
final date = DateTime.now();
await _MyAppState().writeToLogFile(
'$count : ${formatDateLog(date)} --> ${formatLog(data)} --- isMocked: ${data.isMocked}\n');
}
static double dp(double val, int places) {
num mod = pow(10.0, places);
return ((val * mod).round().toDouble() / mod);
}
static String formatDateLog(DateTime date) {
return date.hour.toString() +
":" +
date.minute.toString() +
":" +
date.second.toString();
}
static String formatLog(LocationDto locationDto) {
return dp(locationDto.latitude, 4).toString() +
" " +
dp(locationDto.longitude, 4).toString();
}
#override
void initState() {
super.initState();
if (permissionsGranted) {
setPrerequisites();
} else {
requestPermission();
}
}
void setPrerequisites() async {
finalFile = await _getTempLogFile();
if (IsolateNameServer.lookupPortByName(isolateName) != null) {
IsolateNameServer.removePortNameMapping(isolateName);
}
IsolateNameServer.registerPortWithName(port.sendPort, isolateName);
port.listen(
(dynamic data) async {
await updateUI(data);
},
);
initPlatformState();
setState(() {});
}
Future<void> updateUI(LocationDto data) async {
final log = await readLogFile();
await _updateNotificationText(data);
setState(() {
if (data != null) {
lastLocation = data;
}
logStr = log;
});
}
Future<void> _updateNotificationText(LocationDto data) async {
if (data == null) {
return;
}
await BackgroundLocator.updateNotificationText(
title: "new location received",
msg: "${DateTime.now()}",
bigMsg: "${data.latitude}, ${data.longitude}");
}
Future<void> initPlatformState() async {
print('Initializing...');
await BackgroundLocator.initialize();
logStr = await readLogFile();
print('Initialization done');
final _isRunning = await BackgroundLocator.isServiceRunning();
setState(() {
isRunning = _isRunning;
});
print('Running ${isRunning.toString()}');
}
#override
Widget build(BuildContext context) {
final start = SizedBox(
width: double.maxFinite,
child: ElevatedButton(
child: const Text('Start'),
onPressed: () {
_onStart();
},
),
);
final stop = SizedBox(
width: double.maxFinite,
child: ElevatedButton(
child: Text('Stop'),
onPressed: () {
onStop();
},
),
);
final clear = SizedBox(
width: double.maxFinite,
child: ElevatedButton(
child: Text('Clear Log'),
onPressed: () {
clearLogFile();
setState(() {
logStr = '';
});
},
),
);
String msgStatus = "-";
if (isRunning != null) {
if (isRunning) {
msgStatus = 'Is running';
} else {
msgStatus = 'Is not running';
}
}
final status = Text("Status: $msgStatus");
final log = Text(
logStr,
);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter background Locator'),
),
body: Container(
width: double.maxFinite,
padding: const EdgeInsets.all(22),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[start, stop, clear, status, log],
),
),
),
),
);
}
void onStop() async {
await BackgroundLocator.unRegisterLocationUpdate();
final _isRunning = await BackgroundLocator.isServiceRunning();
setState(() {
isRunning = _isRunning;
});
}
void _onStart() async {
if (await _checkLocationPermission()) {
await _startLocator();
final _isRunning = await BackgroundLocator.isServiceRunning();
setState(() {
isRunning = _isRunning;
lastLocation = null;
});
} else {
// show error
}
}
static Future<void> initCallback(Map<dynamic, dynamic> params) async {
await init(params);
}
static Future<void> disposeCallback() async {
await disposeLocationService();
}
Future<void> locationServicecallback(LocationDto locationDto) async {
await callback(locationDto);
}
static Future<void> notificationCallback() async {
print('***notificationCallback');
}
Future<void> writeToLogFile(String log) async {
await finalFile!.writeAsString(log, mode: FileMode.append);
}
Future<String> readLogFile() async {
return finalFile!.readAsString();
}
static Future<File?> _getTempLogFile() async {
File file =
File('${(await getApplicationDocumentsDirectory()).path}/log.txt');
if (file.existsSync()) {
return file;
} else {
file = await file.create(recursive: true);
}
return file;
}
Future<void> clearLogFile() async {
await finalFile!.writeAsString('');
}
Future<bool> _checkLocationPermission() async {
final access = await LocationPermissions().checkPermissionStatus();
switch (access) {
case PermissionStatus.unknown:
case PermissionStatus.denied:
case PermissionStatus.restricted:
final permission = await LocationPermissions().requestPermissions(
permissionLevel: LocationPermissionLevel.locationAlways,
);
if (permission == PermissionStatus.granted) {
return true;
} else {
return false;
}
case PermissionStatus.granted:
return true;
default:
return false;
}
}
Future<void> _startLocator() async {
Map<String, dynamic> data = {'countInit': 1};
return await BackgroundLocator.registerLocationUpdate(
callback,
initCallback: initCallback,
initDataCallback: data,
disposeCallback: disposeCallback,
iosSettings: const IOSSettings(
accuracy: LocationAccuracy.NAVIGATION, distanceFilter: 0),
autoStop: false,
androidSettings: const AndroidSettings(
accuracy: LocationAccuracy.NAVIGATION,
interval: 5,
distanceFilter: 0,
client: LocationClient.google,
androidNotificationSettings: AndroidNotificationSettings(
notificationChannelName: 'Location tracking',
notificationTitle: 'Start Location Tracking',
notificationMsg: 'Track location in background',
notificationBigMsg:
'Background location is on to keep the app up-tp-date with your location. This is required for main features to work properly when the app is not running.',
notificationIconColor: Colors.grey,
notificationTapCallback: notificationCallback,
),
),
);
}
}
Any help/suggestion would be highly appreciated. Thank you!
The callback function not getting called was an issue I faced inthe version 1.6.12.
I fixed the problem by
forking the background_locator repo on github.
cloning the repo to my computer
opened the location_dto.dart file and went to fromJson function.
added json[Keys.ARG_PROVIDER] ?? '' instead
commited and pushed to my forked repository
in pubspec.yaml, I updated my dependency to point to my forked repository as follows:
background_locator:
git:
url: git#github.com:frankvollebregt/background_locator.git
Please follow these two github issues if you find any problem:
https://github.com/rekabhq/background_locator/issues/320
https://github.com/rekabhq/background_locator/issues/301
background_locator dosen't work on latest flutter sdk versions
for me it's worked when I do this steps
Flutter sdk version should be :3.0.1
In pubspec.yaml file change sdk: ">=2.8.0 <3.0.0"
Don't migrate your code to null safety
in gradle-wrapper.properties change gradle version to gradle-6.5
android/build gradle change ext.kotlin_version to '1.4.31'
android/app/build gradle change compileSdkVersion to 31, minSdkVersion to 19 and targetSdkVersion to 30
This is not a problem with the background locator plugin. When the plugin/library is not registered with Flutter Engine, the 'No implementation' error occurs.
You have been attempting to access the path provider methods from within a Background Isolate. Normally, the path provider plugin will be registered with main isolate.
If you want to use it in your background isolate, you must manually register it with the engine.
Follow the steps below and add these two functions to the Init function in location_service_repositary.dart
if (Platform.isAndroid) PathProviderAndroid.registerWith();
if (Platform.isIOS) PathProviderIOS.registerWith();
Have a good day.
I am using the Flutter local_auth plugin, biometrics works fine but Pincode/pattern doesn't provide authentication. I found if I remove my fingerprints from my mobile then Pincode and pattern authentication works but I need to input 2 times. The library seems correct but couldn't get a proper hold on the reason for this strange behaviour. Can anyone suggest?
Moreover, can we use a custom UI for the authentication, like how it is in WhatsApp?
local_auth_api.dart:
import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
import 'package:local_auth/auth_strings.dart';
class LocalAuthApi {
static final _auth = LocalAuthentication();
static const iosStrings = IOSAuthMessages(
cancelButton: 'cancel',
goToSettingsButton: 'settings',
goToSettingsDescription: 'Please set up your Touch ID.',
lockOut: 'Please reenable your Touch ID');
static const androidStrings = AndroidAuthMessages(
cancelButton: 'cancel',
goToSettingsButton: 'settings',
goToSettingsDescription: 'Please set up your Touch ID.',
signInTitle: 'User Authorization Required',
);
static Future<bool> hasBiometrics() async {
try {
return await _auth.canCheckBiometrics;
} on PlatformException catch (e) {
return false;
}
}
static Future<List<BiometricType>> getBiometrics() async {
try {
return await _auth.getAvailableBiometrics();
} on PlatformException catch (e) {
return <BiometricType>[];
}
}
static Future<bool> authenticate() async {
try {
return await _auth.authenticate(
localizedReason: 'Scan your Fingerprint to Authenticate',
useErrorDialogs: true,
sensitiveTransaction: true,
stickyAuth: true,
iOSAuthStrings: iosStrings,
androidAuthStrings: androidStrings
);
} on PlatformException catch (e) {
print(e);
return false;
}
}
}
lock_screen.dart
import 'package:xyz/resources/constants.dart';
import 'package:xyz/src/services/local_auth_api.dart';
import 'package:flutter/material.dart';
class LockScreen extends StatefulWidget{
const LockScreen({Key? key}) : super(key: key);
#override
_LockScreenState createState() => _LockScreenState();
}
class _LockScreenState extends State<LockScreen>{
#override
void initState() {
super.initState();
authenticate();
}
authenticate() async {
bool isAuthenticated = false;
while(true){
isAuthenticated = await LocalAuthApi.authenticate();
if (isAuthenticated) {
print(isAuthenticated);
break;
}
}
print("unlocked");
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
double screenHeight = size.height;
double screenWidth = size.width;
return Scaffold(
backgroundColor: primaryColor,
body: Center(
)
);
}
}
Response:
E/BiometricFragment(19568): Not launching prompt. Client activity was null.
I'm attempting to run location updates on a Flutter isolate thread, the error is only present when running an isolate. Location requests works without issues on the main thread. The goal here is to run this as a background service, working with dart code only.
I am using Geolocator plugin for location requests.
This is the error I am facing when starting the isolate:
Exception has occurred. FlutterError
(ServicesBinding.defaultBinaryMessenger was accessed before the
binding was initialized.
I have tried to include the WidgetsFlutterBinding.ensureInitialized() before runApp but without results.
Looking at the call stack of the error, it seems problems occur at the android location platform call: checkPermissionStatus
This happens regardless of what location plugin I am using, it stops at the permission status check.
I have figured it could have something to do with awaiting location permission user input, but this check will fail on a non-ui thread?
See this simple main.dart file for an example:
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Isolate location test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Isolate location test'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Isolate isolate;
bool isRunning = false;
String output = '';
ReceivePort receivePort;
void start() async {
receivePort = ReceivePort();
await Isolate.spawn(locationUpdate, receivePort.sendPort);
receivePort.listen((dynamic data) {
setState(() {
isRunning = true;
});
}, onDone: () {
print("done");
});
}
void stop() {
if (isolate != null) {
setState(() {
isRunning = false;
});
receivePort.close();
isolate.kill(priority: Isolate.immediate);
isolate = null;
}
}
static void locationUpdate(SendPort sendPort) async {
Geolocator().checkGeolocationPermissionStatus().then((status) {
sendPort.send(status);
});
// Geolocator().getCurrentPosition().then((pos) {
// sendPort.send(pos);
// });
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(child: Text(output)),
floatingActionButton: FloatingActionButton(
onPressed: isRunning ? stop : start,
child: Icon(isRunning ? Icons.stop : Icons.play_circle_filled),
),
);
}
}
I am making an app which use the camera as well as Flash. I have set the Permissions for Camera in Android Manifest file and Do the code for start Flash one button click but unable to On flash on Post Lollipop devices. It is working fine till lollipop devices. I have put a permission to access the camera but still not getting result. Please Help. I am Added the code which i have completed.
import 'package:flutter/material.dart';
import 'package:lamp/lamp.dart';
import 'dart:async';
import 'package:permission/permission.dart';
import 'dart:io' show Platform;
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _hasFlash = false;
bool _isOn = false;
double _intensity = 1.0;
String platform;
#override
initState() {
super.initState();
initPlatformState();
initplatform();
}
//its just for getting the platform version
initplatform() async {
if (Platform.isIOS) {
platform = "IOS";
print('is a IOS');
} else if (Platform.isAndroid) {
platform = "Android";
print('is a Android');
//requestAndroidPermissions();
}
}
initPlatformState() async {
bool hasFlash = await Lamp.hasLamp;
print("Device has flash ? $hasFlash");
setState(() { _hasFlash = hasFlash; });
}
checkAndroidCameraPermissions() {
getCameraPermissionStatus();
}
getCameraPermissionStatus() async {
var get = '';
List<Permissions> permissions = await Permission.getPermissionsStatus([PermissionName.Camera,]);
permissions.forEach((permission) {
get += '${permission.permissionName}: ${permission.permissionStatus}';
if (get != "PermissionName.Camera: PermissionStatus.allow") {
requestCameraPermission();
} else {
//_turnFlash();
Lamp.turnOn(intensity:1.0);
}
});
}
requestCameraPermission() async {
final res = await Permission.requestPermissions([PermissionName.Camera]);
res.forEach((permission) {
String a = '${permission.permissionStatus}';
setState(() {
if (a == 'PermissionStatus.allow') {
//RestartWidget.restartApp(context).
//_turnFlash();
Lamp.turnOn(intensity:1.0);
}
else {
Permission.openSettings;
}
});
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
theme: new ThemeData(primarySwatch: Colors.pink),
home: new Scaffold(
appBar: new AppBar(title: new Text('Lamp plugin example')),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('Device has flash: $_hasFlash\n Flash is on: $_isOn'),
new Slider(value: _intensity, onChanged: _isOn ? _intensityChanged : null),
new RaisedButton(onPressed: () async => await Lamp.flash(new Duration(seconds: 2)), child: new Text("Flash for 2 seconds"))
]),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(_isOn ? Icons.flash_off : Icons.flash_on),
onPressed:()
//Comment the if code if you want run it in lollipop device
//for post lollipop device
{
if (platform == 'Android') {
requestCameraPermission();
}else{
Lamp.turnOn(intensity:1.0);
}
}
//for pre lollipop devi e
//_turnFlash
),
),
);
}
Future _turnFlash() async {
_isOn ? Lamp.turnOff() : Lamp.turnOn(intensity: _intensity);
var f = await Lamp.hasLamp;
setState((){
_hasFlash = f;
_isOn = !_isOn;
});
}
_intensityChanged(double intensity) {
Lamp.turnOn(intensity : intensity);
setState((){
_intensity = intensity;
});
}
}
Added below permission for Android
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-feature android:name="android.hardware.camera2" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Plugin for Lamp and permission
lamp: ^0.0.6 permission: ^0.1.1