如何使用CupertinoTabBar导航到其他选项卡上的其他页面? [英] How to navigate to a different page on a different tab using CupertinoTabBar?

查看:100
本文介绍了如何使用CupertinoTabBar导航到其他选项卡上的其他页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个选项卡-Tab1和Tab2. Tab1有3个页面-Tab1 Page1,Tab1 Page2,Tab1 Page3.

I have two tabs - Tab1 and Tab2. Tab1 has 3 pages - Tab1 Page1, Tab1 Page2, Tab1 Page3.

我希望能够从Tab2导航到Tab1 Page2.我可以使用controller.index = 0切换索引,但是不确定如何导航到该选项卡的Page2.什么是干净的解决方案?

I want to be able to navigate from Tab2 to Tab1 Page2. I can switch the index using controller.index = 0 but am not sure how to navigate to to Page2 of this tab. What is a clean solution for this?

// main.dart
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Cupertino Tab Bar Demo',
      theme: ThemeData(primarySwatch: Colors.blue, textTheme: TextTheme()),
      home: SafeArea(child: Scaffold(body: MyHomePage('Cupertino Tab Bar Demo Home Page'))),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage(this.title);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  var navigatorKeyList = [GlobalKey<NavigatorState>(), GlobalKey<NavigatorState>()];
  var currentIndex = 0;
  var controller = CupertinoTabController(initialIndex: 0);

  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      controller: controller,
      tabBar: CupertinoTabBar(
        onTap: (index) {
          if (currentIndex == index) {
            // Navigate to the tab's root route
            navigatorKeyList[index].currentState.popUntil((route) {
              return route.isFirst;
            });
          }
          currentIndex = index;
        },
        items: [
          BottomNavigationBarItem(title: Text('Tab 1'), icon: Icon(Icons.ac_unit)),
          BottomNavigationBarItem(title: Text('Tab 2'), icon: Icon(Icons.ac_unit)),
        ],
      ),
      tabBuilder: (BuildContext _, int index) {
        switch (index) {
          case 0:
            return CupertinoTabView(
              navigatorKey: navigatorKeyList[index],
              routes: {
                '/': (context) => WillPopScope(
                      child: Page1(),
                      onWillPop: () => Future<bool>.value(true),
                    ),
                'page1b': (context) => Page1b(),
                'page1c': (context) => Page1c(),
              },
            );
          case 1:
            return CupertinoTabView(
              navigatorKey: navigatorKeyList[index],
              routes: {
                '/': (context) => WillPopScope(
                      child: Page2(controller),
                      onWillPop: () => Future<bool>.value(true),
                    )
              },
            );
          default:
            return Text('Index must be less than 2');
        }
      },
    );
  }
}

// Tab1 Page1
class Page1 extends StatelessWidget {
  Page1();

  @override
  Widget build(BuildContext context) {
    return BaseContainer(
      Column(
        children: <Widget>[
          Container(
            child: Text(
              'Tab1',
              style: Theme.of(context).textTheme.headline4,
            ),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page2'),
            onPressed: () {
              Navigator.pushNamed(context, 'page1b');
            },
          )
        ],
      ),
    );
  }
}

// Tab1 Page2
class Page1b extends StatelessWidget {
  Page1b();

  @override
  Widget build(BuildContext context) {
    return BaseContainer(
      Column(
        children: <Widget>[
          Container(
            child:
                Text('Tab1 Page2', style: Theme.of(context).textTheme.headline4),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page3'),
            onPressed: () {
              Navigator.pushNamed(context, 'page1c');
            },
          )
        ],
      ),
    );
  }
}

// Tab2
class Page2 extends StatelessWidget {
  final CupertinoTabController controller; 

  const Page2(this.controller);

  @override
  Widget build(BuildContext context) {
    return BaseContainer(
      Column(
        children: <Widget>[
          Container(
            child: Text(
              'Tab2',
              style: Theme.of(context).textTheme.headline4,
            ),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page2 (TODO)'),
            onPressed: () {
              // TODO I want this to go to Tab1 Page2
              this.controller.index = 0;
              Navigator.of(context).pushNamed('page1b');
            },
          )
        ],
      ),
    );
  }
}

推荐答案

您可以在
下复制粘贴运行完整代码 步骤1:您可以将navigatorKeyList[0])传递给Page2
步骤2:呼叫navigatorKey.currentState.pushNamed("page1b");并更改index

You can copy paste run full code below
Step 1: You can pass navigatorKeyList[0]) to Page2
Step 2: call navigatorKey.currentState.pushNamed("page1b"); and change index

代码段

