首页 > 解决方案 > Flutter 的 BottomNavigationBar 未在点击时更新所选项目

问题描述

我是 Flutter 的新手,目前正在尝试非常简单的练习来了解基础知识。我刚刚在屏幕底部创建了一个带有 BottomNavigationBar 的基本 Home。但是当我点击一个条形图标时,它不会切换颜色以使其看起来好像被点击了一样。我需要重新加载它以更新它。我无法从“ MyBottmNavigationBar ”类更新图标状态...如果我只是复制/粘贴 Flutter.dev 示例代码它可以工作...我需要在我的代码中修复什么?随时指出任何错误或提示!提前致谢!

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Home();
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyScaffold(),
    );
  }
}

class MyScaffold extends StatefulWidget {
  @override
  _MyScaffoldState createState() => _MyScaffoldState();
}

class _MyScaffoldState extends State<MyScaffold> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Hey Flutter'),),
      body: MyListView(),
      bottomNavigationBar: MyBottomNavigationBar(),
    );
  }
}


class MyListView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: const EdgeInsets.all(2),
      children: <Widget>[
        Container(
          height: 50,
          color: Colors.amber[600],
          child: const Center(child: Text('Entry A')),
        ),
        Container(
          height: 50,
          color: Colors.amber[500],
          child: const Center(child: Text('Entry B')),
        ),
        Container(
          height: 50,
          color: Colors.amber[100],
          child: const Center(child: Text('Entry C')),
        ),
        Container(
          height: 50,
          color: Colors.amber[600],
          child: const Center(child: Text('Entry A')),
        ),
      ],
    );
  }
}

class MyBottomNavigationBar extends StatefulWidget {
  MyBottomNavigationBar({Key key}) : super(key: key);

  @override
  _MyBottomNavigationBarState createState() => _MyBottomNavigationBarState();
}

class _MyBottomNavigationBarState extends State<MyBottomNavigationBar> {
  int _selectedIndex = 0;
  void _onItemTapped(int index){
    _selectedIndex = index;
    print('Selected: ${_selectedIndex} CurrentIndex: ${index}');
  }
  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      currentIndex: _selectedIndex,
      selectedItemColor: Colors.pink,
      onTap: _onItemTapped,
      items: const <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          title: Text('Home'),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.table_chart),
          title: Text('Projects'),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.people),
          title: Text('Teams'),
        ),
      ],
    );
  }
}
```

标签: flutter

解决方案


此外,不要在 build 方法中编写 ontapped() ,因为它创建了相同的实例并且从不更新视图。


推荐阅读