Skip to content

Instantly share code, notes, and snippets.

@jiahaog
Created April 25, 2024 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiahaog/80f8b7757d6f6658e47cb3b324bbc61a to your computer and use it in GitHub Desktop.
Save jiahaog/80f8b7757d6f6658e47cb3b324bbc61a to your computer and use it in GitHub Desktop.
Keeping state when widget is repositioned
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _isBaz = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Foo(child: Counter(), isBaz: _isBaz),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _isBaz = !_isBaz),
tooltip: 'Toggle isBaz',
child: const Icon(Icons.ac_unit),
),
);
}
}
class Counter extends StatefulWidget {
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _counter = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
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,
),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _counter += 1),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class Foo extends StatefulWidget {
final Widget child;
final bool isBaz;
const Foo({required this.child, required this.isBaz});
@override
State<Foo> createState() => FooState();
}
class FooState extends State<Foo> {
final _key = GlobalKey();
@override
Widget build(BuildContext context) {
// Removing the `_key` or the `KeyedSubtree` causes `child` to be
// disposed and recreated when `isBaz` changes.
if (widget.isBaz) {
return KeyedSubtree(key: _key, child: widget.child);
}
return Container(child: KeyedSubtree(key: _key, child: widget.child));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment