ModernMemoires/lib/utils/widgets/MoodTextArea.dart

102 lines
2.5 KiB
Dart
Raw Normal View History

2023-12-17 23:00:31 +01:00
import 'package:flutter/material.dart';
class MoodTextAreaWidget extends StatefulWidget {
final String initialText;
final bool isDisabled;
final bool hasPrefix;
final bool autoFocus;
final bool forceBlinkingCursor;
MoodTextAreaWidget({
Key? key,
this.initialText = '',
this.isDisabled = false,
this.hasPrefix = false,
this.autoFocus = false,
this.forceBlinkingCursor = false,
}) : super(key: key);
@override
_MoodTextAreaWidgetState createState() => _MoodTextAreaWidgetState();
}
class _MoodTextAreaWidgetState extends State<MoodTextAreaWidget> {
late TextEditingController _controller;
final FocusNode _focusNode = FocusNode();
late bool _isEditingEnabled;
@override
void initState() {
super.initState();
String initialText =
widget.hasPrefix ? 'why? ' + widget.initialText : widget.initialText;
_controller = TextEditingController(text: initialText);
_isEditingEnabled = !widget.isDisabled;
_focusNode.addListener(() {
if (!_focusNode.hasFocus) {
setState(() {
// Remove cursor when focus is lost
if (!widget.forceBlinkingCursor) {
_controller.text = _controller.text.replaceAll('|', '');
}
});
}
});
if (widget.autoFocus) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_isEditingEnabled) {
_focusNode.requestFocus();
}
});
}
}
void enableEditing() {
setState(() {
_isEditingEnabled = true;
_focusNode.requestFocus();
});
}
void disableEditing() {
setState(() {
_isEditingEnabled = false;
_focusNode.unfocus();
});
}
@override
Widget build(BuildContext context) {
return TextField(
controller: _controller,
focusNode: _focusNode,
keyboardType: TextInputType.multiline,
maxLines: null,
enabled: _isEditingEnabled,
cursorColor:
widget.forceBlinkingCursor ? Colors.black : Colors.transparent,
style: TextStyle(color: Colors.black, fontSize: 18),
decoration: InputDecoration(
border: InputBorder.none,
),
onChanged: (value) {
if (widget.hasPrefix && !value.startsWith('why? ')) {
_controller.text = 'why? ' + value;
_controller.selection = TextSelection.fromPosition(
TextPosition(offset: _controller.text.length),
);
}
},
);
}
@override
void dispose() {
_controller.dispose();
_focusNode.dispose();
super.dispose();
}
}