return CupertinoTabView(
              navigatorKey: navigatorKeyList[index],
              routes: {
                '/': (context) => WillPopScope(
                      child: Page2(controller, navigatorKeyList[0]),
                      onWillPop: () => Future<bool>.value(true),
                    )
              },
            );
...         
class Page2 extends StatelessWidget {
  final CupertinoTabController controller;
  final GlobalKey<NavigatorState> navigatorKey;
  const Page2(this.controller, this.navigatorKey);
  ...
    FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page2 (TODO)'),
            onPressed: () {
              navigatorKey.currentState.pushNamed("page1b");
              this.controller.index = 0;
            },
          )

工作演示

完整代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Cupertino Tab Bar Demo',
      theme: ThemeData(primarySwatch: Colors.blue, textTheme: TextTheme()),
      home: SafeArea(
          child:
              Scaffold(body: MyHomePage('Cupertino Tab Bar Demo Home Page'))),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage(this.title);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  var navigatorKeyList = [
    GlobalKey<NavigatorState>(),
    GlobalKey<NavigatorState>()
  ];
  var currentIndex = 0;
  var controller = CupertinoTabController(initialIndex: 0);

  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      controller: controller,
      tabBar: CupertinoTabBar(
        onTap: (index) {
          if (currentIndex == index) {
            // Navigate to the tab's root route
            navigatorKeyList[index].currentState.popUntil((route) {
              return route.isFirst;
            });
          }
          currentIndex = index;
        },
        items: [
          BottomNavigationBarItem(
              title: Text('Tab 1'), icon: Icon(Icons.ac_unit)),
          BottomNavigationBarItem(
              title: Text('Tab 2'), icon: Icon(Icons.ac_unit)),
        ],
      ),
      tabBuilder: (BuildContext _, int index) {
        switch (index) {
          case 0:
            return CupertinoTabView(
              navigatorKey: navigatorKeyList[index],
              routes: {
                '/': (context) => WillPopScope(
                      child: Page1(),
                      onWillPop: () => Future<bool>.value(true),
                    ),
                'page1b': (context) => Page1b(),
                'page1c': (context) => Page1c(),
              },
            );
          case 1:
            return CupertinoTabView(
              navigatorKey: navigatorKeyList[index],
              routes: {
                '/': (context) => WillPopScope(
                      child: Page2(controller, navigatorKeyList[0]),
                      onWillPop: () => Future<bool>.value(true),
                    )
              },
            );
          default:
            return Text('Index must be less than 2');
        }
      },
    );
  }
}

// Tab1 Page1
class Page1 extends StatelessWidget {
  Page1();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text(
              'Tab1',
              style: Theme.of(context).textTheme.headline4,
            ),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page2'),
            onPressed: () {
              Navigator.pushNamed(context, 'page1b');
            },
          )
        ],
      ),
    );
  }
}

// Tab1 Page2
class Page1b extends StatelessWidget {
  Page1b();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text('Tab1 Page2',
                style: Theme.of(context).textTheme.headline4),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page3'),
            onPressed: () {
              Navigator.pushNamed(context, 'page1c');
            },
          )
        ],
      ),
    );
  }
}

class Page1c extends StatelessWidget {
  Page1c();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text('Tab1 Page2',
                style: Theme.of(context).textTheme.headline4),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page3'),
            onPressed: () {
              Navigator.pushNamed(context, 'page1c');
            },
          )
        ],
      ),
    );
  }
}

// Tab2
class Page2 extends StatelessWidget {
  final CupertinoTabController controller;
  final GlobalKey<NavigatorState> navigatorKey;
  const Page2(this.controller, this.navigatorKey);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text(
              'Tab2',
              style: Theme.of(context).textTheme.headline4,
            ),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page2 (TODO)'),
            onPressed: () {
              navigatorKey.currentState.pushNamed("page1b");
              this.controller.index = 0;
            },
          )
        ],
      ),
    );
  }
}

