Skip to content

Instantly share code, notes, and snippets.

@gazialankus
Forked from rrousselGit/functions_vs_class.dart
Last active September 25, 2021 21:45
Show Gist options
  • Save gazialankus/65f753b633f68503262d5adc22ea27c0 to your computer and use it in GitHub Desktop.
Save gazialankus/65f753b633f68503262d5adc22ea27c0 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
// This example showcases how by using functions instead of StatelessWidgets,
// this can cause bugs when using InheritedWidgets
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(context) {
print('this build method is called only once');
return Counter(
count: Count(),
child: MaterialApp(
home: Home(),
// Uncomment to make your app crash
// And if you fix the error, rebuilding the counter will rebuild MyApp
// home: Scaffold(
// body: Center(
// child: Text('Count ${Counter.of(context).value}'),
// ),
// floatingActionButton: FloatingActionButton(
// onPressed: () => Counter.of(context).value++,
// child: Icon(Icons.add),
// ),
// ),
),
);
}
}
class Count extends ValueNotifier<int> {
Count() : super(0);
}
class Counter extends InheritedNotifier {
Counter({
Key key,
this.count,
Widget child,
}) : super(key: key, child: child, notifier: count);
final Count count;
static Count of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<Counter>().count;
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('Home is re-executed without re-executing MyApp');
return Scaffold(
body: Center(
child: Text('Count ${Counter.of(context).value}'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => Counter.of(context).value++,
child: Icon(Icons.add),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment