0
0
FlutterComparisonBeginner · 4 min read

Shared Preferences vs Hive Flutter: Key Differences and Usage

In Flutter, SharedPreferences is best for storing simple key-value pairs like user settings, while Hive is a lightweight NoSQL database suited for complex data and faster performance. SharedPreferences is easier for small data, but Hive offers more features and better speed for larger or structured data.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of SharedPreferences and Hive in Flutter.

FactorSharedPreferencesHive
TypeKey-value storageLightweight NoSQL database
Data ComplexitySimple data types onlySupports complex objects
PerformanceSlower for large dataFaster and efficient
SetupVery easy, minimal setupRequires initialization and adapters
Data PersistenceStored as XML/JSON internallyStored in binary format
Use CaseUser preferences, small configsOffline data, caching, complex data
⚖️

Key Differences

SharedPreferences is designed for storing small amounts of simple data like strings, numbers, and booleans. It uses platform-specific persistent storage and is very easy to use without extra setup. However, it does not support storing complex objects or large data efficiently.

Hive is a fast, lightweight NoSQL database written in pure Dart. It supports storing complex Dart objects by using type adapters and stores data in a binary format for better performance. Hive requires initialization and registering adapters but offers more flexibility and speed, especially for offline apps needing structured data storage.

In summary, SharedPreferences is great for quick, simple key-value storage, while Hive is better for apps that need to store and query complex data locally with high performance.

⚖️

Code Comparison

Example: Saving and reading a username string using SharedPreferences.

dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefsExample extends StatefulWidget {
  @override
  _SharedPrefsExampleState createState() => _SharedPrefsExampleState();
}

class _SharedPrefsExampleState extends State<SharedPrefsExample> {
  String _username = '';

  Future<void> _saveUsername() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('username', 'flutterUser');
  }

  Future<void> _loadUsername() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _username = prefs.getString('username') ?? 'No username saved';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('SharedPreferences Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Username: $_username'),
            ElevatedButton(onPressed: _saveUsername, child: Text('Save Username')),
            ElevatedButton(onPressed: _loadUsername, child: Text('Load Username')),
          ],
        ),
      ),
    );
  }
}
Output
UI with two buttons: 'Save Username' and 'Load Username'. Pressing 'Save Username' stores 'flutterUser'. Pressing 'Load Username' shows 'Username: flutterUser'.
↔️

Hive Equivalent

Example: Saving and reading a username string using Hive.

dart
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();
  await Hive.openBox('userBox');
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HiveExample());
  }
}

class HiveExample extends StatefulWidget {
  @override
  _HiveExampleState createState() => _HiveExampleState();
}

class _HiveExampleState extends State<HiveExample> {
  final box = Hive.box('userBox');
  String _username = '';

  void _saveUsername() {
    box.put('username', 'flutterUser');
  }

  void _loadUsername() {
    setState(() {
      _username = box.get('username', defaultValue: 'No username saved');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Hive Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Username: $_username'),
            ElevatedButton(onPressed: _saveUsername, child: Text('Save Username')),
            ElevatedButton(onPressed: _loadUsername, child: Text('Load Username')),
          ],
        ),
      ),
    );
  }
}
Output
UI with two buttons: 'Save Username' and 'Load Username'. Pressing 'Save Username' stores 'flutterUser'. Pressing 'Load Username' shows 'Username: flutterUser'.
🎯

When to Use Which

Choose SharedPreferences when you need to store simple, small pieces of data like user settings, flags, or tokens with minimal setup. It is perfect for quick key-value storage without complex data structures.

Choose Hive when your app requires storing complex or large amounts of data locally, needs faster read/write performance, or offline capabilities with structured data. Hive is better for caching, offline databases, and apps that need to store custom objects.

Key Takeaways

SharedPreferences is ideal for simple key-value storage with minimal setup.
Hive supports complex data and offers faster performance with binary storage.
Use SharedPreferences for small user settings and Hive for offline or structured data.
Hive requires initialization and adapters, while SharedPreferences is ready to use.
Choose based on your app's data complexity and performance needs.