如何在BLOC的Flutter中的BottomNavigationBar中设置currentIndex?

时间:2019-01-15 13:52:21

标签: dart flutter rxdart bloc

我想将 StatelessWidget BottomNavigationBar 一起使用,我可以通过BLOC对其进行控制。我可以将 Scaffold body BottomNavigationBar onTap 连接到BLOC(请参见代码) 。但是我不明白如何从BLOC(来自Observable)设置 BottomNavigationBar currentIndex

有什么好的解决方法吗?还是需要像https://stackoverflow.com/a/53019841/936780中那样使用 StatefulWidget

BLOC代码:

npm ci

小部件代码:

import numpy as np
import scipy.special

def volume (a,b,c,n): #where a,b,c are the axis of the ellipsoid and n 
is the accuracy of the monte carlo integration
    volume= (4/3)*np.pi*a*b*c

1 个答案:

答案 0 :(得分:2)

我认为您需要将Scaffold包裹在具有初始数据集的StreamBuilder中,然后才能访问快照数据。像这样(我必须对您的代码进行一些更改,以便它可以为我构建)

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final bloc = Bloc();

    final List<Widget> _children = [
      Container(color: Colors.blue, child: Center(child: Text("1"))),
      Container(color: Colors.red, child: Center(child: Text("2"))),
      Container(color: Colors.green, child: Center(child: Text("3"))),
      Container(color: Colors.yellow, child: Center(child: Text("4"))),
      Container(color: Colors.orange, child: Center(child: Text("5"))),
    ];

    return StreamBuilder<int>(
      stream: bloc.currentTabIndex,
      initialData: 0,
      builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
        if (!snapshot.hasData) {
          return Container();
        }

        return Scaffold(
          appBar: AppBar(
            title: Text("Test"),
          ),
          body: _children[snapshot.data],
          bottomNavigationBar: BottomNavigationBar(
            currentIndex: snapshot.data,
            onTap: (index) {
              bloc.setTabIndex(index);
            },
            items: _children
                .map((child) => BottomNavigationBarItem(
                    icon: Icon(Icons.add),
                    title: Text("Test"),
                    backgroundColor: Colors.black))
                .toList(),
          ),
        );
      },
    );
  }
}

这对我有用,这里唯一的缺点是每次索引更改时都将不必要地重建AppBar

相关问题