最近也有类似的问题,不过已经在 GitHub 上解决并关闭了。由于我是新手,我可能会在这里遗漏一些东西。方向更改后,页面索引恢复为零,但所选的 BottomNavigationBarItem 保持原样。此处显示页面“一”,但在旋转设备之前选择了选项卡“四”
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Pageview Orientation Bug',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _page = 0;
PageController _controller = PageController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: OrientationBuilder(
builder: (context,orientation) {
return orientation == Orientation.portrait
? Column(
children: [
Expanded(child: Container(color: Colors.grey)),
Expanded(
child: PageView(
controller: _controller,
children: [Text("ONE"), Text("TWO"),Text("THREE"), Text("FOUR"),],
),
),
],
)
: Row(
children: [
Expanded(child: Container(color: Colors.grey)),
Expanded(
child: PageView(
controller: _controller,
children: [Text("ONE"), Text("TWO"),Text("THREE"), Text("FOUR"),],
),
),
],
);
}
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _page,
onTap: (page) {
setState(() {
_page = page;
});
_controller.jumpToPage(page);
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.directions_bike),
label: "ONE",
),
BottomNavigationBarItem(
icon: Icon(Icons.directions_boat_outlined),
label: "TWO",
),
BottomNavigationBarItem(
icon: Icon(Icons.directions_car),
label: "THREE",
),
BottomNavigationBarItem(
icon: Icon(Icons.directions_run),
label: "FOUR",
),
],
),
);
}
}