본문 바로가기
Flutter

AutoDispose와 keepAlive의 차이점 완벽 정리

by 안될개발 2025. 1. 17.

AutoDispose와 keepAlive의 차이점

AutoDispose와 keepAlive의 차이점 완벽 정리

Flutter에서 상태 관리는 성능과 사용자 경험에 직결되는 중요한 부분입니다. 특히 Riverpod을 사용할 때 AutoDispose와 keepAlive는 메모리 관리상태 유지에 핵심적인 역할을 합니다.

이번 글에서는 AutoDispose와 keepAlive의 차이점을 명확히 설명하고, 각각의 동작 방식, 사용 사례, 성능 최적화에 어떻게 도움이 되는지 구체적인 예제와 함께 알아보겠습니다.

1. AutoDispose란?

AutoDispose는 프로바이더의 생명 주기를 관리하는 기능으로, 해당 프로바이더를 더 이상 사용하지 않을 때 자동으로 메모리에서 해제합니다.

📌 AutoDispose의 기본 문법

final counterProvider = StateProvider.autoDispose<int>((ref) => 0);

✅ AutoDispose의 주요 특징

  • 자동 해제: 위젯이 사라지면 프로바이더의 상태도 메모리에서 제거됨
  • 리소스 절약: 메모리 누수 방지 및 성능 최적화에 유용
  • 일시적 상태: 일회성 데이터 또는 화면 전환 시 필요한 경우 사용

📊 AutoDispose 예제

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

final counterProvider = StateProvider.autoDispose<int>((ref) => 0);

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 ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final counter = ref.watch(counterProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('AutoDispose 예제')),
      body: Center(child: Text('카운터: \$counter')),
      floatingActionButton: FloatingActionButton(
        onPressed: () => ref.read(counterProvider.notifier).state++,
        child: const Icon(Icons.add),
      ),
    );
  }
}

👉 특징 설명:

  • 화면을 벗어나면 counterProvider는 자동으로 해제됩니다.
  • 화면을 다시 열면 카운터 값이 초기화됩니다.

📌 AutoDispose의 주요 활용 사례

  • 일회성 작업: 비동기 API 호출 후 즉시 해제
  • 페이지 전환: 특정 페이지에서만 필요한 상태
  • 임시 입력 폼: 사용자 입력을 임시로 저장하는 경우

2. keepAlive란?

keepAlive()는 AutoDispose와 반대로 자동 해제를 방지하고 프로바이더의 상태를 유지하도록 합니다.

📌 keepAlive의 기본 문법

final counterProvider = StateProvider.autoDispose<int>((ref) {
  ref.keepAlive();
  return 0;
});

✅ keepAlive의 주요 특징

  • 상태 유지: 프로바이더가 해제되지 않도록 함
  • 성능 최적화: 빈번한 재생성을 방지하고 데이터 유지
  • 장기 사용: 페이지를 벗어나도 상태를 유지해야 할 때 사용

📊 keepAlive 예제

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

final counterProvider = StateProvider.autoDispose<int>((ref) {
  ref.keepAlive();
  return 0;
});

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 ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final counter = ref.watch(counterProvider);

    return Scaffold(
      appBar: AppBar(title: const Text('keepAlive 예제')),
      body: Center(child: Text('카운터: \$counter')),
      floatingActionButton: FloatingActionButton(
        onPressed: () => ref.read(counterProvider.notifier).state++,
        child: const Icon(Icons.add),
      ),
    );
  }
}

👉 특징 설명:

  • 화면을 벗어나도 카운터 값이 유지됩니다.
  • ref.keepAlive()를 통해 자동 해제 방지

📌 keepAlive의 주요 활용 사례

  • 캐싱 데이터: API 응답을 재사용할 때
  • 탭 유지: 하단 탭 네비게이션에서 각 페이지의 상태를 유지
  • 비용이 큰 작업: 계산 비용이 크거나 복잡한 상태를 재생성하지 않음

3. AutoDispose vs. keepAlive 차이점

기능 AutoDispose keepAlive
상태 유지 위젯이 사라지면 해제 위젯이 사라져도 상태 유지
성능 최적화 사용하지 않는 리소스를 자동으로 해제 빈번한 재생성을 방지해 성능 최적화
활용 사례 일회성 데이터, 임시 입력폼 캐시 유지, 하단탭 상태 보존, 계산 비용 최적화
사용 방법 StateProvider.autoDispose ref.keepAlive() 사용
재생성 위젯이 재빌드될 때마다 새로운 인스턴스 생성 인스턴스가 유지되며 재생성 없음

4. 언제 AutoDispose와 keepAlive를 사용할까?

✅ AutoDispose를 사용할 때

  • 임시 작업: 일회성 API 호출
  • 메모리 관리: 사용하지 않는 상태는 즉시 해제
  • 성능 최적화: 불필요한 리소스 소모 방지

✅ keepAlive를 사용할 때

  • 상태 유지: 페이지 전환 시 상태 보존
  • 복잡한 데이터: 재생성 비용이 큰 작업
  • 캐싱: API 데이터 재사용

5. 결론

  • AutoDispose는 사용하지 않는 리소스를 해제해 메모리를 절약합니다.
  • keepAlive는 상태를 유지해 성능을 최적화합니다.

상황에 맞는 기능을 사용해 Flutter 애플리케이션의 성능안정성을 극대화하세요.