如何使用BottomNavigationBar在.dart文件之间切换

时间:2020-07-31 17:20:03

标签: flutter dart

我不知道使用BottomNavigationBar在.dart文件之间进行切换的方法。我是飞镖的新手,实际上互联网上有很多信息,但是我看不到任何与此特别相关的信息。

import 'package:flutter/material.dart';
import 'Page1m1.dart';
import 'Page1m2.dart';
import 'Page1m3.dart';

class Page1 extends StatefulWidget {
@override
  _Page1State createState() => _Page1State();
}

class _Page1State extends State<Page1> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       home: Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          items: [
            BottomNavigationBarItem(
                icon: Icon(Icons.home),
                title: Text('justworkalr'),
            ),
            BottomNavigationBarItem(
                icon: Icon(Icons.home),
                title: Text('justworkalr'),
            ),
            BottomNavigationBarItem(
                icon: Icon(Icons.home),
                title: Text('justworkalr'),
            ),
          ],
        ),
      )
     );
  }
}

1 个答案:

答案 0 :(得分:0)

您需要导航到那里。 This可能会对您有所帮助。

通常来说,要更改屏幕,您需要一个“可点击的”小部件(或至少要触发一些可用来检测用户交互的事件),然后从那里触发路线导航:

// Within the `FirstRoute` widget
onPressed: () {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondRoute()),
  );
}

对于您的情况,this other示例可能也对您有所帮助。您可以看到_onItemTapped属性触发了onTab方法来更改状态。这将是放置导航的好位置。

  int _selectedIndex = 0;
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Index 0: Home',
      style: optionStyle,
    ),
    Text(
      'Index 1: Business',
      style: optionStyle,
    ),
    Text(
      'Index 2: School',
      style: optionStyle,
    ),
  ];

  void _onItemTapped(int index) {
    // navigate somewhere or change content according to index

    // for example change state and set the index to current selected 
    // this will load the other widget defined above
    setState(() {
        _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('Business'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            title: Text('School'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}