Flutter BottomNavigationBar 调用导航器推送一个导航器项目

Flutter BottomNavigationBar call navigator push for one Navigator item

我有一个包含 4 个 BottomNavigaton 项的 BottomNavigationBar,我想要 3 个项来呈现主体的不同内容,这已经可以正常工作了。我希望第一项打开相机并 link 到一个全新的页面。我该怎么做?

我已经尝试过的附在下面。

我收到类似

的错误

setState() or markNeedsBuild() called during build. This Overlay widget cannot be marked as needing to build because the framework is already in the process of building widgets.

所以我觉得我调用CameraScreen的build方法太早了,但我不知道如何避免。

class TabScreen extends StatefulWidget {
      int index;
    
      TabScreen(this.index);
      @override
      _TabScreenState createState() => _TabScreenState(index);
   }

class _TabScreenState extends State<TabScreen> {
  int _selectedPageIndex;

  _TabScreenState([this._selectedPageIndex = 1]);

  final List<Map<String, Object>> _pages = [
    {
      // index = 0 should push new Screen without appbar & bottom nav bar and open camera
      'page': null,
      'title': 'Cam',
    },
    {
      'page': ListScreen(),
      'title': 'List',
    },
    {
      'page': TransportScreen(),
      'title': 'Transport',
    },
    {
      'page': ExportScreen(),
      'title': 'Export',
    }
  ]; 

void _selectPage(int index, BuildContext ctx) {
      setState(() {
          _selectedPageIndex = index;
      });
      // this part does not work
      // if (_selectedPageIndex == 0){
      //   Navigator.of(ctx).pushNamed(CameraScreen.routeName);
      // }
  }

@override
  Widget build(BuildContext context) {

    final bottomBar = BottomNavigationBar(
      currentIndex: _selectedPageIndex,
      onTap: (i) => _selectPage(i, context),
      items: const <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.camera_alt_outlined),
          label: 'Cam',
          // backgroundColor: Colors.red,
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.article_outlined),
          label: 'List',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.article_outlined),
          label: 'Transport',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.arrow_forward),
          label: 'Export',
        ),
      ],
    );    

    return Scaffold(
      appBar: AppBar(
        title: Text(_pages[_selectedPageIndex]['title']),
      ),
      body: _pages[_selectedPageIndex]['page'],
      bottomNavigationBar: BottomAppBar(
        shape: CircularNotchedRectangle(),
        notchMargin: 4,
        clipBehavior: Clip.antiAlias,
        child: bottomBar,
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: _buildActionButton(),
  );
 }
}

嗯,我自己解决了。上面的解决方案使用 Navigator.of(ctx).pushNamed(CameraScreen.routeName); 确实有效。

我的问题出在 CameraScreen 文件中,它在其构建函数中使用了一些小部件,并且变得太大而无法显示在屏幕上。