-
[ Flutter ] 콜백 함수 Navigation 페이지 이동Application/Flutter 2024. 7. 2. 00:41반응형
BottomNavigation 에서 탭을 누르면 페이지 이동을 구현
CallBack Function
페이지 이동을 위해
콜백함수 ValueChanged<int> onItemTapped 함수를 추가
콜백함수는 값이 변경될때마다 콜백함수를 호출하여 부모에게 값을 전달
class BottomNavigation extends StatefulWidget { final int selectedBtn; final ValueChanged<int> onItemTapped; const BottomNavigation({super.key, required this.selectedBtn, required this.onItemTapped}); @override State<BottomNavigation> createState() => _BottomNavigation(); }
탭을 누르면 widget.onItemTapped(i) 로 콜백함수를 호출
부모에게 전달 누른 탭 index 값을 전달하기위해 콜백함수 호출
AnimatedContainer navigationBar() { return AnimatedContainer( height: 70.0, duration: const Duration(milliseconds: 400), decoration: BoxDecoration( color: white, borderRadius: const BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20), ), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ for (int i = 0; i < navBtn.length; i++) GestureDetector( onTap: () => setState(() { widget.onItemTapped(i); }), child: iconBtn(i), ), ], ), ); }
반응형Parent Widget
부모 widget 에서 상태관리
부모 위젯에서 selectedBtn 값을 상태관리해주며
onItemTapped로 자식 위젯에서 전달받은 값을 setState() 를 통해 selectBtn 값을 업데이트
void _onItemTapped(int index) { setState(() { selectBtn = index; }); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: SafeArea( child: Scaffold( backgroundColor: mint, body: mainPages[selectBtn], bottomNavigationBar: BottomNavigation( selectedBtn: selectBtn, onItemTapped: _onItemTapped, ) ), ), ); }
Page Tab
페이지 관리를 위해 page.dart 파일을 만들어 페이지 리스트 생성
List<Widget> mainPages = <Widget>[ Calendar(), Home(), Profile(), ];
body에 mainPages[selectBtn] 으로 페이지 관리
@override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: SafeArea( child: Scaffold( backgroundColor: mint, body: mainPages[selectBtn], bottomNavigationBar: BottomNavigation( selectedBtn: selectBtn, onItemTapped: _onItemTapped, ) ), ), ); }
그러면 각 탭마다 다른 메뉴를 보여주도록 할 수 있다.
728x90반응형'Application > Flutter' 카테고리의 다른 글
[ Flutter ] 캐시 저장 SharedPreferences (0) 2024.07.07 [ Flutter ] 다크모드 설정 구현하기 (0) 2024.07.07 [ Flutter ] Flutter Color 관리 (0) 2024.06.30 [ Flutter ] Animation Navigation Bar (0) 2024.06.30 [ Flutter ] Border, Color Style 및 Layout 설정 (0) 2024.06.26