Skip to main content

image_blur 3.0.0 copy "image_blur: ^3.0.0" to clipboard
image_blur: ^3.0.0 copied to clipboard

Encode, decode, and display BlurHash image placeholders in Flutter. Use a supplied hash or generate one from a network image, asset, file, or bytes.

image_blur #

pub.dev License: MIT

Encode, decode, and display BlurHash image placeholders in Flutter. A BlurHash is a short string that captures the broad shapes and colours of a photo. It gives the user a preview while Flutter loads the full image. A hash cannot reconstruct the original photo.

راهنمای فارسی · Migration from 2.x · Example app

Installation #

Requires Flutter 3.50.0+ and Dart 3.14.0+ (below 4.0). This guide describes 3.0.0. Use the pub.dev constraint once that version is available there:

dependencies:
  image_blur: ^3.0.0

To try this checkout locally, use a path relative to your app’s pubspec.yaml:

dependencies:
  image_blur:
    path: ../image_blur

Run flutter pub get, then import package:image_blur/image_blur.dart.

Show an image with its BlurHash #

Pass a hash from your API, database, or asset metadata. Flutter still loads the original URL; the package makes no separate image request to generate the placeholder.

import 'package:flutter/widgets.dart';
import 'package:image_blur/image_blur.dart';

Widget photoTile(String url, String? hash) => BlurImage.network(
  url,
  blurHash: hash,
  width: 320,
  height: 180,
  radius: const Radius.circular(12),
  semanticLabel: 'Landscape photo',
);

When blurHash is null, the widget tries to compute it automatically. Supply a smaller thumbnail when the original is large:

BlurImage.network(
  fullSizeUrl,
  thumbnail: ImageSource.network(thumbnailUrl),
  width: 320,
  height: 180,
  cacheWidth: 640,
  errorBuilder: (context, error) => const Center(
    child: Text('Could not load the photo'),
  ),
)

Without a supplied or cached hash, automatic generation can make a separate request for the hash source, while the full image is loaded by Flutter. A backend supplied hash is usually the simplest choice for a large feed. Use an explicit width and height, an AspectRatio, or a grid cell to keep the layout stable before the image loads. BlurHash strings do not contain the photo’s dimensions.

Image sources #

Source Widget constructor Hash source
HTTP(S) URL BlurImage.network(url) ImageSource.network(url, headers: headers)
Bundled asset BlurImage.asset(assetName) ImageSource.asset(assetName, package: package)
Encoded image bytes BlurImage.bytes(bytes) ImageSource.bytes(bytes, cacheKey: key)
Local file path BlurImage.file(path) ImageSource.file(path)
Flutter ImageProvider BlurImage(source: source) ImageSource.provider(provider, cacheKey: key, hashSource: source)

Declare app assets under flutter.assets in your app’s pubspec.yaml. The bytes constructors accept encoded images such as PNG or JPEG. A custom provider needs a supplied blurHash, a separate thumbnail, or a hashSource to generate its placeholder. Local files work on native platforms; on the web, pass bytes from the file picker.

Loading, fallbacks, and callbacks #

Situation What the user sees
Hash unavailable or invalid placeholderColor; an invalid supplied hash does not trigger automatic generation.
Hash ready and original still loading A decoded BlurHash.
Original ready The original replaces the placeholder. The fade is skipped for synchronously loaded images and when reduced motion is enabled.
Original fails Your errorBuilder, or the BlurHash / solid fallback if no builder is set.

Set fadeInDuration: Duration.zero for an immediate swap. onHashResolved reports a valid supplied or computed hash, and onLoaded reports the first available image frame. Both callbacks run after a frame.

Render a hash by itself #

Use BlurHashImage when you have the hash but do not need to load the photo. Its decodeWidth and decodeHeight describe the small raster; width and height describe the widget in logical pixels.

const BlurHashImage(
  hash: r'LEHV6NV#FR}j~Q}FWBjZ00%1IUD$%1WVoJae',
  width: 240,
  height: 160,
  decodeWidth: 36,
  decodeHeight: 24,
  punch: 1.0,
  radius: Radius.circular(12),
)

Use a finite punch of 0 for the hash’s average colour, 1 for default contrast, or a value above 1 to emphasise detail. A typical raster is 16–64 pixels per side; Flutter scales it to fit the widget. Invalid hashes or raster failures leave the solid fallback in place.

Generate, validate, and decode hashes #

Future<String?> computePhotoHash(String url) => ImageBlur.blurHash(
  ImageSource.network(url),
  numCompX: 4,
  numCompY: 3,
  onFailure: (failure) => debugPrint('${failure.reason.name}: ${failure.message}'),
);

ImageBlur.blurHash returns null for source or worker failures. Check failure.reason for sourceUnavailable, undecodable, tooLarge, timedOut, or unknown. An invalid component count is a programming error and throws. Counts range from 1 to 9 per axis. A 4 × 3 hash is 28 characters (4 + 2 × x × y). Larger counts retain more detail and cost more to encode and decode.

Use the lower level API when you already have a small raw buffer:

final encoded = BlurHash.fromRgba(
  rgba: thumbnailRgba, // Row-major RGBA8888 pixels, four bytes per pixel.
  width: 32,
  height: 24,
);
final storedHash = encoded.hash;

final parsed = BlurHash.tryParse(storedHash);
if (parsed != null) {
  final pixels = await ImageBlur.rasterize(parsed, width: 32, height: 24);
  // pixels is a read-only RGBA8888 buffer.
}

BlurHash.parse throws BlurHashFormatException on invalid input. BlurHash.toRgba is the synchronous alternative to ImageBlur.rasterize. BlurHash only stores RGB; reconstructed pixels are opaque. If the transparent parts of an image should match a specific background, composite the image onto that background before encoding.

