240708 TIL

나고수·2024년 7월 8일
0

2024 TIL

목록 보기
30/94
post-thumbnail

① 배운 것
1. ios는 갤러리에 이미지를 저장할때 파일 이름을 커스텀 할 수 없다. IMG_인덱스 번호로 ios가 정한 대로만 저장이됨.

Flutter에서 addAutomaticKeepAlivesAutomaticKeepAliveClientMixin 사용법

Flutter에서 리스트나 그리드와 같은 스크롤 가능한 위젯을 사용할 때, 스크롤이 되어 화면에서 벗어난 아이템의 상태를 유지하고 싶다면 addAutomaticKeepAlivesAutomaticKeepAliveClientMixin을 사용해야 합니다. 이 블로그 포스트에서는 이 두 가지를 어떻게 사용하는지 설명하겠습니다.

addAutomaticKeepAlives란?

addAutomaticKeepAlives는 리스트나 그리드 위젯 내부에서 각 아이템이 자동으로 keep-alive 상태를 관리하도록 설정하는 속성입니다. 기본값은 true로 설정되어 있습니다. 이 속성이 true로 설정되면 리스트나 그리드의 각 아이템이 자동으로 상태를 유지하려고 시도합니다.

AutomaticKeepAliveClientMixin이란?

AutomaticKeepAliveClientMixin은 Flutter에서 제공하는 믹스인으로, 이를 사용하면 위젯이 스크롤에서 벗어나더라도 상태를 유지할 수 있습니다. 즉, 리스트나 그리드뷰에서 아이템들이 화면에서 벗어나도 해당 아이템의 상태가 초기화되지 않고 유지됩니다.

상태 유지를 위한 정확한 설정

addAutomaticKeepAlives가 기본적으로 true로 설정되어 있어도, 리스트 아이템에서 AutomaticKeepAliveClientMixin을 명시적으로 사용하여 상태를 유지해야 합니다. 다음은 ListViewAutomaticKeepAliveClientMixin을 함께 사용하는 예제입니다.

예제 코드

import 'package:flutter/material.dart';

class KeepAliveDemo extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Keep Alive Demo'),
      ),
      body: ListView.builder(
        itemCount: 100,
        itemBuilder: (context, index) {
          return KeepAliveItem(key: ValueKey(index));
        },
      ),
    );
  }
}

class KeepAliveItem extends StatefulWidget {
  const KeepAliveItem({Key? key}) : super(key: key);

  
  _KeepAliveItemState createState() => _KeepAliveItemState();
}

class _KeepAliveItemState extends State<KeepAliveItem>
    with AutomaticKeepAliveClientMixin {
  
  bool get wantKeepAlive => true;

  
  Widget build(BuildContext context) {
    super.build(context); // 이 라인은 꼭 필요합니다.
    return ListTile(
      title: Text('Item ${widget.key}'),
    );
  }
}

void main() => runApp(MaterialApp(home: KeepAliveDemo()));

위 코드에서 중요한 점은 다음과 같습니다:
1. KeepAliveItemAutomaticKeepAliveClientMixin을 믹스인합니다.
2. wantKeepAlive 속성을 true로 설정하여 이 아이템이 상태를 유지하도록 합니다.
3. super.build(context)를 호출하여 상태 유지 메커니즘이 제대로 작동하도록 합니다.

메모리 사용량과 성능 최적화

모든 아이템의 상태를 유지하면 메모리 사용량이 증가하고 성능에 영향을 미칠 수 있습니다. 특히 리스트가 매우 길 경우, 메모리 사용량이 크게 증가할 수 있습니다. 이는 불필요한 메모리 사용으로 이어질 수 있으며, 최적화된 성능을 위해서는 상태 유지를 꼭 필요한 아이템에만 적용하는 것이 좋습니다.

불필요한 리렌더링 방지와 메모리 사용

AutomaticKeepAliveClientMixin을 사용하면 리스트나 그리드의 아이템이 화면에서 벗어났다 다시 돌아올 때 재렌더링되지 않으므로 불필요한 리렌더링을 방지할 수 있습니다. 그러나, 이는 화면에 보이지 않는 아이템도 메모리에 계속 상주하게 되어 메모리 사용량이 증가하는 단점이 있습니다.

선택적 상태 유지 적용

리스트나 그리드의 모든 아이템에 상태 유지를 적용하는 대신, 필요에 따라 선택적으로 상태 유지를 적용할 수 있습니다. 예를 들어, 사용자가 상호작용한 아이템이나 특정 조건을 만족하는 아이템에만 AutomaticKeepAliveClientMixin을 적용할 수 있습니다. 이를 통해 메모리 사용량을 최적화할 수 있습니다.

선택적 상태 유지 예제

import 'package:flutter/material.dart';

class ConditionalKeepAliveDemo extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Conditional Keep Alive Demo'),
      ),
      body: ListView.builder(
        itemCount: 100,
        itemBuilder: (context, index) {
          return ConditionalKeepAliveItem(index: index, key: ValueKey(index));
        },
      ),
    );
  }
}

class ConditionalKeepAliveItem extends StatefulWidget {
  final int index;

  const ConditionalKeepAliveItem({Key? key, required this.index}) : super(key: key);

  
  _ConditionalKeepAliveItemState createState() => _ConditionalKeepAliveItemState();
}

class _ConditionalKeepAliveItemState extends State<ConditionalKeepAliveItem>
    with AutomaticKeepAliveClientMixin {
  bool _shouldKeepAlive = false;

  void _toggleKeepAlive() {
    setState(() {
      _shouldKeepAlive = !_shouldKeepAlive;
    });
  }

  
  bool get wantKeepAlive => _shouldKeepAlive;

  
  Widget build(BuildContext context) {
    super.build(context); // 이 라인은 꼭 필요합니다.
    return ListTile(
      title: Text('Item ${widget.index}'),
      trailing: IconButton(
        icon: Icon(
          _shouldKeepAlive ? Icons.star : Icons.star_border,
          color: _shouldKeepAlive ? Colors.yellow : null,
        ),
        onPressed: _toggleKeepAlive,
      ),
    );
  }
}

void main() => runApp(MaterialApp(home: ConditionalKeepAliveDemo()));

결론

리스트나 그리드뷰의 아이템 상태를 유지하는 것은 사용자 경험을 향상시키는 데 유용하지만, 모든 아이템에 적용하면 메모리 사용량이 증가할 수 있습니다. 따라서 필요한 경우에만 상태 유지를 적용하는 방식으로 성능을 최적화할 수 있습니다.

이러한 방법을 통해 리스트나 그리드의 성능을 최적화하면서도 필요한 아이템의 상태를 유지할 수 있습니다.


② 회고 (restropective)
나는 역시 마감일에 닥쳐서 하는걸 불안해하고 미리미리 해두는걸조아한다.

③ 개선을 위한 방법

profile
되고싶다

0개의 댓글