Last active
May 5, 2023 12:08
-
-
Save KammererTob/112cc5c8b9cf28fac38b4b37656aede5 to your computer and use it in GitHub Desktop.
FocusNode listener triggered on rebuild
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 'package:flutter/material.dart'; | |
const Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark().copyWith( | |
scaffoldBackgroundColor: darkBlue, | |
), | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: Container(child: MyWidget(), width: 300, height: 200) | |
), | |
), | |
); | |
} | |
} | |
class MyWidget extends StatefulWidget { | |
@override | |
MyWidgetState createState() => MyWidgetState(); | |
} | |
class MyWidgetState extends State<MyWidget> { | |
late final FocusNode markFocusNode; | |
bool isLocked = false; | |
@override | |
void initState() { | |
markFocusNode = FocusNode(debugLabel: "MarkFocusNode") | |
..addListener(_onChangeFocus); | |
super.initState(); | |
} | |
@override | |
void dispose() { | |
markFocusNode.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Column( | |
children: [ | |
TextField( | |
autofocus: false, | |
enabled: !isLocked, | |
focusNode: markFocusNode, | |
onChanged: (val) => print('onChanged'), | |
textInputAction: TextInputAction.next, | |
), | |
ElevatedButton(child: Text('Toggle Lock'), onPressed: () => setState(() => isLocked = !isLocked)) | |
] | |
); | |
} | |
void _onChangeFocus() { | |
if (!markFocusNode.hasFocus) { | |
print('Lost focus'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment