import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; /// Builds [builder] once and hands Flutter the same child until [memo] /// changes, so a list that rebuilds on every notification skips the rows /// whose own data did not change. /// /// [memo] must capture everything the built subtree shows or calls: the /// row's data and every callback or controller its closures use (compare /// callbacks by `==`, so a tear-off of the same method still matches). The /// subtree's own inherited dependencies (theme, host, media) still rebuild /// it directly, as they mark its elements rather than this one. class MemoSubtree extends StatefulWidget { const MemoSubtree({super.key, required this.memo, required this.builder}); final Object? memo; final WidgetBuilder builder; @override State createState() => _MemoSubtreeState(); } class _MemoSubtreeState extends State { Widget? _child; @override void didUpdateWidget(MemoSubtree oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.memo != widget.memo) _child = null; } @override void didChangeDependencies() { super.didChangeDependencies(); // A builder that read an inherited widget through this context. _child = null; } @override void reassemble() { super.reassemble(); _child = null; } @override Widget build(BuildContext context) => _child ??= widget.builder(context); } /// A JSON row map as a [MemoSubtree] memo: equal when it is the same map or /// has the same entries (nested values compare by `==`, so a rebuilt nested /// map counts as a change). @immutable class MemoMap { const MemoMap(this.map); final Map? map; @override bool operator ==(Object other) => other is MemoMap && (identical(map, other.map) || mapEquals(map, other.map)); @override int get hashCode => map?.length ?? 0; }