Created
October 14, 2022 10:32
-
-
Save VintageAppMaker/219146fafcda80e7dfd8108e514c310c to your computer and use it in GitHub Desktop.
ChildStatefulWithKey.dart
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(StateFulTest()); | |
} | |
class StateFulTest extends StatefulWidget { | |
@override | |
_StateFulTestState createState() { | |
return _StateFulTestState(); | |
} | |
} | |
class _StateFulTestState extends State<StateFulTest> | |
with AutomaticKeepAliveClientMixin { | |
late List<Widget> _items; | |
ScrollController controller = ScrollController(); | |
GlobalKey buttonKey = GlobalKey(); | |
@override | |
void initState() { | |
_items = [ | |
GestureDetector( | |
onTap: () { | |
setState(() {}); | |
}, | |
child: Text("Click me - this ${this.context.toString()}")), | |
for (var i = 0; i < 10; i++) Icon(Icons.bolt), | |
GestureDetector( | |
onTap: () { | |
var w = (buttonKey.currentState as _ButtonWidgetState); | |
w.setVisble(!w.isVisble); | |
}, | |
child: Text("Click me - ButtonWidget(child with key)")) | |
]; | |
super.initState(); | |
} | |
@override | |
void dispose() { | |
controller.dispose(); | |
super.dispose(); | |
} | |
// Setting to true will force the tab to never be disposed. This could be dangerous. | |
@override | |
bool get wantKeepAlive => true; | |
@override | |
Widget build(BuildContext context) { | |
print("${this.widget.toString()}"); | |
return MaterialApp( | |
home: Scaffold( | |
floatingActionButton: ButtonWidget(key: buttonKey), | |
body: SingleChildScrollView( | |
controller: controller, | |
child: Expanded( | |
child: Container( | |
color: Colors.amber, | |
width: double.infinity, | |
child: Column( | |
crossAxisAlignment: CrossAxisAlignment.center, | |
children: _items, | |
), | |
)), | |
), | |
), | |
); | |
} | |
} | |
class ButtonWidget extends StatefulWidget { | |
const ButtonWidget({Key? key}) : super(key: key); | |
@override | |
_ButtonWidgetState createState() => _ButtonWidgetState(); | |
} | |
class _ButtonWidgetState extends State<ButtonWidget> { | |
bool isVisble = false; | |
void setVisble(bool b) { | |
setState(() { | |
isVisble = b; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
print("${this.widget.toString()}"); | |
return Visibility( | |
visible: isVisble, | |
child: Container( | |
padding: EdgeInsets.all(10), | |
decoration: BoxDecoration( | |
borderRadius: BorderRadius.circular(50), | |
color: Colors.red, | |
), | |
child: Icon( | |
Icons.add_alert, | |
color: Colors.black, | |
), | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment