Created
September 7, 2023 09:41
-
-
Save dkbast/16ec67a9fb756f1c6acd95dc0b559722 to your computer and use it in GitHub Desktop.
Lifecycle of a StatefulWidget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MainApp()); | |
} | |
class MainApp extends StatefulWidget { | |
const MainApp({super.key}); | |
@override | |
State<MainApp> createState() => _MainAppState(); | |
} | |
class _MainAppState extends State<MainApp> { | |
bool isDark = false; | |
int counter = 0; | |
List<Key> keys = [GlobalKey(), GlobalKey()]; | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: isDark ? ThemeData.dark() : ThemeData.light(), | |
home: Scaffold( | |
appBar: AppBar( | |
title: const Text('Flutter Dark Mode'), | |
actions: [ | |
Switch( | |
value: isDark, | |
onChanged: (value) { | |
setState(() { | |
isDark = value; | |
}); | |
}, | |
), | |
], | |
), | |
body: Column( | |
children: [ | |
StatefulExample(count: counter, key: keys[0]), | |
StatefulExample(count: counter, key: keys[1]), | |
], | |
), | |
floatingActionButton: Row( | |
children: [ | |
FloatingActionButton( | |
onPressed: () { | |
setState(() { | |
keys.insert(0, keys.removeAt(1)); | |
}); | |
}, | |
child: const Icon(Icons.rotate_left)), | |
FloatingActionButton( | |
onPressed: () { | |
setState(() { | |
counter++; | |
}); | |
}, | |
child: const Icon(Icons.add), | |
), | |
], | |
), | |
), | |
); | |
} | |
} | |
class StatefulExample extends StatefulWidget { | |
const StatefulExample({Key? key, required this.count}) : super(key: key); | |
final int count; | |
@override | |
_StatefulExampleState createState() => _StatefulExampleState(); | |
} | |
class _StatefulExampleState extends State<StatefulExample> { | |
@override | |
Widget build(BuildContext context) { | |
return Center( | |
child: Text('Hello World ${widget.count}!', | |
style: Theme.of(context).textTheme.displayLarge), | |
); | |
} | |
@override | |
void initState() { | |
super.initState(); | |
print('initState'); | |
} | |
@override | |
void didChangeDependencies() { | |
super.didChangeDependencies(); | |
print('didChangeDependencies'); | |
} | |
@override | |
void didUpdateWidget(covariant StatefulExample oldWidget) { | |
super.didUpdateWidget(oldWidget); | |
print('didUpdateWidget'); | |
} | |
@override | |
void deactivate() { | |
super.deactivate(); | |
print('deactivate'); | |
} | |
@override | |
void dispose() { | |
print('dispose'); | |
super.dispose(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment