android-studio - 如何修复 WillPopScope() 对我不起作用

标签 android-studio flutter dart

我创建了两个页面,一个是登录页面和主页,但我想从主页关闭应用程序,我正在使用 Willpopscope但它对我不起作用我已经尝试了所有方法,但 onwillpop方法不调用请帮帮我谢谢。

class main_page extends StatelessWidget {
@override
Widget build(BuildContext context) {
  return MaterialApp(
  theme: ThemeData(primarySwatch: Colors.amber),
  home: my_page(),
);
}
}

class my_page extends StatefulWidget {
@override
_my_pageState createState() => _my_pageState();
}

class _my_pageState extends State<my_page> {
 @override
void initState() {
check_login();
 super.initState();
}

Future check_login() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
if (preferences.getBool("islogin") == false)
  setState(() {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => MyApp(),
    ));
  });
}

@override
 Widget build(BuildContext context) {
return WillPopScope(
  onWillPop: () async=>false,
  child: Scaffold(
    appBar: new AppBar(
      title: Text(
        "Home",
        style: new TextStyle(color: Colors.white),
      ),
      actions: <Widget>[
        FlatButton(
            onPressed: () async {
              SharedPreferences sharedPreferences =
                  await SharedPreferences.getInstance();

              setState(() {
                sharedPreferences.setBool("islogin", false);
                Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) => main_page(),
                ));
              });
            },
            child: Text(
              "Logout",
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ))
      ],
    ),
  ),
);
}
}
我也在用 Shredprefrences但我认为没关系,我想从我的 main_page 关闭应用程序,请帮助我,谢谢。

最佳答案

看看这个答案,让我知道它是否有效:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.amber),
      home: SecondPage(),
    );
  }
}

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
            child: RaisedButton(
          child: Text('Move to second page after Login'),
          onPressed: () async {
            SharedPreferences preferences =
                await SharedPreferences.getInstance();

            preferences.setBool("islogin", true);
            // this will remove the login page after routing to the second page and then the stack will have only one page that is second page.
           // so later you can use the willpopscape 
            Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => SecondPage()),
                ModalRoute.withName("/Home"));
          },
        )),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {
  @override
  void initState() {
    check_login();
    
    super.initState();
  }

  Future check_login() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    if (preferences.getBool("islogin") == null)

    //This above if statement will check if the parameter islogin is null then redirect to the login screeen
    // else if the value is not null then i will not enter the if statement
      setState(() {
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => LoginPage(),
        ));
      });
  }

  Future<bool> _onWillPop() async {

    // This dialog will exit your app on saying yes
    return (await showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text('Are you sure?'),
            content: new Text('Do you want to exit an App'),
            actions: <Widget>[
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text('No'),
              ),
              new FlatButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: new Text('Yes'),
              ),
            ],
          ),
        )) ??
        false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        appBar: new AppBar(
          title: Text(
            "Home",
            style: new TextStyle(color: Colors.white),
          ),
          actions: <Widget>[
            FlatButton(
                onPressed: () async {
                   SystemNavigator.pop();
                },
                child: Text(
                  "Logout",
                  style: TextStyle(color: Colors.white, fontSize: 16.0),
                ))
          ],
        ),
      ),
    );
  }
}

关于android-studio - 如何修复 WillPopScope() 对我不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62726522/

相关文章:

android - 使用 flutter 中的手势检测器导航到不同页面时,黑屏 flutter 。说多个英雄共享同一个标签

Debug模式下的 Android Studio "view bitmap"不显示位图

android - 在 2.3 上处理 Android Studio 3.0 项目

安卓工作室 : Error: SplashActivity is not an Activity subclass or alias

flutter - 有没有办法在 Flutter 中将 Text 与 spritewidget 一起使用?

json - 在 dart 中使用 JSON.decode() 从 json 字符串实例化类

Android Studio 2.0 无法在模拟器中启动 AVD

flutter - 如何在 Flutter Widget(Center Widget)的子属性中使用条件语句

ios - Flutter ios存档应用程序 undefined symbol

exception - 扩展面板底部溢出