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

패키지 상세v1.1.0

fl_query

Flutter용 비동기 데이터 캐싱, 재요청 및 무효화 라이브러리

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
359
좋아요
38
Pub 점수
130

패키지 설치

flutter pub add fl_query

패키지 개요

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

fl_query는 비동기 데이터를 관리하기 위해 설계된 Flutter 패키지로, 내장 캐시, 자동 재요청 및 캐시 무효화 기능을 제공합니다. 데이터 가져오기, 로딩 상태, 오류 및 캐시된 응답을 효율적으로 처리함으로써 상태 관리를 간소화합니다. 실시간 또는 자주 업데이트되는 데이터가 필요한 앱에 적합하며, 반복 코드를 줄이고 앱 전체에서 일관된 데이터를 보장합니다. 이 라이브러리는 Flutter의 반응형 생태계와 원활하게 통합되며 모든 주요 플랫폼을 지원합니다.

사용 사례

  • 실시간 데이터 업데이트
  • 오프라인 우선 애플리케이션
  • API 데이터 동기화
  • 비동기 데이터를 가진 동적 UI
  • API 응답 캐싱
  • 자동 데이터 새로 고침

주요 기능

  • 내장 캐싱
  • 자동 재검색
  • 캐시 무효화
  • 최소한의 보일러플레이트
  • 크로스 플랫폼 지원
  • 오류 처리

적합한 대상

  • 상태 관리 사용 개발자
  • 자주 API 호출이 발생하는 앱
  • 오프라인 기능이 필요한 프로젝트
  • 개발자 생산성을 우선시하는 팀
  • 동적 콘텐츠를 가진 Flutter 앱

고려 사항

  • async/await 패턴에 대한 이해가 필요합니다
  • 큰 캐시를 사용할 경우 메모리 사용량이 증가할 수 있습니다
  • 중간에서 높은 데이터 주파수에 적합
  • 복잡한 캐시 전략에 대한 사용자 지정 제한
  • 간단한 정적 데이터에 적합하지 않음

원본 README

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

"Fl-Query Logo"

Fl-Query

Asynchronous data caching, refetching & invalidation library for Flutter. FL-Query lets you manage & distribute your async data without touching any global state

Fl-Query makes asynchronous server state management a breeze in flutter

Features

  • Async data caching & management
  • Smart + effective refetching
  • Optimistic updates
  • Automatically cached data invalidation & unneeded query/mutation garbage collection
  • Infinite pagination via InfiniteQuery
  • Lazy persistent cache (Uses hive for persisting query results to disk) (optional)
  • Easy to write & understand code. Follows DRY (Don't repeat yourself) convention
  • Compatible with both vanilla Flutter & elite flutter_hooks

Installation

Regular installation:

$ flutter pub add fl_query

For elite flutter_hooks user (Welcome to the flutter cool community btw😎)

$ flutter pub add flutter_hooks fl_query_hooks

Docs

You can find the documentation of fl-query at https://fl-query.krtirtho.dev/

Basic Usage

Initialize the cache databases in your main method

fl-query uses hive for persisting data to disk

void main()async {
  WidgetsFlutterBinding.ensureInitialized();
  await QueryClient.initialize(cachePrefix: 'fl_query_example');
  runApp(MyApp());
}

In MyApp Widget's build method wrap your MaterialApp with with QueryClientProvider widget

  Widget build(BuildContext context) {
    return QueryClientProvider(
      child: MaterialApp(
        title: 'Fl-Query Example App',
        theme: ThemeData(
          useMaterial3: true,
          primarySwatch: Colors.blue,
        ),
        home: const MyHomePage(),
      ),
    );
  }

Let's write use a Query now FL-Query provides a QueryBuilder widget that creates and listens to the specified Query and re-runs the builder function whenever there's an update

It has 2 required parameters(unnamed) key & builder

class MyApp extends StatelessWidget{
    MyApp({super.key});

    @override
    build(context){
      return QueryBuilder<String, dynamic>(
        'hello',
        () {
          return Future.delayed(
              const Duration(seconds: 6), () => 'Hello World!');
        },
        initial: 'A replacement',
        jsonConfig: JsonConfig(
          fromJson: (json) => json['data'],
          toJson: (data) => {'data': data},
        ),
        onData: (value) {
          debugPrint('onData: $value');
        },
        onError: (error) {
          debugPrint('onError: $error');
        },
        builder: (context, query) {
          if (query.isLoading) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else if (query.hasError) {
            return Center(
              child: Text(query.error.toString()),
            );
          }
          return Center(
            child: Text(query.data ?? "Unfortunately, there's no data"),
          );
        },
      );
    }
}

And if you're using flutter_hooks you got that too

class MyApp extends HookWidget{
    MyApp({super.key});

    @override
    build(context){
      final query = useQuery<String, dynamic>(
        'hello',
        () {
          return Future.delayed(
              const Duration(seconds: 6), () => 'Hello World!');
        },
        initial: 'A replacement',
        jsonConfig: JsonConfig(
          fromJson: (json) => json['data'],
          toJson: (data) => {'data': data},
        ),
        onData: (value) {
          debugPrint('onData: $value');
        },
        onError: (error) {
          debugPrint('onError: $error');
        },
      );

      if (query.isLoading) {
        return const Center(
            child: CircularProgressIndicator(),
          );
      } else if (query.hasError) {
        return Center(
          child: Text(query.error.toString()),
        );
      }
      return Center(
        child: Text(query.data ?? "Unfortunately, there's no data"),
      );
    }
}

To master the fl-query follow the official blog at https://fl-query.krtirtho.dev/blog

Why?

The hell, why?

The main purpose of Fl-Query is providing the easiest way to manage the messy server-state part requiring the least amount of code with code reusability & performance This let's you focus more on those cool UI animations & transitions✨. Leave the boring stuff to fl-query

Q. Isn't FutureBuilder good?

No, of course not. Unless you're from 2013 or your app is a purely offline app

Q. So FutureProvider from riverpod or provider not enough?

Probably yes. Although riverpod@v2 has added a lot of caching related features but still optimistic updates, periodic refetching & disk persistence are missing. Let's not forget about infinite pagination, it's a nightmare😅. In case of provider, same story. It's a great package but it's not ideal for server-state management

Notice Board

We need some bada** coders to write tests and ruin our life🥲 100% coverage is our goal🙃

카테고리

의존성

의존성 목록 5 개

소스 저장소

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

아직 데이터가 없습니다.