Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Last active December 18, 2024 19:31
Show Gist options
  • Save rodydavis/4fa7f3d6d03317c06cd4474a22194375 to your computer and use it in GitHub Desktop.
Save rodydavis/4fa7f3d6d03317c06cd4474a22194375 to your computer and use it in GitHub Desktop.
Signals with functional widget
// ignore_for_file: non_constant_identifier_names
import 'package:flutter/material.dart';
import 'package:signals/signals_flutter.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: Counter((
counter: signal(0),
title: 'Counter Example',
)),
));
}
// inspired by: https://github.com/flutter/flutter/issues/19269#issuecomment-563132307
Widget Function(T props, {Key? key}) signalsWidget<T>(
Widget create(BuildContext c, T props),
) {
final id = UniqueKey();
return (props, {Key? key}) {
Widget child = Watch.builder(
key: id,
builder: (context) {
return create(context, props);
},
);
if (key != null) {
child = KeyedSubtree(
key: key,
child: child,
);
}
return child;
};
}
final Counter = signalsWidget<({Signal<int> counter, String title})>((
context,
props,
) {
final counter = props.counter;
return Scaffold(
appBar: AppBar(
title: Text(props.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('You have pushed the button this many times:'),
Text(
'$counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => counter.value++,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment