Cached Widget

Avoid unnecessary rebuilding of Flutter Widgets. Only rebuild when the Widget's data changes.


Platform Pub Package License: MIT


Installing

1. Depend on it

Add this to your package's pubspec.yaml file:

dependencies:
  cached_widget: ^1.0.0

2. Install it

You can install packages from the command line:

with pub:

$ pub get

with Flutter:

$ flutter pub get

3. Import it

Now in your Dart code, you can use:

import 'package:cached_widget/cached_widget.dart';

Usage

Primitive

class PrimitiveExample extends StatelessWidget {
  const PrimitiveExample({super.key});

  @override
  Widget build(BuildContext context) {
    return CachedWidget(
      value: "String",
      builder: (context, value) {
        return const SizedBox.shrink();
      },
    );
  }
}

Collection

class ListExample extends StatelessWidget {
  const ListExample({super.key});

  @override
  Widget build(BuildContext context) {
    return CachedWidget(
      value: const ['1', '2', '3'],
      builder: (context, value) {
        return const SizedBox.shrink();
      },
    );
  }
}

Object

Object class must be extended from Equatable or use Freeze to implement the equals and hashCode functions for diffing.

import 'package:equatable/equatable.dart';

class ObjectDemo extends Equatable {
  final String id;
  final List<String> skins;

  const ObjectDemo({
    required this.id,
    required this.skins,
  });

  @override
  List<Object?> get props => [id, skins];
}

class ObjectExample extends StatelessWidget {
  const ObjectExample({super.key});

  @override
  Widget build(BuildContext context) {
    return CachedWidget(
      value: const ObjectDemo(id: '1', skins: ['1', '2', '3']),
      builder: (context, value) {
        return const SizedBox.shrink();
      },
    );
  }
}

Libraries

cached_widget