import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(
const ProviderScope(child: MyApp()),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int selectedIndex = 0;
var loadPages = [0];
@override
Widget build(BuildContext context) {
print("바텀 네비게이션 클릭할때마다 전체가 다시 그려지나?");
return Scaffold(
body: IndexedStack(
index: selectedIndex,
children: [
loadPages.contains(0) ? const APage() : Container(),
loadPages.contains(1) ? const BPage() : Container(),
],
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: selectedIndex,
onTap: (index) {
var pages = loadPages;
if (!pages.contains(index)) {
// 아직 열리지 않았다면!!
pages.add(index);
print(pages);
}
selectedIndex = index;
loadPages = pages;
setState(() {});
},
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: ""),
BottomNavigationBarItem(icon: Icon(Icons.person), label: ""),
],
),
);
}
}
class APage extends StatelessWidget {
const APage();
@override
Widget build(BuildContext context) {
// watch (통신)
print("APage 통신 시작됨");
return Center(
child: Text("APage"),
);
}
}
class BPage extends StatelessWidget {
const BPage();
@override
Widget build(BuildContext context) {
// watch (통신)
print("BPage 통신 시작됨");
return Center(
child: Text("BPage"),
);
}
}
I/flutter (18404): │ 🐛 디버그 : MainHolderPage 실행됨
I/flutter (18404): │ 🐛 디버그 : HomePage 실행됨
I/flutter (18404): │ 🐛 디버그 : HomePage 실행됨
I/flutter (18404): │ 🐛 디버그 : MainHolderPage 실행됨
I/flutter (18404): │ 🐛 디버그 : YourLibraryPage 실행됨
I/flutter (18404): │ 🐛 디버그 : YourLibraryPage 실행됨
I/flutter (18404): │ 🐛 디버그 : MainHolderPage 실행됨
I/flutter (18404): │ 🐛 디버그 : ProfilePage 실행됨
I/flutter (18404): │ 🐛 디버그 : ProfilePage 실행됨
전체 ViewModel이 실행되고 나면, ViewModel은 상태를 가진 상태로 재 실행되지 않는다.
I/flutter (18404): │ 🐛 디버그 : MainHolderPage 실행됨
I/flutter (18404): │ 🐛 디버그 : MainHolderPage 실행됨
I/flutter (18404): │ 🐛 디버그 : MainHolderPage 실행됨
참고
Flutter bottomNavigator with indexed stack