【问题标题】:how to handle the back button of andriod in flutter如何在颤动中处理android的后退按钮
【发布时间】:2021-10-13 23:26:34
【问题描述】:

我正在开发一个具有超过 5 个屏幕的颤振应用程序,我想处理 android 的后退按钮,例如,当我登录应用程序时,它会显示仪表板屏幕,所以当我移动到配置文件时然后移动到历史屏幕,当我点击历史屏幕上的后退按钮时,它应该导航到个人资料屏幕,因为我在历史屏幕之前访问的最后一个屏幕是个人资料,但它显示了第一个登录屏幕。

我找到了解决方案,当我单击后退按钮时它会关闭应用程序。

更新:

我的屏幕从抽屉和底部导航导航,只有登录屏幕,我使用登录按钮并调用仪表板屏幕按下功能,除此之外,任何屏幕上都没有导航到其他屏幕的按钮。这是抽屉和底部导航的代码。

这是我在登录按钮上使用的代码行

 Navigator.push(
              context, new MaterialPageRoute(builder: (context) => Employee()));

抽屉和底部导航代码: 代码:

class Employee extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(
        primaryColor: Colors.blue
      ),
      home: EmployeeNavigation(),
    );
  }
}
  int _selectedTab = 0;
  final _pageOptions = [
    EmployeeDashboard(),
    location(),
    Profile()
  ];

  String getname="";
  String getemail="";
  String getdesignation="";
  String getaccesstoken="";   
  String getdate;
  String getTime;

// ignore: must_be_immutable
class EmployeeNavigation extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return EmployeeNavigationState();
  }
}
class EmployeeNavigationState extends State<EmployeeNavigation> {
  
  var email;
  var designation;
  var date;
  bool valuefirst = false;
  String backtext="";

  @override
  Widget build(BuildContext context) {
   //i used this too but it doesn't work.
    return WillPopScope(
      onWillPop: () async {
        if (_selectedTab == 0) {
          return true;
        }
        setState(() {
          _selectedTab = 0;
        });
        return false;
      },
      
    child:Scaffold(    
    drawer:Emp_DrawerCode(),
    body:  _pageOptions[_selectedTab], 
    bottomNavigationBar: BottomNavigationBar(
     backgroundColor: Colors.blue[50],
    type: BottomNavigationBarType.fixed,
    currentIndex: _selectedTab,
    onTap: (value) {
      print(value);
      setState(() {
        _selectedTab = value;
      });
    },
    items: [
      BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"),
      BottomNavigationBarItem(icon: Icon(Icons.location_on), label: "Location"),
      BottomNavigationBarItem(
        icon: Icon(Icons.person),
        label: "Profile",
      ),
    ],
  )));
  
}
}



class Emp_DrawerCode extends StatefulWidget {
  @override
  _Emp_DrawerCodeState createState() => _Emp_DrawerCodeState();
}

class _Emp_DrawerCodeState extends State<Emp_DrawerCode> {

  SharedPreferences myPrefs;
  name() async{
     myPrefs=await SharedPreferences.getInstance();
    setState(() {
          getname=myPrefs.getString('name');
          getemail=myPrefs.getString('email');
          getdesignation=myPrefs.getString('designation');
   
        });
    
  }
  void initState(){
    name();
  }

  @override
  Widget build(BuildContext context) {
    return new Drawer(
      child: new ListView(
          padding: const EdgeInsets.all(0.0),
          children: <Widget>[
            
            new UserAccountsDrawerHeader(
                accountName: new Text(getname),
                accountEmail: new Text(getemail),
                currentAccountPicture: new CircleAvatar(
                  backgroundColor:
                  Theme.of(context).platform == TargetPlatform.android
                      ? Colors.white
                      : Colors.blue,
              child: Text(
                getname[0][0],
                style: TextStyle(fontSize: 40.0),
              ),
            ),
          ),
          new ListTile(
              title: new Text('Home'),
              leading: Icon(Icons.dashboard,color:Colors.grey),
              onTap: (){
                Navigator.pop(context);
                  Navigator.push(context, new MaterialPageRoute(
                    builder: (context)=> EmployeeNavigation()
                    )
                  );
              },
            ),
            new ListTile(
              title: new Text('Request for leave'),
              leading: Icon(Icons.request_page,color:Colors.grey),
              onTap: (){
                Navigator.pop(context);
                  Navigator.push(context, new MaterialPageRoute(
                    builder: (context)=>RequestForLeave()
                    )
                  );
              },
            ),
            new ExpansionTile(
              title: new Text('History'),
              children: <Widget>[
                ListTile(
                   title:new Text("My Attendance"),
                  leading: Icon(Icons.assessment_outlined ,color:Colors.grey),
                  onTap: (){
                Navigator.pop(context);
                  Navigator.push(context, new MaterialPageRoute(
                    builder: (context)=>new MyAttendance()
                    )
                  );
              },
                 
                ),
                ListTile(
                   title:new Text("Leaves"),
                  leading: Icon(Icons.assessment_outlined,color:Colors.grey ),
                  onTap: (){
                Navigator.pop(context);
                  Navigator.push(context, new MaterialPageRoute(
                    builder: (context)=>new LeaveHistory()
                    )
                  );
              },
                 
                ),
              ],
              leading: Icon(Icons.history,),
            
            ),
           
            new ListTile(
              title: new Text('Log out'),
              leading: Icon(Icons.logout,color:Colors.grey),
              onTap: (){
                myPrefs.setBool('login', true);
                Navigator.pop(context);
                  Navigator.push(context, new MaterialPageRoute(
                    builder: (context)=>
                    
                    Login()
                    )
                  );
              },
            ),
            
            ],
            
        ),
        

      
    );
  }
}

