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

패키지 상세v1.0.0

cozy_data

Flutter용 스위프트를 영감으로 한 지속 가능한 데이터 관리 솔루션입니다. 간단하고 강력하며 타입 안전하게 앱 모델을 지속적으로 저장하고 자동 UI 업데이트를 제공합니다.

AndroidiOSmacOS
30일 다운로드
50
좋아요
16
Pub 점수
130

패키지 설치

flutter pub add cozy_data

패키지 개요

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

Cozy Data는 Swift의 데이터 관리 방식에서 영감을 받은 Flutter 패키지로, SQL을 사용하여 앱 모델을 타입 안전하고 직관적으로 지속적으로 저장할 수 있는 방법을 제공합니다. 데이터가 변경될 때 자동으로 UI 업데이트를 트리거하고 데이터베이스 작업을 자동으로 처리하여 반복 코드를 줄이고 개발 속도를 향상시킵니다. 간단함과 신뢰성에 중점을 두어 Flutter의 반응형 프레임워크와 원활하게 통합되며, 실시간 UI 동기화가 필요한 지속적 저장 기능을 필요로 하는 앱에 적합합니다.

사용 사례

  • 오프라인 우선 모바일 애플리케이션
  • 실시간 데이터 동기화
  • 형 안전한 모델 지속성
  • 동적 폼 및 목록 상태 관리
  • 앱 설정 및 사용자 선호 사항 저장

주요 기능

  • 데이터 변경 시 자동 UI 업데이트
  • 타입 안전한 데이터 모델링
  • 스위프트를 영감으로 한 구문과 디자인
  • 내장된 CRUD 작업
  • Flutter 위젯과의 원활한 통합

적합한 대상

  • 간단한 지속성을 찾는 플러터 개발자
  • 오프라인 기능이 필요한 앱
  • 코드 안전성과 유지보수를 우선시하는 팀
  • 자주 데이터 모델이 변경되는 프로젝트
  • Swift 또는 유사한 선언적 패턴에 익숙한 개발자

고려 사항

  • SQL 기반 저장에 제한됨
  • 기본적인 데이터베이스 개념을 이해하고 있어야 합니다
  • 매우 간단한 사용 사례에 대해 오버헤드를 유발할 수 있습니다
  • 비구조적이거나 대규모 NoSQL 요구 사항에 적합하지 않습니다

원본 README

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

Cozy Data

Quickstart • Documentation • Sample Apps • Pub.dev

CozyData:
  1. SwiftData for flutter.
  2. Support sqflite, sqlite3, inMemory data Storage

A Swift-inspired persistent data management solution for Flutter. CozyData provides a simple, powerful, and type-safe way to persist your app's models and automatically update your UI when data changes.

Features

  • 🔄 Automatic UI updates when data changes
  • 🏃‍♂️ Fast and efficient database operations
  • 📱 Built specifically for Flutter
  • 💾 Simple persistent storage
  • 🔍 Powerful querying capabilities
  • 🎯 Type-safe data operations
  • 🧩 Easy-to-use annotations
  • 📦 Zero configuration needed

Quickstart

Add cozy_data to your pubspec.yaml:

1. Add to pubspec.yaml
dependencies:
  cozy_data: latest
  dart_mappable: latest

dev_dependencies:
  build_runner: any
  dart_mappable_builder: any

Usage

1. Define Your Models
import 'package:dart_mappable/dart_mappable.dart';
part 'recipe.mapper.dart';

@MappableClass()
class Recipe with RecipeMappable {
  final String persistentModelID; // This field is required for the cozy_data package to work
  String name;
  List<Ingredients>? ingredients;

  Recipe({required this.id, required this.name, this.ingredients});
}

@MappableClass()
class Ingredients with IngredientsMappable {
  String name;
  int? quantity;
  CookStyle cookStyle;
  Ingredients({required this.name, this.quantity, required this.cookStyle});
}

@MappableEnum()
enum CookStyle { bake, fry, boil }

and make sure to run dart run build_runner build after creating your model.

For more about the annotation please check dart_mappable.

2. Initialize CozyData

Initialize CozyData in your main.dart:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await CozyData.initialize(
      engine: CozyEngine.sqlite3,
      mappers: [RecipeMapper.ensureInitialized()]);

  runApp(MyApp());
}
 

the RecipeMapper will be generate in .mapper.dart file

Basic Operations

Save Data
final newRecipe = Recipe(
  persistentModelID: CozyId.cozyPersistentModelIDString(),
  name: 'salad',
  ingredients: [
    Ingredients(name: 'Tomato',quantity: 2,cookStyle: CookStyle.fry),
    Ingredients(name: 'Onion',quantity: 1,cookStyle: CookStyle.fry),
    Ingredients(name: 'Salt',quantity: 1,cookStyle: CookStyle.boil),
  ]
);

await CozyData.save<Recipe>(newRecipe);

Note: DataModel must be Specify <Recipe>

Delete Data

await CozyData.delete<Recipe>(model);

Update Data

await CozyData.update<Recipe>(updateRecipe);

Simple Query Data with UI Updates
class RecipeListView extends StatefulWidget {
  @override
  _RecipeListViewState createState() => _RecipeListViewState();
}

class _RecipeistViewState extends State<RecipeListView> {

final CozyQueryListener<Recipe> _recipeQuery = CozyData.queryListener<Recipe>();

  @override
  Widget build(BuildContext context) {
    return ListenableBuilder(
      listenable: _recipeQuery,
      builder: (context, _) {
        final recipes = _recipeQuery.items;
        return ListView.builder(
          itemCount: recipes.length,
          itemBuilder: (context, index) => ListTile(
            title: Text(recipes[index].name),
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    _recipeQuery.dispose();
    super.dispose();
  }
}

Fetch Data Once

final recipes = await CozyData.fetch<Recipe>();

Find by ID
final recipe = await CozyData.fetcById<Recipe>(persistentModelID: id);

Advanced Usage

The CozyQueryBuilder is a class used to construct complex SQL-like queries in a structured and programmatic way. It allows you to specify various components of a query, such as fields to group by, order by, having clauses, joins, limits, offsets, selected fields, subqueries, table aliases, and where conditions.


final customBuilder = CozyQueryBuilder(
// groupByFields: A list of fields by which the results should be grouped. In this case, it's an empty list, meaning no grouping is applied.
groupByFields: [],
// orderByFields: A list of fields by which the results should be ordered. It's also an empty list here, so no specific ordering is applied.
orderByFields: [],
// Conditions that filter the groups created by the groupBy clause. It's empty, indicating no such conditions.
havingClauses: [],
// joins: A list of join operations to combine rows from two or more tables based on a related column. No joins are specified here
joins: [],
// limit: The maximum number of records to return. Here, it's set to 10.
limit: 10,
// offset: The number of records to skip before starting to return records. It's set to 0, meaning no records are skipped.
offset: 0,
// selectFields: A list of fields to be selected in the query. It's empty, meaning all fields are selected
selectFields: [],
// subqueries: A list of subqueries to be included in the main query. It's empty, indicating no subqueries.
subqueries: [],
// tableAliases: A map of table aliases to be used in the query. It's an empty map here.
tableAliases: {},
// whereGroups: A list of conditions to filter the results. It's empty, meaning no filtering conditions are applied.
whereGroups: [],
);

Sorting and Filtering once

final recipes = await CozyData.fetch<Recipe>(customBuilder: customBuilder);

The CozyQueryController manages query operations for a CozyQueryListener. It allows adding where conditions, joins, order by fields, and custom queries to the listener.

Example usage:

  final controller = CozyQueryController<MyModel>();
  await controller.addWhere([PredicateGroup(predicates: [Predicate.equals('field', 'value')])]);
  await controller.addJoin([Join(table: 'other_table', condition: 'other_table.id = my_table.other_id')]);
  await controller.orderBy([OrderBy(field: 'created_at', direction: OrderDirection.desc)]);
  await controller.addCustomQuery(CozyQueryBuilder<MyModel>());
  await controller.reset();
Sorting and Filtering
// Controller
final CozyQueryController<Recipe> _queryController = CozyQueryController<Recipe>();

final CozyQueryListener<Recipe> _recipeQuery =
      CozyData.queryListener<Recipe>(controller: _queryController);

  await controller.addWhere([PredicateGroup(predicates: [Predicate.contains('field', 'value')])]);


Best Practices

  • Initialize Early: Call CozyData.initialize() as early as possible in your app lifecycle.

  • Dispose Queries: Always dispose of queries when they're no longer needed to prevent memory leaks.

Full Documentation

See the full documentation here or jump directly to the topic you are looking for:

카테고리

의존성

의존성 목록 8 개

소스 저장소

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

아직 데이터가 없습니다.