flutter 如何将permission_handler代码添加到我的主.dart页面?

bzzcjhmw  于 2022-12-30  发布在  Flutter
关注(0)|答案(1)|浏览(129)

我想添加permission_handler插件。我已经把它添加到pubspec.yaml文件中,但是不知道下一步该怎么做。我该如何把location权限的代码添加到我的main.dart页面中呢?

主省道页码:

import 'package:flutter/material.dart';
import 'package:athena/providers/app_state.dart';
import 'package:athena/providers/user.dart';
import 'package:athena/screens/login.dart';
import 'package:athena/screens/splash.dart';
import 'locators/service_locator.dart';
import 'screens/home.dart';
import 'package:provider/provider.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  setupLocator();
  return runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider<AppStateProvider>.value(
        value: AppStateProvider(),
      ),
      ChangeNotifierProvider<UserProvider>.value(
        value: UserProvider.initialize(),
      ),
    ],
    child: MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Athena',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyApp(),
    ),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserProvider auth = Provider.of<UserProvider>(context);
    switch (auth.status) {
      case Status.Uninitialized:
        return Splash();
      case Status.Unauthenticated:
      case Status.Authenticating:
        return LoginScreen();
      case Status.Authenticated:
        return MyHomePage();
      default:
        return LoginScreen();
    }
  }
}
qq24tv8q

qq24tv8q1#

创建如下函数

Future<void> askLocationPermission() async {
    await Permission.location.request();
  }

由于您已经添加了home: MyApp()作为home,
转到MyApp(),并将其设置为状态小部件。
然后在其initState()中调用请求权限的函数。
示例如下所示

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

相关问题