반응형
권한 요청에 사용되는 패키지
pub.dev/packages/permission_handler
1. 권한확인
Future<bool>_checkPermission() async {
var status = await Permission.storage.status;
return status == PermissionStatus.granted ? true : false;
}
2. 권한요청
Future<bool> _requestPermission() async {
Map<Permission, PermissionStatus> statues =await [Permission.storage].request();
return statues[Permission.storage] == PermissionStatus.granted ? true : false;
}
3. 사용
여러가지 방법이 있을 수 있습니다.
@override
void initState() {
super.initState();
_checkPermission()
.then((value){
if(value == false){
return _requestPermission();
}
})
.then((value){
print(value);
});
}
[전체 소스]
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _storagePermission = false;
Future<bool>_checkPermission() async {
var status = await Permission.storage.status;
print(status);
if(status == PermissionStatus.granted){
return true;
}else{
return false;
}
}
Future<bool> _requestPermission() async {
//여러개
Map<Permission, PermissionStatus> statues =await [Permission.storage].request();
print(statues[Permission.storage]);
if(statues[Permission.storage] == PermissionStatus.granted){
return true;
}else{
return false;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text("appbar"),
actions: [
IconButton(
onPressed: () async{
var hasOpened = openAppSettings();
debugPrint("App Settings opend : "+hasOpened.toString());
},
icon: const Icon(Icons.settings))
],
),
body: Center(
child: Column(
children: [
Text('Storage permission : $_storagePermission'),
ElevatedButton(onPressed: () async {
var result= await _checkPermission();
setState(() {
_storagePermission = result;
});
}, child: Text("권한확인")),
ElevatedButton(onPressed: () async {
var result = await _requestPermission();
setState(() {
_storagePermission = result;
});
}, child:Text("권한요청"))
],
),
),
);
}
}
'flutter.dev' 카테고리의 다른 글
json 파싱 (0) | 2021.07.06 |
---|---|
Hive (0) | 2021.05.25 |
[하는 중.]어셋과 이미지 추가하기 (0) | 2019.11.26 |
Provider (0) | 2019.11.05 |
리스트 기본 (0) | 2019.05.03 |