Skip to content

Instantly share code, notes, and snippets.

@amani27
Created February 4, 2023 13:06
Show Gist options
  • Select an option

  • Save amani27/73685937834406c4b722f3e387d08740 to your computer and use it in GitHub Desktop.

Select an option

Save amani27/73685937834406c4b722f3e387d08740 to your computer and use it in GitHub Desktop.
Prop drilling demo
import 'package:flutter/material.dart';
class ParentWidget extends StatefulWidget {
const ParentWidget({super.key});
@override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ChildWidgetA(counter: _counter),
ChildWidgetB(counter: _counter),
ChildWidgetC(counter: _counter),
ElevatedButton(
onPressed: _incrementCounter,
child: const Text('Increment'),
),
],
),
),
);
}
}
class ChildWidgetA extends StatelessWidget {
final int counter;
const ChildWidgetA({Key? key, required this.counter}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text('Counter: $counter');
}
}
class ChildWidgetB extends StatelessWidget {
final int counter;
const ChildWidgetB({Key? key, required this.counter}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text('Counter: $counter');
}
}
class ChildWidgetC extends StatelessWidget {
final int counter;
const ChildWidgetC({Key? key, required this.counter}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text('Counter: $counter');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment