분류, 패키지 및 저장소 검색

after_init 표지
패키지 상세v0.2.0

after_init

상태가 있는 위젯에 상속된 위젯에 안전하게 액세스할 수 있는 didInitState() 생명주기 메서드를 추가합니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
155
좋아요
33
Pub 점수
160

패키지 설치

flutter pub add after_init

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

after_init 패키지는 initState() 이후 바로 호출되며 상속된 위젯이 완전히 사용 가능하다는 것을 보장하는 새로운 라이프사이클 메서드인 didInitState()를 도입함으로써 Flutter의 상태 기반 위젯을 강화합니다. 이로 인해 개발자는 null 값의 위험 없이 종속성이나 컨텍스트 기반 데이터에 안전하게 액세스할 수 있습니다. 의존성 주입 및 상태 관리 워크플로우를 단순화하여 초기화 로직에 대한 신뢰할 수 있는 훅을 제공합니다. 이 패키지는 가볍고 모든 주요 플랫폼과 호환되어, 상속된 위젯에 조기에 접근이 필요한 앱에 이상적입니다.

사용 사례

  • initState 이후 상속된 위젯에 액세스하기
  • 의존성 주입 설정 간소화
  • 컨텍스트에 따라 달라지는 데이터로 상태 초기화
  • initState에서 null 확인 회피
  • 안전한 위젯 트리 탐색 보장
  • 초기화 로직 간소화

주요 기능

  • 새로운 didInitState() 라이프사이클 메서드
  • 상속된 위젯에 대한 보장된 액세스
  • 경량이며 최소한의 오버헤드
  • 크로스 플랫폼 호환성
  • 기존 코드와의 간편한 통합
  • 추가적인 보일러플레이트 없음

적합한 대상

  • 상속 위젯을 사용하는 개발자
  • 복잡한 종속성 주입을 가진 앱
  • 조기 컨텍스트 접근이 필요한 상태 유지 위젯
  • 청소된 초기화 패턴을 우선시하는 팀
  • 널 안전성 위험을 줄이려는 프로젝트
  • Flutter 초보자가 라이프사이클 메서드 배우기

고려 사항

  • Flutter의 라이프사이클에 대한 이해가 필요합니다
  • 상속된 종속성이 없는 간단한 위젯에는 필요하지 않음
  • 과도하게 사용하면 복잡성이 증가할 수 있습니다
  • 상태가 있는 위젯만 가능
  • 다른 상태 관리 솔루션을 대체하지 않습니다
  • 기존의 상태 관리 방법과 함께 사용하는 것이 가장 좋습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

after_init

Adds a didInitState() lifecycle method to stateful widgets where you can safely access inherited widgets.

InheritedWidget is heavily used throughout the Flutter framework. Many state management packages such as ScopedModel and Provider use it as well. Unfortunately, InheritedWidgets are not accessible from the initState() method of State. The Flutter documentation states:

/// You cannot use [BuildContext.inheritFromWidgetOfExactType] from this
/// method. However, [didChangeDependencies] will be called immediately
/// following this method, and [BuildContext.inheritFromWidgetOfExactType] can
/// be used there.

This package consists of a simple mixin on the State class that provides a new method called didInitState(). It is only called exactly once, after initState(), and before didChangeDependencies() and build(). You can safely access InheritedWidgets from this method, and use them to perform any setup tasks for your widget.

Method Order

With this library, State methods are invoked in the following order:

  1. initState()
  2. didInitState()← new!
  3. didChangeDependencies()
  4. build()

Learn more about the Stateful Widget Lifecycle.

Example

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

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        body: Example(),
      ),
    ),
  );
}

class Example extends StatefulWidget {
  @override
  State<Example> createState() => _ExampleState();
}

class _ExampleState extends State<Example> with AfterInitMixin<Example> {
  late Size size;

  /// This gets called first, as usual.
  @override
  void initState() {
    super.initState();
    // Your code here
  }

  /// This gets called after initState(), only once.
  /// Safely access inherited widgets here.
  @override
  void didInitState() {
    // No need to call super.didInitState().
    // setState() is not required because build() will automatically be called by Flutter.
    size = MediaQuery.of(context).size;
  }

  /// This gets called after didInitState().
  /// And anytime the widget's dependencies change, as usual.
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Your code here
  }

  /// Finally this gets called, as usual.
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(size.toString()),
    );
  }
}

This is just a simplistic example. You would normally do something more useful in didInitState(), such as access setup data or subscribe to a Stream that comes from an InheritedWidget.

Alternative

A typical workaround for the initState() limitation is to delay execution of the code that needs to access InheritedWidget:

@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) {
    print(MediaQuery.of(context).size);
  });
}

However, this will cause your code to execute after the build() method, which may not be what you want.

Unit Tests

This package comes with unit tests that verify that didInitState() only gets called once and that State methods are invoked in the order specified above.

Credits

This package was inspired by the after_layout package.

카테고리

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.