Skip to content

Instantly share code, notes, and snippets.

@eEQK
Created September 29, 2025 13:48
Show Gist options
  • Select an option

  • Save eEQK/e1806daab6c38e4afa22ad44b3dcdc20 to your computer and use it in GitHub Desktop.

Select an option

Save eEQK/e1806daab6c38e4afa22ad44b3dcdc20 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: Demo()));
class Demo extends StatefulWidget {
@override
_DemoState createState() => _DemoState();
}
class _DemoState extends State<Demo> {
bool enableGestures = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('State Reset Demo')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => setState(() => enableGestures = !enableGestures),
child: Text(enableGestures ? 'Disable' : 'Enable'),
),
SizedBox(height: 20),
Text('❌ BAD (resets state):'),
BadWrapper(enableGestures: enableGestures, child: Counter()),
SizedBox(height: 20),
Text('✅ GOOD (preserves state):'),
GoodWrapper(enableGestures: enableGestures, child: Counter()),
],
),
);
}
}
class BadWrapper extends StatelessWidget {
final bool enableGestures;
final Widget child;
BadWrapper({required this.enableGestures, required this.child});
@override
Widget build(BuildContext context) {
if (!enableGestures) return child;
return GestureDetector(
onTap: () => print('Bad tapped'),
child: Container(
decoration: BoxDecoration(border: Border.all(color: Colors.red)),
child: child,
),
);
}
}
class GoodWrapper extends StatelessWidget {
final bool enableGestures;
final Widget child;
GoodWrapper({required this.enableGestures, required this.child});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: enableGestures ? () => print('Good tapped') : null,
child: Container(
decoration: BoxDecoration(border: Border.all(color: Colors.green)),
child: child,
),
);
}
}
class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count = 0;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(16),
child: Column(
children: [
Text('Count: $count'),
ElevatedButton(
onPressed: () => setState(() => count++),
child: Text('+'),
),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment