Created
October 24, 2023 13:41
-
-
Save sma/c656344ab05946e5ebd98396db7d7a0d to your computer and use it in GitHub Desktop.
moving the overlaying the text cursor
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'; | |
import 'package:flutter/rendering.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: const Scaffold( | |
body: Center( | |
child: Demo(), | |
), | |
), | |
); | |
} | |
} | |
class Demo extends StatefulWidget { | |
const Demo({super.key}); | |
@override | |
State<Demo> createState() => _DemoState(); | |
} | |
class _DemoState extends State<Demo> { | |
late final _node = FocusNode() | |
..addListener(() { | |
setState(() {}); | |
}); | |
late final _controller = TextEditingController() | |
..addListener(() { | |
_updateCursor(); | |
}); | |
var _rect = Rect.zero; | |
@override | |
void dispose() { | |
_node.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Stack( | |
fit: StackFit.passthrough, | |
children: [ | |
TextField( | |
focusNode: _node, | |
controller: _controller, | |
decoration: const InputDecoration( | |
labelText: 'Name', | |
hintText: 'Enter your name', | |
border: OutlineInputBorder(), | |
), | |
// onChanged: _changed, | |
), | |
if (_node.hasFocus) | |
Positioned( | |
top: 15 + _rect.top + 10, | |
left: 12 + _rect.left, | |
child: Container( | |
width: _rect.width, | |
height: _rect.height, | |
color: Colors.red, | |
), | |
), | |
], | |
); | |
} | |
void _updateCursor() { | |
final editable = context.findRenderObject()?.findChildOfType<RenderEditable>(); | |
if (editable != null) { | |
WidgetsBinding.instance.addPostFrameCallback((_) { | |
setState(() { | |
final selection = _controller.selection; | |
_rect = editable.getLocalRectForCaret(selection.extent); | |
}); | |
}); | |
} | |
} | |
} | |
extension on RenderObject { | |
T? findChildOfType<T extends RenderBox>() { | |
if (this is T) { | |
return this as T; | |
} | |
T? result; | |
visitChildren((child) { | |
result ??= child.findChildOfType<T>(); | |
}); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment