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

패키지 상세v0.0.3

data_widget

데이터 관련 보조 위젯 및 도구로 코드를 적게 사용하여 더 빠르게 플러터 앱을 구축할 수 있습니다.

AndroidiOSLinuxmacOSWebWindows
30일 다운로드
3.9만
좋아요
7
Pub 점수
160

패키지 설치

flutter pub add data_widget

패키지 개요

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

Data Widget는 Flutter/Dart 패키지로, 보조 위젯과 유틸리티를 제공함으로써 앱 내 데이터 처리를 간소화하도록 설계되었습니다. 뼈대 코드를 줄여 더 빠르게 개발하고, 깔끔하고 유지보수 용이한 UI를 구현할 수 있게 합니다. 이 패키지는 데이터 상태를 효율적으로 관리하고, 로딩 또는 오류 표시를 표시하며, 위젯 간의 데이터 바인딩을 단순화하는 도구를 제공합니다. 동적 데이터를 사용하는 Flutter 앱에서 생산성을 높이고 반복적인 코드를 줄이고자 하는 개발자에게 이상적입니다.

사용 사례

  • 로딩 상태를 사용하여 데이터 표시
  • 데이터 가져오기 중 오류 처리
  • 상태 관리 간소화
  • 최소한의 코드로 반응형 UI 만들기
  • 데이터 기반 화면에서 반복 코드 줄이기

주요 기능

  • 내장된 로딩 및 오류 위젯
  • 데이터 표시를 위한 최소 설정
  • 반응형 데이터 바인딩
  • 데이터 로직과 UI의 명확한 분리
  • 비동기 데이터 스트림 지원

적합한 대상

  • 간단함을 찾는 Flutter 초보자
  • 빠른 프로토타이핑에 집중하는 개발자
  • 명확한 데이터 표시가 필요한 프로젝트
  • 일관된 데이터 처리 패턴을 원하는 팀
  • 자주 API 또는 로컬 데이터 상호작용을 하는 앱

고려 사항

  • 기본적인 데이터 표시 요구 사항에 한정됨
  • 복잡한 흐름을 처리하려면 추가적인 상태 관리가 필요할 수 있습니다
  • Provider 또는 Riverpod과 같은 고급 상태 라이브러리의 완전한 대체물은 아님
  • 간단한 데이터 렌더링 시나리오에 가장 적합

원본 README

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

data_widget

data_widget is a Flutter package that provides a simple wrapper for InheritedWidget, InheritedModel, InheritedNotifier, ValueNotifier, and ChangeNotifier.

Features

Data

A widget that holds a single data and allows its descendants to access the data and listen to changes.

Providing the data
Data.inherit(
  data: 'Hello, World!',
  child: const MyWidget(),
)
Getting the data

There are multiple ways to get the data:

Find and listen

This method will find the nearest Data<T> widget (in this case Data<String>). Calling this method will register a listener that will be invoked when the data changes. In other words, the widget will rebuild when the data changes. This will throw an assertion error if the data is not found.

String data = Data.of<String>(context);
Optionally find and listen

This method is similar to Data.of<T>(BuildContext context), but will not throw an assertion error if the data is not found.

String? data = Data.maybeOf<String>(context);
Find

This method will find the nearest Data<T> widget (in this case Data<String>). This will throw an assertion error if the data is not found. This method does not register any listener so the widget will not rebuild when the data changes. This is useful when you only need to read the data once (i.e. in onPressed callback, onTap callback, etc.).

String data = Data.find<String>(context);
Optionally find

This method is similar to Data.find<T>(BuildContext context), but will not throw an assertion error if the data is not found.

String? data = Data.maybeFind<String>(context);
Blocking the data

You can stop the data from being passed down to its descendants by wrapping the widget with Data.boundary

Data.boundary<MyService>(
  child: const MyWidget(),
)
MultiData

A widget that holds multiple data and allows its descendants to access the data and listen to changes without having to nest multiple Data widgets.

