如何在底部导航栏上使用或设置“轻按”

时间:2020-05-09 19:32:44

标签: flutter dart

我真的很陌生。我需要点击bottomnavigationBar,这将打开一个新页面。但是我应该在哪里使用onTap?在顶部(正文)上,我还有另一个导航(Tabbarview)。为什么我在BottomnavigationBar内没有“ onTap”

bottomNavigationBar: SnakeNavigationBar(
          style: SnakeBarStyle.floating,
          backgroundColor: Color(0xffFFFFFF),
          snakeColor: Color(0xff3f51b5),
          currentIndex: _selectedItemPosition,
          onPositionChanged: (index) =>
              setState(() => _selectedItemPosition = index),
          padding: EdgeInsets.all(4),
          items: [
            new BottomNavigationBarItem(icon: Icon(Icons.home)),
            new BottomNavigationBarItem(icon: Icon(Icons.description)),
            new BottomNavigationBarItem(icon: Icon(Icons.people)),
            new BottomNavigationBarItem(icon: Icon(Icons.settings)),
            new BottomNavigationBarItem(icon: Icon(Icons.battery_unknown)),
          ],
        )));

1 个答案:

答案 0 :(得分:0)

有多种使用BottomNavigationBar的方法,在您的情况下,这是一个库,其中将“ onPositionChanged”用作“ onTap”,不仅可以更新变量,还可以打开更改当前值。小部件显示在屏幕上。

以下是使用BottomNavigationBar在小部件之间进行切换的完整示例:

import 'package:flutter/material.dart';

void main() => runApp(Demo());

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: DemoApp());
  }
}

class DemoApp extends StatefulWidget {
  @override
  _DemoAppState createState() => _DemoAppState();
}

class _DemoAppState extends State<DemoApp> {
  Widget _currentWidget = Container();
  var _currentIndex = 0;

  Widget _homeScreen() {
    return Container(
      color: Colors.green,
    );
  }

  Widget _settingsScreen() {
    return Container(
      color: Colors.red,
    );
  }

  @override
  void initState() {
    super.initState();
    _loadScreen();
  }

  void _loadScreen() {
    switch(_currentIndex) {
      case 0: return setState(() => _currentWidget = _homeScreen());
      case 1: return setState(() => _currentWidget = _settingsScreen());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _currentWidget,
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() => _currentIndex = index);
          _loadScreen();
        },
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
          BottomNavigationBarItem(icon: Icon(Icons.settings), title: Text('Settings')),
        ],
      ),
    );
  }
}

其结果是以下应用程序: