1. 목적
- 부모 위젯에 있는 상태값을 자식 위젯에서 setState로 변경하려고 함
2. 조건
- 중앙에 todo 리스트가 있음
- 리스트는 진행 전 리스트와 삭제 완료 리스트로 나뉨
- default는 진행 전 리스트가 노출됨
- main 에 전역 상태값을 두고 리스트에 상태값을 전달해 진행 전, 삭제 완료 리스트를 노출할 수 있도록 함
- 이때 상태값은 bottom navagation bar를 클릭해서 설정함
3. 작업
// main.dart
import 'package:flutter/material.dart';
import 'package:sig_schedule_test/screens/schedule_list.dart';
import 'package:sig_schedule_test/screens/bottom_navigation_bar.dart';
class ScheduleMain extends StatefulWidget {
const ScheduleMain({Key? key}) : super(key: key);
@override
State<ScheduleMain> createState() => _ScheduleMainState();
}
class _ScheduleMainState extends State<ScheduleMain> {
//리스트 전역 상태값
int bottomIndex = 0;
//상태값 변경 함수
setBottomIndex(int index) {
setState(() {
bottomIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SigSchedule'),
),
body: ScheduleList(bottomIndex: bottomIndex), //리스트에 상태값 전달해서 진행 전 리스트 또는 삭제 완료 리스트 불러옴
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () async {
await showDialog(context: context, builder: (context) {
return AddJobDialog();
});
setState(() {});
},
),
bottomNavigationBar: CustomBottomNavagationBar(setBottomIndex: setBottomIndex), //bottom navagation bar에 전역 상태값 변경 함수 전달
);
}
}
// bottom navagation
// screens/bottom_navigation_bar.dart
import 'package:flutter/material.dart';
//전달받은 setBottomIndex 함수 정의
class CustomBottomNavagationBar extends StatefulWidget {
const CustomBottomNavagationBar({Key? key, required this.setBottomIndex}) : super(key: key);
final Function setBottomIndex;
@override
State<CustomBottomNavagationBar> createState() => _CustomBottomNavagationBarState();
}
class _CustomBottomNavagationBarState extends State<CustomBottomNavagationBar> {
int _selectedIndex = 0;
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
//bottom navagation 클릭 시 값을 받아서 함수에서 설정함, 이때 widget. 을 붙여주지 않으면 함수 인식 못 함
widget.setBottomIndex(index);
});
}
//bottom navagation logic
...
}
// 리스트
// screens/schedule_list.dart
import 'package:flutter/material.dart';
//전달받은 bottomIndex 변수 정의
class ScheduleList extends StatefulWidget {
const ScheduleList({Key? key, required this.bottomIndex}) : super(key: key);
final int bottomIndex;
@override
State<ScheduleList> createState() => _ScheduleListState();
}
class _ScheduleListState extends State<ScheduleList> {
//list logic
...
//리스트 불러오는 함수
Future<List<dynamic>> _getData() async {
//widget.bottomIndex로 상태값 가져옴
if (widget.bottomIndex == 1) {
...
}
}
}