首先咱们想一下,若是在 Android 中实现 布局切换,一般的思路是:app
上边提到的用安卓原生作,思路是很明确,可是代码量仍是有的,那么来看一下, Flutter 如何使用 Viewpager 实现的。ide
首先建立有状态 StatefulWidget,而后构建 state:_ApplicationPageState布局
class ApplicationPage extends StatefulWidget { //@override //_ApplicationPageState createState() => new _ApplicationPageState(); 等同于上边注释掉的 createState(); @override State<StatefulWidget> createState() { // TODO: implement createState return _ApplicationPageState(); } }
Scaffold 实现了基本的纸墨设计布局结构。因此咱们 new Scaffold 而后 return 便可。ui
class _ApplicationPageState extends State<ApplicationPage> { int _currentPageIndex = 0; var _pageController = new PageController(initialPage: 0); @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("我是AppBar"), centerTitle: true, ), body: new PageView.builder( onPageChanged:_pageChange, controller: _pageController, itemBuilder: (BuildContext context,int index){ return index==1?new Text("我是第一页"):new Text("我是第二页"); }, itemCount: 2, ), bottomNavigationBar: new BottomNavigationBar(items: [ BottomNavigationBarItem( icon: new Icon(Icons.category), title: new Text("首页")), BottomNavigationBarItem( icon: new Icon(Icons.message), title: new Text("个人")), ], currentIndex: _currentPageIndex, onTap: onTap, ), ); } // bottomnaviagtionbar 和 pageview 的联动 void onTap(int index) { // 过pageview的pagecontroller的animateToPage方法能够跳转 _pageController.animateToPage(index, duration: const Duration(milliseconds: 300), curve: Curves.ease); } void _pageChange(int index) { setState(() { if (_currentPageIndex != index) { _currentPageIndex = index; } }); } }
关于上边有几个方法:spa
经过上边的代码也能够发现,pageView有个 onPageChanged 属性,而且类中定义了一个 _pageChange 方法,设计
经过 pageview 的 pagecontroller 的 animateToPage 方法实现的界面跳转;code