Usually, when you need to pass multiple data to its descendants, you will have to nest multiple Data widgets.

Data.inherit(
  data: 'Hello, World!',
  child: Data.inherit(
    data: 42,
    child: Data.boundary<MyService>(
      child: const MyWidget(),
    ),
  ),
)

With MultiData, you can pass multiple data without having to nest multiple Data widgets.

MultiData(
  data: [
    Data<String>('Hello, World!'),
    Data(42), // not providing type is optional, it will be inferred from the data
    Data.boundary<MyService>(), // but a must for boundary
  ],

Getting the data is similar to Data widget.

[!NOTE] Providing type in the type param is optional but encouraged to avoid runtime errors due to type mismatch.

[!WARNING] The order of the data must be the same as the order of the data provided.

Model

A widget that holds a single model and allows its descendants to access or change the value of the model. Similar to Data but uses symbol as the key to identify the model. Mostly useful when getting same type data within the same widget tree.

// Using Data
Data.inherit(
  data: 'Hello, World!',
  child: Data.inherit(
    data: 'Another!',
    child: const MyWidget(), // The widget can only access 'Another!' data 
  ),
)
// Using Model
MultiModel(
  data: [
    Model(#myString, 'Hello, World!'),
    Model(#myString2, 'Another!'),
  ],
  child: const MyWidget(), // The widget can access both 'Hello, World!' and 'Another!' data
)
Providing a read-only model
Model.inherit(
  #myString,
  'Hello World',
  child: const MyWidget(),
)
Providing a model
String myString = 'Hello World';

Model.inherit(
  #myString,
  myString,
  child: const MyWidget(),
  onChanged: (value) {
    myString = value;
  },
)
Getting the model

There are multiple ways to get the model, most of them are similar to Data widget.

// Find and listen
String myString = Model.of<String>(context, #myString);
// Optionally find and listen
String? myString = Model.maybeOf<String>(context, #myString);
// Find
String myString = Model.find<String>(context, #myString);
// Optionally find
String? myString = Model.maybeFind<String>(context, #myString);
Blocking the model

You can stop the model from being passed down to its descendants by wrapping the widget with ModelBoundary

/// Single boundary
ModelBoundary<MyService>(
  #myService,
  child: const MyWidget(), // cannot access #myService
)
/// Multiple boundary
MultiModel(
  data: [
    ModelBoundary<MyService>(#myService),
    ModelBoundary<MyService>(#myService2),
  ],
  child: const MyWidget(), // cannot access #myService and #myService2
)
MultiModel

A widget that holds multiple models and allows its descendants to access or change the value of the model. Similar to MultiData but uses symbol as the key to identify the model. Mostly useful when getting same type data within the same widget tree.

MultiModel(
  data: [
    Model(#myString, 'Hello, World!'),
    Model(#myString2, 'Another!'),
    ModelBoundary<MyService>(#myService),
  ],
  child: const MyWidget(),
)

Getting the model is similar to Model widget.

[!NOTE] Providing type in the type param is optional but encouraged to avoid runtime errors due to type mismatch.

[!WARNING] The order of the data must be the same as the order of the data provided.

MutableNotifier

When using List (or any mutable object) as the value for ValueNotifier, it will not notify the listeners when the list is mutated, because the reference to the list is not changed. MutableNotifier solves this problem by providing a method to mutate the list and notify the listeners.

MutableNotifier<List<int>> list = MutableNotifier([1, 2, 3]);
list.mutate((value) {
  value.add(4);
});

You can also decide whether to notify the listeners or not.

MutableNotifier<List<int>> set = MutableNotifier([1, 2, 3]);
set.mutate((value) {
  if (!value.contains(4)) {
    value.add(4);
    return true; // notify the listeners
  }
  return false; // do not notify the listeners
});
ValueNotifierUnmodifiableView

A wrapper for ValueNotifier that provides an unmodifiable view of the value.

ValueNotifier<String> valueNotifier = ValueNotifier('Hello, World!');
// Sure you can do this so that the value cannot be changed
ValueListenable<String> castedNotifier = valueNotifier;
// But you can still change the value by casting it back to ValueNotifier
(castedNotifier as ValueNotifier<String>).value = 'Another!';
// This can cause unexpected behavior

// Using ValueNotifierUnmodifiableView
ValueListenable<String> valueListenable = ValueNotifierUnmodifiableView(valueNotifier);
// This prevents the value from being changed outside of your control
(valueListenable as ValueNotifier<String>).value = 'Another!';
// as valueListenable is no longer a ValueNotifier, this will throw an error

You can also use the ValueNotifier extension method to convert the ValueNotifier to ValueNotifierUnmodifiableView.

ValueNotifier<String> _valueNotifier = ValueNotifier('Hello, World!');

ValueListenable<String> get valueListenable => _valueNotifier.readOnly(); 
ValueChangeNotifier

Similar to ValueNotifier, but listeners can be notified with the old value and the new value.

ValueChangeNotifier<int> valueChangeNotifier = ValueChangeNotifier(42);
valueChangeNotifier.addChangeListener((newValue, oldValue) {
  print('Old value: $oldValue');
  print('New value: $newValue');
});
valueChangeNotifier.value = 43;
ListNotifier

A list that can notify the listeners when the list is mutated.

ListNotifier<int> listNotifier = ListNotifier([1, 2, 3]);
listNotifier.addChangeListener((details) {
  print('Added: ${details.added}');
  print('Removed: ${details.removed}');
  print('Index: ${details.index}');  
});
listNotifier.add(4);
SetNotifier

A set that can notify the listeners when the set is mutated.

SetNotifier<int> setNotifier = SetNotifier({1, 2, 3});
setNotifier.addChangeListener((details) {
  print('Added: ${details.added}');
  print('Removed: ${details.removed}');
});
setNotifier.add(4);
MapNotifier

A map that can notify the listeners when the map is mutated.

MapNotifier<int, String> mapNotifier = MapNotifier({1: 'One', 2: 'Two', 3: 'Three'});
mapNotifier.addChangeListener((details) {
  print('Added: ${details.added}'); // added entries
  print('Removed: ${details.removed}'); // removed entries
});
mapNotifier[4] = 'Four';
DebounceController

A controller that can be used to debounce the function call.

DebounceController debounceController = DebounceController();

debounceController.debounce(() {
  print('Debounced!'); // This will be cancelled
}, duration: const Duration(seconds: 1));
debounceController.debounce(() {
  print('Debounced 2!'); // This will be executed
}, duration: const Duration(seconds: 1));
// The first function call will be canceled and only the second function call will be executed
// Unless we wait for the debounce to finish, then the next function call will be executed
await Future.delayed(const Duration(seconds: 1));
debounceController.debounce(() {
  print('Debounced 3!'); // This will be executed
}, duration: const Duration(seconds: 1));
Use case

Preventing multiple function calls when the user is typing in the search bar.

TextField(
  onChanged: (value) {
    debounceController.debounce(() {
      // This will be executed after the user stops typing for 500ms,
      // if the user keeps typing, the debounce will be reset
      // so user cannot spam the search request if they type too fast
    }, duration: const Duration(milliseconds: 500));
  },
)

Getting started

1. Install the package

In your terminal:

flutter pub add data_widget

or you can add it manually in your pubspec.yaml:

dependencies:
  data_widget: {latest_version}
2. Import the package
import 'package:data_widget/data_widget.dart';
Using Experimental Version

If you want to use the experimental version, you can add the following to your pubspec.yaml:

dependencies:
  data_widget:
    git:
      url: "https://github.com/sunarya-thito/data_widget.git"

카테고리

소스 저장소

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

아직 데이터가 없습니다.

순위