簡體   English   中英

當按下返回按鈕到 go 到上一條路線時,如何處理 flutter 底部導航欄?

[英]How to handle flutter bottom navigation bar when back button is pressed to go to the previous route?

我正在研究底部導航欄,但我無法完美地向后按到上一條路線。

如果我 select 多於底部導航欄視圖項目的兩個導航按鈕,那么當我按下返回按鈕時,它將關閉應用程序。

   return Scaffold(
    body: (_getBody(index, model)),
    bottomNavigationBar: BottomNavigationBar(
      backgroundColor: Colors.white,
      selectedItemColor: Color(0xFFf5851f),
      unselectedItemColor: Colors.grey,
      type: BottomNavigationBarType.fixed,
      currentIndex: index,

      // onTap: (value) => setState(() => index = value),
      onTap: (value) {
        setState(() => index = value);
        print(value);
      },
      items: [
        BottomNavigationBarItem(
            icon: Icon(Icons.restaurant),
            title: Text('GMA', style: Theme.of(context).textTheme.body2)),
        BottomNavigationBarItem(
            icon: Icon(Icons.call),
            title: Text('CALL ON ORDER',
                style: Theme.of(context).textTheme.body2)),
        BottomNavigationBarItem(
            icon: Icon(Icons.notifications),
            title:
                Text('NOTIFICATION', style: Theme.of(context).textTheme.body2)),
        BottomNavigationBarItem(
            icon: Icon(Icons.shopping_cart),
            title: Text('CART', style: Theme.of(context).textTheme.body2)),
        //TextStyle(fontSize: 12, fontWeight: FontWeight.w600))),
      ],
    ), 
       


Widget _getBody(int index, MainModel model) {
switch (index) {
  case 0:
    return firstpage(); // Create this function, it should return your first page as a widget
  case 1:
    return ProductSearch(); // Create this function, it should return your second page as a widget
  case 2:
    return Account(); // Create this function, it should return your third page as a widget
  case 3:
    return Cart(); // Create this function, it should return your fourth page as a widget
 }
}
       

試試這個,創建了一個自定義導航隊列來保存路線索引

import 'dart:collection';

import 'package:flutter/material.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


  ListQueue<int> _navigationQueue =ListQueue();
  int index=0;


  @override
  Widget build(BuildContext context) {

    return WillPopScope(

///this method will be called on press of the back button
      onWillPop: ()async{
     /* Use this code if you just want to go back to 0th index
         if(index == 0)
           return true;
         setState(() {
          index = 0;
        });
      return false;
    */

/* below code keeps track of all the navigated indexes*/
        if(_navigationQueue.isEmpty)
          return true;
        
        setState(() {
          index = _navigationQueue.last;
          _navigationQueue.removeLast();
        });
        return false;
      },


      child: Scaffold(
        body: (getBody(index)),


        bottomNavigationBar: BottomNavigationBar(
          backgroundColor: Colors.white,
          selectedItemColor: Color(0xFFf5851f),
          unselectedItemColor: Colors.grey,
          type: BottomNavigationBarType.fixed,

          currentIndex: index,



          // handles onTap on bottom navigation bar item
          onTap: (value) {
            _navigationQueue.addLast(index);
            setState(() => index = value);
            print(value);
          },


          items: [
            BottomNavigationBarItem(
                icon: Icon(Icons.restaurant),
                title: Text('GMA',)),
            BottomNavigationBarItem(
                icon: Icon(Icons.call),
                title: Text('CALL ON ORDER')),
            BottomNavigationBarItem(
                icon: Icon(Icons.notifications),
                title:Text('NOTIFICATION')),
            BottomNavigationBarItem(
                icon: Icon(Icons.shopping_cart),
                title: Text('CART'),),

          ],
        ),

      ),);


  }


  Widget getBody(int index) {
    switch (index) {
      case 0:
        return firstpage(); // Create this function, it should return your first page as a widget
      case 1:
        return ProductSearch(); // Create this function, it should return your second page as a widget
      case 2:
        return Account(); // Create this function, it should return your third page as a widget
      case 3:
        return Cart(); // Create this function, it should return your fourth page as a widget
    }
  }
}




@Niteesh我為您的答案添加了一些改進,以便它以正確的方式工作:

  // Initialize index on 0
  ListQueue<int> _navigationQueue = ListQueue();
  int _index = 0;


  // Change this section (If the queue is empty return first tab)
  onWillPop: () async {
    if (_navigationQueue.isEmpty) return true;
      setState(() {
      _navigationQueue.removeLast();
      int position = _navigationQueue.isEmpty ? 0 : _navigationQueue.last;
      _index = position;
    });
    return false;
  }

  // And this part (will remove repeated elements from the list)
  onTap: (index) {
    if(index != _index){
      _navigationQueue.removeWhere((element) => element == index);
      _navigationQueue.addLast(index);
      setState(() {
        this._index = index;
      });
    }
  },
  currentIndex: this._index,
  ...

這可能對某人有所幫助。 我有 2 個版本:

  1. 如果您第一次按下返回按鈕,它會導航到初始選項卡的主屏幕,然后下次離開應用程序:
   WillPopScope(
      onWillPop: () async {
        if (_selectedPageIndex != 0) {
        setState(() {
            _selectedPageIndex=0;
          });
          return false;
        }
        return true;
      },
      child: Scaffold(...
  1. 這可以追溯到_selectedPageIndex = 0並離開應用程序
   WillPopScope(
      onWillPop: () async {
        if (_selectedPageIndex != 0) {
          setState(() {
            _selectedPageIndex--;
          }); 
          return false;
        }
        return true;
      },
      child: Scaffold(...

//edit: 改了一行代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM