Android Studio 如何修复WillPopScope()对我不起作用

k97glaaz  于 2022-11-16  发布在  Android
关注(0)|答案(6)|浏览(304)

我创建了两个页面,一个是登录和主页,但我想从主页关闭应用程序,我正在使用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,但我认为这并不重要,我想关闭应用程序从我的主页请帮助我,谢谢。

0s7z1bwu

0s7z1bwu1#

请查看此答案,如果有效,请告诉我:

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),
                ))
          ],
        ),
      ),
    );
  }
}
szqfcxe2

szqfcxe22#

以下是答案example_page代码

class exmp extends StatefulWidget {
@override
_exmpState createState() => _exmpState();
}

class _exmpState extends State<exmp> {
@override
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text("example"),
  ),
  body: Column(
    children: <Widget>[
      Center(
        child: RaisedButton(onPressed: () {
          Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(
                builder: (context) => my_example(),
              ),
              (route) => false);
        }),
      )
    ],
  ),
);
}
}

这是我的第二页

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

 class my_examp extends StatefulWidget {
  @override
  _my_exampState createState() => _my_exampState();
 }

class _my_exampState extends State<my_examp> {
Future<bool> onbackpress() async{
return true;
}

@override
Widget build(BuildContext context) {
return WillPopScope(
  onWillPop: onbackpress,
  child: Scaffold(
    appBar: AppBar(
      title: Text("my_eaxmple"),
    ),
  ),
);
}
}

问题是我正在从我的主页推送另一个页面,但我忘记删除第一页,因为我使用Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => my_example()(route) => false);在导航到另一个页面之前删除了主页

fkaflof6

fkaflof63#

"这就是你应该如何使用"

Future<bool> _willPopCallback() async {
    // await Show dialog of exit or what you want
    // then
    return true; //  
}

//then use in the build like
WillPopScope(child: new Scaffold(), onWillPop: _willPopCallback)
8dtrkrch

8dtrkrch4#

  • 我解决了这个错误,因为我有一个父屏幕,我有PageView。我试图在我的一个PageView中调用WillPopScope,然后我意识到我的父屏幕也有WillPopScope。*
  • 这就是它不调用PageView的WillPopScope的原因 *
vdzxcuhz

vdzxcuhz5#

我一直在纠结这个问题,没有一个答案有帮助,但最后我在BackButton小部件源代码中找到了正确的答案。
当我们在小部件上使用WillPopScope时,我们应该使用maybePop而不是pop方法,pop方法强制Navigator弹出最后推送的页面,以便让WillPopScope小部件决定下一个操作。

Navigator.maybePop(context);
vmjh9lq9

vmjh9lq96#

不要在Scaffold()上使用,如示例所示 Package MaterialApp

bool allowed = false;
return WillPopScope(
  onWillPop: () async {
    print('MJD POP TRYING TO GET BACK from login Page');
    return Future.value(allowed);
  },
  child: MaterialApp(
    title: 'Your App Title',
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: const MyLoginPage(title: 'Login Page'),
  ),
);

相关问题