如果您运行下面的代码,您将看到第一个选项卡正在执行您所看到的操作,而第二个选项卡是您所期望的。
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CupertinoStoreHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class CupertinoStoreHomePage extends StatelessWidget {
const CupertinoStoreHomePage({title});
@override
Widget build(BuildContext context) {
return CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.bell),
title: Text('TAB1'),
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.bell_solid),
title: Text('TAB2'),
),
],
),
tabBuilder: (context, index) {
switch (index) {
case 0:
return CupertinoTabView(builder: (context) {
return CupertinoPageScaffold(
child: TAB1(),
);
});
case 1:
return CupertinoTabView(
builder: (context) {
return CupertinoPageScaffold(
child: TAB2(),
);
},
routes: {
'/screen': (ctx) => NextScreen(),
},
);
default:
return Container();
}
},
);
}
}
class TAB1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("TAB1"),
),
body: Container(
child: FlatButton(
child: Text("Go To Next Screen"),
onPressed: () => Navigator.of(context)
.push(MaterialPageRoute(builder: (_) => NextScreen())),
),
),
);
}
}
class TAB2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("TAB2"),
),
body: Container(
child: FlatButton(
child: Text("Go To Next Screen"),
onPressed: () => Navigator.of(context).pushNamed("/screen"),
)),
);
}
}
class NextScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Scaffold(
appBar: AppBar(
title: Text("NextScreen"),
),
body: Container(
child: Text("NextScreen"),
),
),
);
}
}
使用 Navigator.of(ctx).push 时,应用程序尝试在根导航器上推送新屏幕,在您的情况下是标签栏,但它无法替换标签栏,因此您会看到不完整的动画。但是,在第二种方法中,您在相关选项卡中定义了路由并使用 Push Named,应用程序使用分配给该选项卡的导航器,从而获得预期的结果。
快乐编码!