完整代码2

    import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Cupertino Tab Bar Demo',
      theme: ThemeData(primarySwatch: Colors.blue, textTheme: TextTheme()),
      home: SafeArea(
          child:
              Scaffold(body: MyHomePage('Cupertino Tab Bar Demo Home Page'))),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage(this.title);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  var navigatorKeyList = [
    GlobalKey<NavigatorState>(),
    GlobalKey<NavigatorState>()
  ];
  int currentIndex = 0;
  var controller = CupertinoTabController(initialIndex: 0);

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

  @override
  Widget build(BuildContext context) {
    return CupertinoTabScaffold(
      controller: controller,
      tabBar: CupertinoTabBar(
        onTap: (index) {
          if (currentIndex == index) {
            // Navigate to the tab's root route
            navigatorKeyList[index].currentState.popUntil((route) {
              return route.isFirst;
            });
          }
          currentIndex = index;
        },
        items: [
          BottomNavigationBarItem(
              title: Text('Tab 1'), icon: Icon(Icons.ac_unit)),
          BottomNavigationBarItem(
              title: Text('Tab 2'), icon: Icon(Icons.ac_unit)),
        ],
      ),
      tabBuilder: (BuildContext _, int index) {
        switch (index) {
          case 0:
            return CupertinoTabView(
              navigatorKey: navigatorKeyList[index],
              routes: {
                '/': (context) => WillPopScope(
                      child: Page1(controller, navigatorKeyList[1]),
                      onWillPop: () => Future<bool>.value(true),
                    ),
                'page1b': (context) => Page1b(),
                'page1c': (context) => Page1c(),
              },
            );
          case 1:
            return CupertinoTabView(
              navigatorKey: navigatorKeyList[index],
              routes: {
                '/': (context) => WillPopScope(
                      child: Page2(controller, navigatorKeyList[0]),
                      onWillPop: () => Future<bool>.value(true),
                    )
              },
            );
          default:
            return Text('Index must be less than 2');
        }
      },
    );
  }
}

// Tab1 Page1
class Page1 extends StatelessWidget {
  final CupertinoTabController controller;
  final GlobalKey<NavigatorState> navigatorKey;
  const Page1(this.controller, this.navigatorKey);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text(
              'Tab1',
              style: Theme.of(context).textTheme.headline4,
            ),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab2 Page2'),
            onPressed: () async {
              controller.index = 1;
              await Future.delayed(Duration(seconds: 1), () {});
              navigatorKey.currentState.pushNamed("/");
            },
          )
        ],
      ),
    );
  }
}

// Tab1 Page2
class Page1b extends StatelessWidget {
  Page1b();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text('Tab1 Page2',
                style: Theme.of(context).textTheme.headline4),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page3'),
            onPressed: () {
              Navigator.pushNamed(context, 'page1c');
            },
          )
        ],
      ),
    );
  }
}

class Page1c extends StatelessWidget {
  Page1c();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text('Tab1 Page2',
                style: Theme.of(context).textTheme.headline4),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page3'),
            onPressed: () {
              Navigator.pushNamed(context, 'page1c');
            },
          )
        ],
      ),
    );
  }
}

// Tab2
class Page2 extends StatelessWidget {
  final CupertinoTabController controller;
  final GlobalKey<NavigatorState> navigatorKey;
  const Page2(this.controller, this.navigatorKey);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text(
              'Tab2',
              style: Theme.of(context).textTheme.headline4,
            ),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab1 Page2 (TODO)'),
            onPressed: () async {
              navigatorKey.currentState.pushNamed("page1b");
              await Future.delayed(Duration(seconds: 1), () {});
              this.controller.index = 0;
            },
          )
        ],
      ),
    );
  }
}

完整代码3

return CupertinoTabView(
          navigatorKey: navigatorKeyList[index],
          routes: {
            '/': (context) => WillPopScope(
                  child: Page1(controller, navigatorKeyList),
                  onWillPop: () => Future<bool>.value(true),
                ),
            'page2b': (context) => Page2b(),
            'page3b': (context) => Page3b(),
          },
        );

...
import 'package:cupertino_tab_bar/base_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Page1 extends StatelessWidget {
  final CupertinoTabController controller;
  final List<GlobalKey<NavigatorState>> navigatorKeyList;
  const Page1(this.controller, this.navigatorKeyList);

  @override
  Widget build(BuildContext context) {
    return BaseContainer(
      Column(
        children: <Widget>[
          Container(
            child: Text(
              'Tab1',
              style: Theme.of(context).textTheme.headline4,
            ),
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab2 Page2'),
            onPressed: () async{
              controller.index = 1;
              await Future.delayed(Duration(seconds: 1), () {});
              navigatorKeyList[1].currentState.pushNamed("page2b");
            },
          ),
          FlatButton(
            color: Colors.lightGreen,
            child: Text('Go to Tab3 Page2'),
            onPressed: () async{
              controller.index = 2;
              await Future.delayed(Duration(seconds: 1), () {});
              navigatorKeyList[2].currentState.pushNamed("page3b");Navigator.pushNamed(context, 'page3b');
            },
          )
        ],
      ),
    );
  }
}

这篇关于如何使用CupertinoTabBar导航到其他选项卡上的其他页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