Skip to content

Instantly share code, notes, and snippets.

@ChrisMarxDev
Created July 22, 2024 07:15
Show Gist options
  • Save ChrisMarxDev/fa81348e733e59097792939ce600b871 to your computer and use it in GitHub Desktop.
Save ChrisMarxDev/fa81348e733e59097792939ce600b871 to your computer and use it in GitHub Desktop.
Paint a white rectangle exactly behind the text
class LineWidgetText extends ConsumerStatefulWidget {
const LineWidgetText({
required this.element,
super.key,
});
final LineElement element;
@override
ConsumerState<LineWidgetText> createState() => _LineWidgetTextState();
}
class _LineWidgetTextState extends ConsumerState<LineWidgetText> {
late final TextEditingController _textController;
@override
void initState() {
super.initState();
_textController = TextEditingController(
text: widget.element.name,
);
_textController.addListener(() {
setState(() {});
});
}
@override
void didUpdateWidget(covariant LineWidgetText oldWidget) {
super.didUpdateWidget(oldWidget);
if (_textController.text != widget.element.name) {
_textController.text = widget.element.name;
}
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraint) {
final style = context.canvas;
final width = (constraint.maxWidth * 0.5).clamp(80, 180).toDouble();
final size = textSize(
_textController.text,
style,
maxWidth: width,
maxLines: 3,
);
return Center(
child: SizedBox(
width: width,
child: Stack(
alignment: Alignment.center,
children: [
Visibility(
visible: _textController.text.isNotEmpty,
child: Container(
width: size.width,
height: size.height,
color: context.background,
),
),
SizedBox(
width: width,
child: TextField(
style: style,
controller: _textController,
onChanged: (value) {
// change text in model
},
cursorColor: context.secondary,
decoration: const InputDecoration(
border: InputBorder.none,
contentPadding: EdgeInsets.zero,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
),
textAlign: TextAlign.center,
textAlignVertical: TextAlignVertical.top,
maxLines: 3,
minLines: 1,
),
),
],
),
),
);
},
);
}
}
Size textSize(
String text,
TextStyle style, {
double maxWidth = double.infinity,
int maxLines = 1,
}) {
final textPainter = TextPainter(
text: TextSpan(text: text, style: style),
maxLines: maxLines,
textDirection: TextDirection.ltr,
)..layout(
maxWidth: maxWidth,
);
return textPainter.size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment