惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
Visual Studio Blog
IT之家
IT之家
博客园 - 聂微东
The Cloudflare Blog
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
H
Help Net Security
博客园 - 叶小钗
V
V2EX
WordPress大学
WordPress大学
J
Java Code Geeks
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园_首页
C
Check Point Blog
B
Blog
D
DataBreaches.Net
美团技术团队
罗磊的独立博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Flutter Local Storage Guide — SharedPreferences vs Hive v...
kanta13jp1 · 2026-04-29 · via DEV Community

kanta13jp1

Flutter Local Storage Guide — SharedPreferences vs Hive vs SQLite

Choosing the right local storage solution in Flutter directly impacts performance and code simplicity. Here's a practical breakdown of the three main options.

SharedPreferences — Key-Value Settings

Best for small primitives: user settings, theme, login state.

dependencies:
  shared_preferences: ^2.3.0

Enter fullscreen mode Exit fullscreen mode

class SettingsService {
  static const _themeKey = 'theme_mode';

  Future<void> saveTheme(String theme) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_themeKey, theme);
  }

  Future<String> getTheme() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_themeKey) ?? 'system';
  }
}

Enter fullscreen mode Exit fullscreen mode

Hive — Fast NoSQL Storage

Perfect for structured data, offline caching, and large datasets. TypeAdapters keep it type-safe.

dependencies:
  hive: ^2.2.3
  hive_flutter: ^1.1.0
dev_dependencies:
  hive_generator: ^2.0.1
  build_runner: ^2.4.0

Enter fullscreen mode Exit fullscreen mode

@HiveType(typeId: 0)
class Task extends HiveObject {
  @HiveField(0) late String id;
  @HiveField(1) late String title;
  @HiveField(2) late bool isDone;
  @HiveField(3) late DateTime createdAt;
}

Enter fullscreen mode Exit fullscreen mode

// Generate adapter: dart run build_runner build

await Hive.initFlutter();
Hive.registerAdapter(TaskAdapter());
final box = await Hive.openBox<Task>('tasks');

// CRUD
await box.put(task.id, task);
final all = box.values.toList();
await box.delete(task.id);

Enter fullscreen mode Exit fullscreen mode

Reactive UI with ValueListenableBuilder

ValueListenableBuilder<Box<Task>>(
  valueListenable: Hive.box<Task>('tasks').listenable(),
  builder: (context, box, _) {
    final tasks = box.values.toList();
    return ListView.builder(
      itemCount: tasks.length,
      itemBuilder: (_, i) => TaskTile(task: tasks[i]),
    );
  },
)

Enter fullscreen mode Exit fullscreen mode

SQLite (sqflite) — Relational Data

Use when you need complex queries, JOINs, or aggregations.

class DatabaseHelper {
  static Database? _db;

  static Future<Database> get database async {
    _db ??= await _initDb();
    return _db!;
  }

  static Future<Database> _initDb() async {
    final path = join(await getDatabasesPath(), 'app.db');
    return openDatabase(
      path,
      version: 1,
      onCreate: (db, _) async {
        await db.execute('''
          CREATE TABLE tasks (
            id TEXT PRIMARY KEY,
            title TEXT NOT NULL,
            is_done INTEGER DEFAULT 0,
            created_at TEXT NOT NULL
          )
        ''');
      },
    );
  }

  static Future<void> insert(Map<String, dynamic> task) async {
    final db = await database;
    await db.insert('tasks', task, conflictAlgorithm: ConflictAlgorithm.replace);
  }

  static Future<List<Map<String, dynamic>>> getAll() async {
    final db = await database;
    return db.query('tasks', orderBy: 'created_at DESC');
  }
}

Enter fullscreen mode Exit fullscreen mode

Decision Matrix

Use case Best choice
App settings / flags SharedPreferences
Offline cache / large datasets Hive
Complex relations / filtering sqflite
Encryption required Hive AES / sqlcipher

How I Use This in My App

In my life management app (自分株式会社), I use Hive for offline journal storage and manage Supabase sync timing with Riverpod. Local-first design means the app is fully functional even on airplane mode.


Building something offline-capable in Flutter? Drop a comment — curious what storage stack you're using.