请帮助如何做到这一点。

【问题讨论】:

    标签: android flutter back-button-control


    【解决方案1】:

    我正在使用 navigator.push 方法,它正在按照您的意愿行事。

    appBar: AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.blue),
        onPressed: () => Navigator.of(context).pop(),
      ), 
      title: Text("Sample"),
      centerTitle: true,
    ),
    

    希望它能解决你的问题。

    【讨论】:

    • 但是我在appbar上使用了抽屉图标,我不能用这个,还有其他方法吗?更多的事情是 android 后退按钮的工作方式与 appbar 上的这个图标一样吗?
    • 您可以添加一个Row 小部件,然后添加您的抽屉图标和返回按钮@TimeToCode
    • 但是在appbar上使用2图标不是一个好主意,我想用android的后退按钮来完成它,而且大多数用户使用他们的手机后退按钮。
    • 在将用户发送到新页面之前,您需要清除页面历史记录。 Navigator.pop(context); Navigator.push(context, ... 你能不能删除 navigator.pop 然后试试这个。它必须解决问题。如果一切都不清楚,请告诉我。 @TimeToCode
    • @Z_Z 我这样做了,但是当我按下后退按钮时,它会进入登录屏幕(这是我的应用程序的第一个屏幕),然后当我单击登录按钮时,它会显示我的屏幕最后访问。
    【解决方案2】:

    您需要先澄清一下您的问题。

    正在使用页面视图/您是在谈论所有都是单独导航屏幕的场景还是一些不同的场景?

    我认为这是第二种情况,所有屏幕都是单独可导航的屏幕

    在这种情况下,每次用户导航到下一个屏幕时,您必须使用 Navigator.pushNamed() / Navigator.push() 因为现在我认为您正在使用 Navigator.pushReplacement( ) 这可能是导致此问题的原因。

    Navigator 只不过是一个知道内存中堆栈屏幕的类,它为我们提供的功能也是如此。 简单的推送意味着推过最后一个推送的屏幕,而推送一个替换最终会替换最后一个推送的屏幕阻止您导航到最后推送的屏幕。就像它在堆栈数据结构中的工作方式一样。

    【讨论】:

    • 嘿,我正在使用简单推送,我更新我的问题请检查代码
    【解决方案3】:

    首先用 WillPopScope 包裹你的脚手架

        return WillPopScope(
          onWillPop: _onBackPressed,
          child : Scaffold());
    

    然后你可以调用处理后按的函数。

    // Back Button Android Behaviour
          Future<bool> _onBackPressed() async {
            final shouldPop = await showDialog(
                context: context,
                builder: (context) => AlertDialog(
                      title: Text(
                        "Are you sure you want to leave this page?",
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: 25.0,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      actions: <Widget>[
                        SizedBox(width: 16),
                        InkWell(
                          onTap: () {
                            Navigator.pushAndRemoveUntil(
                              context,
                              MaterialPageRoute(
                                builder: (BuildContext context) => HomeScreen(), // Destination
                              ),
                              (route) => false,
                            );
                          },
                          child: Container(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              "LEAVE",
                              style: TextStyle(
                                color: Colors.red,
                                fontSize: 20.0,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 8.0),
                        InkWell(
                          onTap: () => Navigator.of(context).pop(false),
                          child: Container(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              "DO NOT LEAVE",
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 20.0,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ));
            return shouldPop ?? false;
          }
    

    【讨论】:

    • 你能检查更新的问题吗,我发布了一个代码,我怎么能在那里做到这一点?
    猜你喜欢
    • 1970-01-01
    • 2013-04-22
    • 2011-07-15
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 2017-06-20
    相关资源
    最近更新 更多