Skip to content

Commit

Permalink
fix: rebuild RearchElement when its widget updates (#164)
Browse files Browse the repository at this point in the history
Fixes #163
  • Loading branch information
GregoryConrad authored Apr 29, 2024
1 parent aaf4f26 commit 211e918
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
9 changes: 9 additions & 0 deletions packages/flutter_rearch/lib/src/widgets/consumer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ class _RearchElement extends ComponentElement {
);
}

// NOTE: for some reason, Flutter doesn't rebuild an Element automatically
// when its Widget changes; thus, we need to override this method.
// See https://github.com/GregoryConrad/rearch-dart/issues/163
@override
void update(RearchConsumer newWidget) {
super.update(newWidget);
rebuild(force: true);
}

@override
void deactivate() {
for (final listener in deactivateListeners) {
Expand Down
42 changes: 42 additions & 0 deletions packages/flutter_rearch/test/widgets_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import 'package:flutter/material.dart';
import 'package:flutter_rearch/flutter_rearch.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:rearch/rearch.dart';

void main() {
testWidgets('RearchConsumer rebuilds when constructor params change (#163)',
(tester) async {
await tester.pumpWidget(
const RearchBootstrapper(
child: MaterialApp(home: Scaffold(body: ParentConsumer())),
),
);
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
await tester.tap(find.byType(TextButton));
await tester.pumpAndSettle();
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}

class ParentConsumer extends RearchConsumer {
const ParentConsumer({super.key});
@override
Widget build(BuildContext context, WidgetHandle use) {
final value = use.data(0);
return TextButton(
onPressed: () => value.value++,
child: ChildConsumer(value.value),
);
}
}

class ChildConsumer extends RearchConsumer {
const ChildConsumer(this.i, {super.key});
final int i;
@override
Widget build(BuildContext context, WidgetHandle use) {
return Text('$i');
}
}

0 comments on commit 211e918

Please sign in to comment.