본문 바로가기

Flutter

Flutter - PageView에서 각 페이지의 값 유지하기

PageView에서 각 페이지를 넘기면 값이 초기화 된다. 

내가 지금 만들고 있는 앱에서 각 Page에 TextField가 있는데  유저가 입력한 값을 저장하고 

Page를 넘겨도 그래도 저장해야한다. 

 

https://cyj893.github.io/flutter/Flutter10/

 

Flutter - PageView: 페이지 스크롤해도 상태 저장하기, ExpandablePageView 등

 

cyj893.github.io

다음 블로그를 참고하였다. 

 

근데 여기서 주의해야할게 PageView 위젯에 다음 과정을 바로하는게 아닌 

상태를 저장할 item class에 해줘야한다. 

 

그래서 다음 코드를 보면 

PageView.builder에서 Container를 retrun 하는데 

이걸 따로 커스텀 위젯을 만들어 거기서 위 블로그에서 진행한 방식대로 코드를 입력했다. 

 

  Widget build(BuildContext context) {
    return PageView.builder(

        itemBuilder: (context, index) {
          return ContainerWidget(); #따로 빼준 위젯
        },
    );

 

# 여기서 해줌
class ContainerWidget extends StatefulWidget {
  const ContainerWidget({Key? key}) : super(key: key);

  @override
  State<ContainerWidget> createState() => _ContainerWidgetState();
}

class _ContainerWidgetState extends State<ContainerWidget> with AutomaticKeepAliveClientMixin {

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      child: TextField(),
      padding: EdgeInsets.all(30),
      margin: EdgeInsets.all(30),
      .
      .
      .