Flutter:如何仅使用主屏幕中的按钮导航到第二个导航屏幕(底部导航)?

时间:2021-04-06 10:16:53

标签: flutter bottomnavigationview flutter-routes

在我的项目中,我为我的底部导航栏项目使用了索引。它控制了我拥有的所有三个主屏幕(主页、票务和个人资料)。从字面上看,我只是使用底部导航按钮在屏幕之间导航。作为替代方式,我想自定义一个位于主屏幕中的按钮。这样当它点击时,它就会导航到票务(第二个屏幕)。

我尝试使用 Navigator.pushNamed(context, screenName);,但它会堆叠在所有屏幕上方并且不显示 BottomNavigationBar。

1 个答案:

答案 0 :(得分:0)

import 'package:flutter/material.dart';  
  
void main() => runApp(MyApp());  
  
/// This Widget is the main application widget.  
class MyApp extends StatelessWidget {  
  @override  
  Widget build(BuildContext context) {  
    return MaterialApp(  
      home: MyNavigationBar (),  
    );  
  }  
}  
  
class MyNavigationBar extends StatefulWidget {  
  MyNavigationBar ({Key key}) : super(key: key);  
  
  @override  
  _MyNavigationBarState createState() => _MyNavigationBarState();  
}  
  
class _MyNavigationBarState extends State<MyNavigationBar > {  
  int _selectedIndex = 0;  
  static const List<Widget> _widgetOptions = <Widget>[  
    Text('Home Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),  
    Text('Search Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),  
    Text('Profile Page', style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold)),  
  ];  
  
  void _onItemTapped(int index) {  
    setState(() {  
      _selectedIndex = index;  
    });  
  }  
  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: const Text('Flutter BottomNavigationBar Example'),  
          backgroundColor: Colors.green  
      ),  
      body: Center(  
        child: _widgetOptions.elementAt(_selectedIndex),  
      ),  
      bottomNavigationBar: BottomNavigationBar(  
        items: const <BottomNavigationBarItem>[  
          BottomNavigationBarItem(  
            icon: Icon(Icons.home),  
            title: Text('Home'),  
            backgroundColor: Colors.green  
          ),  
          BottomNavigationBarItem(  
            icon: Icon(Icons.search),  
            title: Text('Search'),  
            backgroundColor: Colors.yellow  
          ),  
          BottomNavigationBarItem(  
            icon: Icon(Icons.person),  
            title: Text('Profile'),  
            backgroundColor: Colors.blue,  
          ),  
        ],  
        type: BottomNavigationBarType.shifting,  
        currentIndex: _selectedIndex,  
        selectedItemColor: Colors.black,  
        iconSize: 40,  
        onTap: _onItemTapped,  
        elevation: 5  
      ),  
    );  
  }  
}  

在 _onItemTapped(int index) 方法中只需更改您的视图索引,例如,最好创建一个控制器类,您可以实现任何其他小部件或类。

void _onItemTapped() {  
        setState(() {  
          _selectedIndex = 1;  
        });  
      }