如何导航到具有BottomNavigationBar的屏幕并同时更改BottomNavigationBar的选项卡?

时间:2020-05-28 16:13:57

标签: flutter dart

我想同时浏览屏幕并更改bottomNavigationBar中的选项卡。

....

class _MainPageState extends State<MainPage> with TickerProviderStateMixin {
  ...

  Widget selectedAppBar(int index) {
    ...
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: selectedAppBar(_selectedIndex),
        body: SafeArea(
          child: _screenOptions.elementAt(_selectedIndex),
        ),
        bottomNavigationBar: BottomNavigation(
          onChangeScreen: _onChangeScreen,
          selectedIndex: _selectedIndex,
        ),
      );
  }

  ...
}

其他页面,有一个底部,当我单击它时,将导航到主屏幕并更改BottomNavigationBar的选项卡

....

class _ItemState extends State<ItemPage> {

  ItemScreenArguments _screenArguments;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _screenArguments = ModalRoute.of(context).settings.arguments;
    final item = _screenArguments.item;

    return BlocBuilder<CartBloc, CartState>(
      builder: (BuildContext context, CartState state) {
        ...

        final cart = (state as LoadCartState);
        return Scaffold(
          extendBodyBehindAppBar: true,
          appBar: AppBar(
          backgroundColor: Colors.transparent,
            title: Text(item.name),
              actions: [
                Basket(
                  count: cart.count,
                  onTap: () {
                   // It should navigate main route and fourth section in bottomNavigationBar
                   Navigator.of(context).popUntil(ModalRoute.withName('/main'))
                  },
                )
              ]
            ),
            body: ItemScreen(),
            ...
        );
      }
    );
  }

我尝试使用Bloc还是使用Bloc是个坏主意?

使用Router MaterialPageRoute比使用Bloc更好还是将它们结合使用?你怎么做?您能帮忙选择更好的选择吗?

1 个答案:

答案 0 :(得分:0)

您可以发送默认要选择的标签号

Navigate.of(context).pushNamed("/main",arguments:{'tab':3})

您可以使用 ModalRoute 检索此标签号,并相应地设置 _selectedIndex

Widget build(BuildContext context) {
   final route= ModalRoute.of(context).settings.arguments as Map<String,int>;
   var _selectedIndex = route['tab']

    return Scaffold(
        appBar: selectedAppBar(_selectedIndex),
        body: SafeArea(
          child: _screenOptions.elementAt(_selectedIndex),
        ),
        bottomNavigationBar: BottomNavigation(
          onChangeScreen: _onChangeScreen,
          selectedIndex: _selectedIndex,
        ),
      );
  }