效果圖
1. 創(chuàng)建主頁面
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
final List<Widget> _pages = List();
PageController _controller;
@override
void initState() {
super.initState();
_pages..add(MainPage())..add(MinePage());
_controller = PageController(initialPage: 0);
}
@override
void dispose() {
super.dispose();
_controller.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: _buildBottomNavigationBarWidget(),
body: _buildBodyWidget(),
);
}
Widget _buildBodyWidget() {
return PageView.builder(
controller: _controller,
itemCount: _pages.length,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return _pages[index];
},
onPageChanged: (index) {
if (index != _controller) {
setState(() {
_currentIndex = index;
});
}
},
);
}
Widget _buildBottomNavigationBarWidget() {
return BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _currentIndex,
fixedColor: Colors.amber,
items: [
BottomNavigationBarItem(title: Text("首頁"), icon: Icon(Icons.home)),
BottomNavigationBarItem(title: Text("我的"), icon: Icon(Icons.person))
],
onTap: (index) {
_controller.jumpToPage(index);
},
);
}
}
2.創(chuàng)建2個(gè)子頁面
class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage>
with AutomaticKeepAliveClientMixin {
@protected
bool get wantKeepAlive => true;
int _count = 0;
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: AppBar(
title: Text("首頁"),
),
body: Center(
child: Text("狀態(tài)$_count"),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
setState(() {
_count++;
});
}),
);
}
}
class MinePage extends StatefulWidget {
@override
_MinePageState createState() => _MinePageState();
}
class _MinePageState extends State<MinePage>
with AutomaticKeepAliveClientMixin {
@protected
bool get wantKeepAlive => true;
int _count = 0;
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: AppBar(
title: Text("我的"),
),
body: Center(
child: Text("狀態(tài)$_count"),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
setState(() {
_count++;
});
}),
);
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者