Skip to content

Instantly share code, notes, and snippets.

@ltvu93
Last active January 30, 2024 03:26
Show Gist options
  • Save ltvu93/31d04c2d86d335251c5ad7282b008424 to your computer and use it in GitHub Desktop.
Save ltvu93/31d04c2d86d335251c5ad7282b008424 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() {
runApp(TestAlignApp());
}
class TestAlignApp extends StatefulWidget {
@override
State<TestAlignApp> createState() => _TestAlignAppState();
}
class _TestAlignAppState extends State<TestAlignApp> {
TextEditingController _controller = TextEditingController(text: '12345');
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 20),
TextField(
controller: _controller,
),
SizedBox(height: 20),
Container(
width: 200,
height: 200,
color: Colors.red,
child: ValueListenableBuilder<TextEditingValue>(
valueListenable: _controller,
builder: (context, textEdit, child) {
return Align(
alignment: Alignment(-1.25, -1),
child: Container(
color: Colors.yellow,
child: Text(
textEdit.text.trim(),
style: TextStyle(
color: Colors.white,
),
),
),
);
},
),
),
SizedBox(height: 20),
Container(
width: 200,
height: 200,
color: Colors.red,
child: Stack(
children: [
Positioned(
top: 0,
left: 0,
child: ValueListenableBuilder<TextEditingValue>(
valueListenable: _controller,
builder: (context, textEdit, child) {
return AlignWithItself(
offset: Offset(-0.5, 0),
child: Container(
color: Colors.yellow,
child: Text(
textEdit.text.trim(),
style: TextStyle(
color: Colors.white,
),
),
),
);
},
),
),
],
),
),
],
),
),
),
),
);
}
}
class AlignWithItself extends StatelessWidget {
final Offset offset;
final Widget child;
const AlignWithItself({Key? key, required this.offset, required this.child})
: super(key: key);
@override
Widget build(BuildContext context) {
return CustomSingleChildLayout(
delegate: _AlignWithItselfLayoutDelegate(
offset: offset,
),
child: child,
);
}
}
class _AlignWithItselfLayoutDelegate extends SingleChildLayoutDelegate {
final Offset offset;
_AlignWithItselfLayoutDelegate({required this.offset});
@override
Size getSize(BoxConstraints constraints) {
return constraints.smallest;
}
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
return constraints;
}
@override
Offset getPositionForChild(Size size, Size childSize) {
return Offset(childSize.width * offset.dx, childSize.height * offset.dy);
}
@override
bool shouldRelayout(_AlignWithItselfLayoutDelegate oldDelegate) {
return offset != oldDelegate.offset;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment