flutter 如何修复权限处理程序错误

utugiqy6  于 2023-04-07  发布在  Flutter
关注(0)|答案(5)|浏览(142)

我不知道如何解决这个红色错误的一部分。我从互联网上复制这个,然后我得到了这个错误。请帮助我解决这个问题。

这是我的完整代码。

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:android_intent/android_intent.dart';
import 'package:geolocator/geolocator.dart';
class AskForPermission extends StatefulWidget {
  @override
  _AskForPermissionState createState() => _AskForPermissionState();
}
class _AskForPermissionState extends State<AskForPermission> {
  final PermissionHandler permissionHandler = PermissionHandler();
  Map<PermissionGroup, PermissionStatus>? permissions;
  void initState() {
    super.initState();
    requestLocationPermission();
    _gpsService();
  }
  Future<bool> _requestPermission(PermissionGroup permission) async {
    final PermissionHandler _permissionHandler = PermissionHandler();
    var result = await _permissionHandler.requestPermissions([permission]);
    if (result[permission] == PermissionStatus.granted) {
      return true;
    }
    return false;
  }
/*Checking if your App has been Given Permission*/
  Future<bool> requestLocationPermission({Function? onPermissionDenied}) async {
    var granted = await _requestPermission(PermissionGroup.location);
    if (granted!=true) {
      requestLocationPermission();
    }
    debugPrint('requestContactsPermission $granted');
    return granted;
  }
/*Show dialog if GPS not enabled and open settings location*/
  Future _checkGps() async {
    if (!(await Geolocator.isLocationServiceEnabled())) {
      if (Theme.of(context).platform == TargetPlatform.android) {
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("Can't get gurrent location"),
                content:const Text('Please make sure you enable GPS and try again'),
                actions: <Widget>[
                  FlatButton(child: Text('Ok'),
                      onPressed: () {
                        final AndroidIntent intent = AndroidIntent(
                            action: 'android.settings.LOCATION_SOURCE_SETTINGS');
                        intent.launch();
                        Navigator.of(context, rootNavigator: true).pop();
                        _gpsService();
                      })],
              );
            });
      }
    }
  }

/*Check if gps service is enabled or not*/
  Future _gpsService() async {
    if (!(await Geolocator.isLocationServiceEnabled())) {
      _checkGps();
      return null;
    } else
      return true;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Ask for permisions'),
          backgroundColor: Colors.red,
        ),
        body: Center(
            child: Column(
              children: <Widget>[
                Text("All Permission Granted"),
              ],
            ))
    );
  }
}
xtfmy6hx

xtfmy6hx1#

我也遇到了同样的问题--在我升级到^8.3.0后,与permission_handler ^8.0.0+2一起工作的代码不再工作了--代码无法编译,Permission和其他类不再“找到”(我使用VS Code)
我通过清理pub缓存修复了它:

flutter pub cache clean

然后再次得到依赖关系:

flutter pub get

PS:为了升级到8.3.0,我在build.gradle文件中设置了targetSdkVersion和compileSdkVersion为31

gywdnpxw

gywdnpxw2#

安装权限处理程序包from here。然后在.dart文件中添加import并在某处调用权限请求函数。例如,像这样的函数要求存储权限。

import 'package:permission_handler/permission_handler.dart';

  Future<void> getStoragePermission() async {
    if (await Permission.manageExternalStorage.request().isGranted) {
      setState(() {});
    } else if (await Permission.storage.request().isPermanentlyDenied) {
      await openAppSettings();
    } else if (await Permission.storage.request().isDenied) {
      setState(() {});
    }
  }
mefy6pfw

mefy6pfw3#

请参考下面的代码
https://pub.dev/packages/permission_handler/install permission_handler:^5.0.1+1

import 'package:permission_handler/permission_handler.dart';
import 'package:google_fonts/google_fonts.dart';

class MyApp extends StatelessWidget {
  MyApp({Key key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primaryColor: Color(0xfff00B074),
        textTheme: const TextTheme(
          bodyText1: TextStyle(
              fontSize: 18.0,
              fontFamily: 'Barlow-Medium',
              color: Color(0xff464255)),
        ),
      ),
      home: PermissionHandlerScreen(),
    );
  }
}

class PermissionHandlerScreen extends StatefulWidget {
  @override
  _PermissionHandlerScreenState createState() =>
      _PermissionHandlerScreenState();
}

class _PermissionHandlerScreenState extends State<PermissionHandlerScreen> {
  @override
  void initState() {
    super.initState();
    permissionServiceCall();
  }

  permissionServiceCall() async {
    await permissionServices().then(
      (value) {
        if (value != null) {
          if (value[Permission.storage].isGranted &&
              value[Permission.camera].isGranted &&
              value[Permission.microphone].isGranted) {
            /* ========= New Screen Added  ============= */

            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => SplashScreen()),
            );
          }
        }
      },
    );
  }

  /*Permission services*/
  Future<Map<Permission, PermissionStatus>> permissionServices() async {
    // You can request multiple permissions at once.
    Map<Permission, PermissionStatus> statuses = await [
      Permission.storage,
      Permission.camera,
      Permission.microphone,
      //add more permission to request here.
    ].request();

    if (statuses[Permission.storage].isPermanentlyDenied) {
      openAppSettings();
      setState(() {});
    } else {
      if (statuses[Permission.storage].isDenied) {
        permissionServiceCall();
      }
    }
    if (statuses[Permission.microphone].isPermanentlyDenied) {
      openAppSettings();
      setState(() {});
    } else {
      if (statuses[Permission.microphone].isDenied) {
        permissionServiceCall();
        
      }
    }

    if (statuses[Permission.camera].isPermanentlyDenied) {
      openAppSettings();
      setState(() {});
    } else {
      if (statuses[Permission.camera].isDenied) {
        permissionServiceCall();
      }
    }
    /*{Permission.camera: PermissionStatus.granted, Permission.storage: PermissionStatus.granted}*/
    return statuses;
  }

  @override
  Widget build(BuildContext context) {
    permissionServiceCall();
    return WillPopScope(
      onWillPop: () {
        SystemNavigator.pop();
      },
      child: Scaffold(
        body: Container(
          child: Center(
            child: InkWell(
                onTap: () {
                  permissionServiceCall();
                },
                child: Text("Click here to enable Enable Permission Screen")),
          ),
        ),
      ),
    );
  }
}

class SplashScreen extends StatelessWidget {
  const SplashScreen({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        SystemNavigator.pop();
      },
      child: Scaffold(
        body: Center(
          child: Text(
            "Splash Screen",
          ),
        ),
      ),
    );
  }
}
cyvaqqii

cyvaqqii4#

pubspec.yaml文件中添加permission_handler依赖项。
尝试flutter pub get命令。如果已经完成,请参考有关permission handler package的链接。

7cjasjjr

7cjasjjr5#

import 'package:permission_handler/permission_handler.dart' as ph;
...
int n = int n. int n();
...

相关问题