Caching and configuration #

The package caches hash strings by source identity, component counts, and encoder thumbnail size. It caches rasters separately by hash, dimensions, and punch. Calls for the same work can share a pending job. The original image is cached separately by Flutter’s ImageCache or by your custom provider.

ImageBlur.configure((s) => s.copyWith(
  numCompX: 4,
  numCompY: 3,
  thumbnailMaxDimension: 32,
  maxConcurrentLoads: 4,
));
ImageBlurSettings Default Controls
numCompX, numCompY 4, 3 Encoder detail in each axis, 1–9.
thumbnailMaxDimension 32 px Longest side of encoder input, 4–256 px.
decodeWidth, decodeHeight 32 × 32 px Default hash raster size, 1–256 px per side.
punch 1.0 Finite, nonnegative contrast multiplier.
hashCacheSize, pixelCacheSize 512, 64 Maximum memory entries. Set either to 0 to disable that cache. Rasters also have a 4 MiB budget.
maxSourceBytes, maxSourcePixels 12 MiB, 64 million Limits for automatic hash generation; they do not cap the original displayed by Flutter.
maxConcurrentLoads 6 Simultaneous source fetch, decode, and encode jobs.
workerCount 1 Number of native workers to start on demand or at warm-up, from 1 to 8.
fetchTimeout, computeTimeout 20 s, 10 s Time allowed for a source read or store lookup, and for native worker execution (including its queue), respectively.
store null Optional persistent hash cache.
Operation Use it to…
ImageBlur.preloadHashes(sources) Prefetch several hashes. Missing results are null, keyed by ImageSource.cacheKey.
ImageBlur.putHash(source, hash) Seed the in-memory cache with a valid hash.
ImageBlur.blurHash(source, forceRefresh: true) Skip the memory and persistent hash entries and recompute.
BlurImage.precache(context, source, blurHash: hash) Preload the original via Flutter. Omit the hash to warm its cache too.
ImageBlur.evict(source) / ImageBlur.clearCache() Clear in-memory hash variants for a source / clear both in-memory caches. Neither deletes Flutter’s original image cache or the persistent store.
ImageBlur.stats Read current occupancy, hash hits, misses, failures, pending hash jobs, and cache evictions.
ImageBlur.warmUp() / ImageBlur.shutdown() Start native workers proactively / release them and clear memory and counters.
ImageBlur.reset() Restore default settings and clear memory.

Use a versioned URL when an image changes. If the same URL is used for different images, pass a distinct cacheKey for the hash (for example, a photo ID and revision). That key does not change Flutter’s original image cache key. Use a versioned URL, configure your image provider, or evict its cache entry if the original at a URL changes. Use a stable custom key for bytes when you want reuse across launches.

Persistent hash storage #

Implement BlurHashStore in your app with a preferences or database adapter. For example, after adding shared_preferences to your app:

import 'package:image_blur/image_blur.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PreferencesBlurHashStore implements BlurHashStore {
  final SharedPreferencesAsync _preferences = SharedPreferencesAsync();
  static const _prefix = 'blurhash/';

  @override
  Future<String?> load(String key) => _preferences.getString('$_prefix$key');

  @override
  Future<void> save(String key, String hash) =>
      _preferences.setString('$_prefix$key', hash);

  @override
  Future<void> remove(String key) => _preferences.remove('$_prefix$key');

  @override
  Future<void> clear() async {
    final keys = await _preferences.getKeys();
    await _preferences.clear(
      allowList: keys.where((key) => key.startsWith(_prefix)).toSet(),
    );
  }
}

Set it with ImageBlur.configure((s) => s.copyWith(store: PreferencesBlurHashStore())) before building image widgets. Treat keys as opaque and manage expiry or size in the adapter. Store errors fall back to the image source; saving happens in the background. Use copyWith(clearStore: true) to detach the store.

Platforms and troubleshooting #

  • Android, iOS, macOS, Windows, Linux: Flutter supplies thumbnail pixels; BlurHash encoding and rasterisation run on native worker isolates.
  • Web: hash computation runs on the browser’s main isolate. Keep thumbnail sizes small and prefer supplied hashes. Automatic generation uses PNG, JPEG, GIF, BMP, or WebP headers to check dimensions before decoding. For other formats, supply a hash or a thumbnail in one of those formats. The image host must allow the required browser requests via CORS.
  • Network images fail only on release builds: check android.permission.INTERNET on Android or com.apple.security.network.client for sandboxed macOS apps.
  • No blur appears: a cached image may finish first. For a preview that always displays the hash, use BlurHashImage. Give the widget a bounded size if nothing appears at all.
  • Wrong or stale blur: use a hash generated from the same photo or crop, and update the URL or hash cache key when content changes. A BlurHash has no aspect ratio; use display constraints that match your intended crop.
  • Hash generation fails: inspect onFailure, check image permissions and format, and use a smaller source when a byte or pixel guard is reached. The first decoded frame is used for animated inputs.

Run the example #

cd example
flutter pub get
flutter run

The example shows a scrollable list of 22 photos with supplied and automatically generated BlurHashes. See the example guide for what to try. The package uses Flutter and http at runtime. The source is available under the MIT license.

23
likes
160
points
247
downloads

Documentation

API reference

Publisher

verified publisherswanflutterdev.com

Weekly Downloads

Encode, decode, and display BlurHash image placeholders in Flutter. Use a supplied hash or generate one from a network image, asset, file, or bytes.

Repository (GitHub)
View/report issues

Topics

#image #blurhash #placeholder

License

MIT (license)

Dependencies

flutter, http

More

Packages that depend on image_blur