微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flutter 中不可关闭的对话框

如何解决Flutter 中不可关闭的对话框

我想要实现的是通过单击android中的后退按钮来制作无法关闭的对话框。

我知道 barrierdismissible 方法showDialog 属性,但它只执行名称所暗示的操作。将其设置为 false 并单击后退按钮,对话框仍然消失。

我还尝试将我的代码包装在 WillPopScope 中以拦截后退按钮点击,但如果显示对话框,则永远不会调用 onWillPop。也许我搞砸了 context 或其他东西,或者有另一种方法来实现这种行为?任何帮助表示赞赏。

我稍微修改认计数器应用程序以显示我的研究目前处于哪个阶段

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,this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  bool _isLocationWarningActive = false;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // this is never called if the dialog is shown
        if (_isLocationWarningActive) return true;
        return false;
      },child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),body: Center(
          child: LocationChecker(
            isLocationWarningActive: _isLocationWarningActive,setIsLocationWarningActive: (value) {
              setState(() {
                _isLocationWarningActive = value;
              });
            },child: Column(
              mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
                Text(
                  'You have pushed the button this many times:',Text(
                  '$_counter',style: Theme.of(context).textTheme.headline4,],floatingActionButton: FloatingActionButton(
          onpressed: _incrementCounter,tooltip: 'Increment',child: Icon(Icons.add),// This trailing comma makes auto-formatting nicer for build methods.
      ),);
  }
}

class LocationChecker extends StatefulWidget {
  final bool isLocationWarningActive;
  final Function(bool) setIsLocationWarningActive;
  final Widget child;

  const LocationChecker({Key key,this.setIsLocationWarningActive,this.isLocationWarningActive,this.child}) : super(key: key);
  
  @override
  _LocationCheckerState createState() => _LocationCheckerState();
}

class _LocationCheckerState extends State<LocationChecker> with WidgetsBindingObserver {
  
  @override
  void initState() {
    WidgetsBinding.instance.addobserver(this);
    super.initState();
  }
  
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
  
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("state: $state");
    if (state == AppLifecycleState.resumed && !_isCheckingLocation) {
      _showLocationSettingsAlertIfNeeded();
    }
  }

  bool _isCheckingLocation = false;
  Future _showLocationSettingsAlertIfNeeded() async {
    if (!mounted) return;
    _isCheckingLocation = true;
  
    if (await checkLocationPermission) {
      if (widget.isLocationWarningActive) {
        widget.setIsLocationWarningActive(false);
        _isCheckingLocation = false;
        Navigator.of(context).pop(true);
      }
    } else if (!widget.isLocationWarningActive) {
      print("should show notification");
      widget.setIsLocationWarningActive(true);
      await showDialog(
        context: context,barrierdismissible: false,builder: (BuildContext context) =>
            OneActionDialog(
              title: "Location Settings",child: Text("Click OK to goto settings"),btnTitle: "OK",action: () {
                widget.setIsLocationWarningActive(false);
                _isCheckingLocation = false;
                SystemSetting.goto(SettingTarget.LOCATION);
                Navigator.of(context).pop(true);
              },);
    }
  }
  
  @override
  Widget build(BuildContext context) {
    return Container(
      child: widget.child,);
  }
}

Future<bool> get checkLocationPermission async {
  ServiceStatus serviceStatus = await LocationPermissions().checkServiceStatus();
  if (serviceStatus != ServiceStatus.enabled) return false;
  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;
      }
      break;
    case PermissionStatus.granted:
      return true;
      break;
    default:
      return false;
      break;
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。