[flutter] 플러터에서의 Swipeable 화면 저장 처리 방법

플러터 앱에서 swipeable한 화면을 구현하고, 그 상태를 저장하고 복원하는 방법에 대해 알아보겠습니다.

Swipeable 화면 구현

Swipeable한 화면을 구현하기 위해서는 flutter_swipe_action_cell과 같은 라이브러리를 사용할 수 있습니다. 이 라이브러리를 사용하여 간단히 swipeable한 화면을 구현할 수 있습니다.

import 'package:flutter/material.dart';
import 'package:flutter_swipe_action_cell/flutter_swipe_action_cell.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Swipeable 화면')),
        body: ListView.builder(
          itemCount: 10,
          itemBuilder: (context, index) {
            return SwipeActionCell(
              key: ObjectKey(index),
              child: ListTile(title: Text('Item $index')),
              trailingActions: <SwipeAction>[
                SwipeAction(
                  onTap: (CompletionType type) {
                    // handle action
                  },
                  color: Colors.green,
                  icon: Icons.check,
                ),
                SwipeAction(
                  onTap: (CompletionType type) {
                    // handle action
                  },
                  color: Colors.red,
                  icon: Icons.delete,
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}

화면 상태 저장 및 복원

화면의 상태를 저장하고 복원하기 위해서는 shared_preferences 라이브러리를 이용할 수 있습니다.

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MyStatefulWidget extends StatefulWidget {
  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _selectedIndex = 0;
  late SharedPreferences _prefs;

  @override
  void initState() {
    super.initState();
    _loadState();
  }

  void _loadState() async {
    _prefs = await SharedPreferences.getInstance();
    setState(() {
      _selectedIndex = _prefs.getInt('selectedIndex') ?? 0;
    });
  }

  void _onItemTap(int index) {
    setState(() {
      _selectedIndex = index;
      _prefs.setInt('selectedIndex', index);
    });
  }

  @override
  Widget build(BuildContext context) {
    return BottomNavigationBar(
      items: <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          label: 'Home'
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.business),
          label: 'Business'
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.school),
          label: 'School'
        ),
      ],
      currentIndex: _selectedIndex,
      onTap: _onItemTap,
    );
  }
}

위의 예제에서는 shared_preferences를 사용하여 _selectedIndex 값을 저장하고 복원하는 방법을 보여줍니다.

플러터에서 swipeable한 화면을 구현하고, 그 상태를 저장하고 복원하는 방법을 알아보았습니다. 이를 통해 사용자 경험을 향상시키고 앱의 유용성을 높일 수 있습니다.