패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.2.0

futuristic

StatelessWidget 내에서 Future를 안전하게 실행하고 재시도할 수 있게 합니다.

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

패키지 설치

flutter pub add futuristic

패키지 개요

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

Futuristic는 StatelessWidget 위젯 내에서 Futures의 안전한 실행 및 재시도 로직을 가능하게 하는 Flutter/Dart 패키지입니다. 상태 관리 없이 로딩 상태, 오류, 재시도를 관리할 수 있는 깔끔하고 선언적인 API를 제공하여 상태 없는 컨텍스트에서 비동기 작업을 간단히 처리할 수 있도록 합니다. 이 패키지는 Flutter의 위젯 트리와 원활하게 통합되며 모든 주요 플랫폼을 지원합니다. 응답성 있는 UI를 유지하면서 데이터를 가져오거나 비동기 작업을 수행해야 할 경우에 이상적입니다.

사용 사례

  • 상태 없는 위젯에서 데이터 가져오기
  • 실패한 비동기 작업에 대한 재시도 로직 구현
  • 로딩 및 오류 상태 표시
  • 비동기 콘텐츠를 사용하여 동적 UI 구축하기
  • 함수형 컴포넌트에서 비동기 처리 간소화

주요 기능

  • StatelessWidgets에서의 안전한 Future 실행
  • 내장된 재시도 메커니즘
  • 로딩 및 오류 상태 지원
  • 최소한의 보일러플레이트
  • 크로스 플랫폼 호환성

적합한 대상

  • StatelessWidget을 광범위하게 사용하는 개발자
  • 복잡한 상태 관리를 피하는 팀
  • 간단한 비동기 처리가 필요한 프로젝트
  • 자주 데이터를 가져오는 UI
  • 다중 플랫폼을 대상으로 하는 앱

고려 사항

  • 복잡한 상태 기반 로직에 적합하지 않습니다
  • 기본 재시도 전략에 제한됨
  • Futures 및 async/await에 대한 이해가 필요합니다
  • 전체 상태 관리 솔루션을 대체할 수 없을 수도 있습니다
  • 경량 비동기 작업에 최적

원본 README

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

futuristic

Makes it possible to safely execute and retry a Future inside a StatelessWidget.

See the Mainstream package for a similar API for working with Streams.

Problem

If you've ever tried to use the FutureBuilder widget in Flutter, you've probably been surprised by its behavior. When used inside a StatelessWidget, it will re-execute its Future every time it is rebuilt. Since a widget can be rebuilt many times in Flutter (including due to hot reload), this can be undesirable if our Future calls a non-idempotent REST API endpoint, for example.

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: myExpensiveFuture(),  //Will be executed every time Home is rebuilt
      builder: (_context, snapshot) {
        ...
      },
    );
  }
}

To execute our Future only once, we could use a StatefulWidget, but now we have the extra boilerplate of using a StatefulWidget and holding onto our Future in a state variable.

class Home extends StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Future _future;

  @override
  void initState() {
    super.initState();
    _future = myExpensiveFuture();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _future,  // Will be executed only once
      builder: (_context, snapshot) {
        ...
      },
    );
  }
}

Solution

The problem with FutureBuilder is, ironically, that it takes a Future instance as its input. Instead, the Futuristic widget takes a Function that returns a Future and holds onto it in its own State. This means:

  • It can be used in a StatelessWidget.
  • It can let child widgets start or retry a Future.

Additionally, Futuristic provides:

  • Multiple builder callbacks to provide mutually exclusive initial/busy/data/error widget states.
  • Optional onData/onError callbacks to perform additional actions when a Future succeeds or fails.
  • Generic type safety for the data provided to callbacks. The type parameter <T> can be omitted if it can be inferred from the futureBuilder function.

Usage

We can use the Futuristic widget to wrap a single component like a button, or even an entire screen.

Button example

To start executing a Future in response to a button press, connect its onPressed handler to the start function provided in the initialBuilder callback.

Future<int> myFuture(int first, int second) async {
  await Future.delayed(const Duration(seconds: 1));
  return first + second;
}

class MyButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Futuristic<int>(
      futureBuilder: () => myFuture(1, 2),
      initialBuilder: (context, start) => RaisedButton(child: Text('Go'), onPressed: start),
      busyBuilder: (context) => CircularProgressIndicator(),
      errorBuilder: (context, error, retry) => RaisedButton(child: Text('Oops'), onPressed: retry),
      dataBuilder: (context, data) => Text(data.toString()),
    );
  }
}

The futureBuilder parameter is required.

The initialBuilder parameter is required if autoStart is false (see example below).

The optional busyBuilder displays a widget when the Future is busy executing. By default, it shows a centered CircularProgressIndicator. By displaying this, we inform the user that the operation is in progress and also prevent the Future from being triggered twice accidentally.

The optional errorBuilder displays a widget when the Future has failed, typically with an Error or Exception. This is provided as a parameter, together with a retry function that can be called to "retry" the Future.

The optional dataBuilder displays a widget when the Future has succeded. The resulting T value of the Future<T> is provided as a parameter to the callback. Note that this will be null in the case of a Future<void>.

Screen example

To automatically start executing a Future upon navigating to a screen, set the autoStart parameter to true instead of providing an initialBuilder. The busyBuilder will be displayed immediately.

Future<int> myFuture(int first, int second) async {
  await Future.delayed(const Duration(seconds: 1));
  throw Exception('something happened');
  return first + second;
}

class MyScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Futuristic<int>(
      autoStart: true,
      futureBuilder: () => myFuture(1, 2),
      busyBuilder: (context) => CircularProgressIndicator(),
      onError: (error, retry) => showDialog(...),
      onData: (data) => showDialog(...),
    );
  }
}

The futureBuilder parameter is required.

The optional onError callback can be used to handle the error event by displaying an alert dialog or sending to a logging provider, for example. It can be used in place of or together with the errorBuilder. A retry function is provided as a parameter that can be called to "retry" the Future. Be careful not to call retry without user interaction to avoid creating an infinite loop. This callback will not be retriggered as a result of a widget rebuild.

The optional onData callback can be used to handle a successful result by displaying an alert dialog or performing navigation. for example. This can be used in place of or together with the dataBuilder. This callback will not be retriggered as a result of a widget rebuild.

카테고리

소스 저장소

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

아직 데이터가 없습니다.