Created
March 23, 2023 15:53
-
-
Save hawkkiller/7c3e4cfb83dc5abb8559d9b8f78dabf3 to your computer and use it in GitHub Desktop.
Dart global key showcase
This file contains hidden or 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 'dart:math'; | |
| import 'package:flutter/material.dart'; | |
| void main() { | |
| runApp(const MainApp()); | |
| } | |
| class MainApp extends StatelessWidget { | |
| const MainApp({super.key}); | |
| @override | |
| Widget build(BuildContext context) { | |
| return const MaterialApp( | |
| home: Scaffold( | |
| body: Center(child: Body()), | |
| ), | |
| ); | |
| } | |
| } | |
| class Body extends StatefulWidget { | |
| const Body({super.key}); | |
| @override | |
| State<Body> createState() => _BodyState(); | |
| } | |
| class _BodyState extends State<Body> { | |
| bool swapped = false; | |
| @override | |
| Widget build(BuildContext context) { | |
| return Column( | |
| children: [ | |
| const Text('Miha'), | |
| IconButton( | |
| onPressed: () { | |
| setState(() { | |
| swapped = !swapped; | |
| }); | |
| }, | |
| icon: const Icon(Icons.swap_horiz), | |
| ), | |
| if (swapped) | |
| const WidgetWithGlobalKey( | |
| key: GlobalObjectKey('key'), | |
| ) | |
| else | |
| const WidgetWithGlobalKey( | |
| key: GlobalObjectKey('key'), | |
| ), | |
| ], | |
| ); | |
| } | |
| } | |
| class WidgetWithGlobalKey extends StatefulWidget { | |
| const WidgetWithGlobalKey({super.key}); | |
| @override | |
| State<WidgetWithGlobalKey> createState() => _WidgetWithGlobalKeyState(); | |
| } | |
| class _WidgetWithGlobalKeyState extends State<WidgetWithGlobalKey> { | |
| @override | |
| void activate() { | |
| print('$a activated'); | |
| super.activate(); | |
| } | |
| @override | |
| void deactivate() { | |
| print('$a deactivated'); | |
| super.deactivate(); | |
| } | |
| @override | |
| void dispose() { | |
| print('$a disposed'); | |
| super.dispose(); | |
| } | |
| int a = Random().nextInt(100); | |
| @override | |
| Widget build(BuildContext context) { | |
| a++; | |
| return Column( | |
| children: [ | |
| Text('a = $a'), | |
| ], | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment