Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix errors and add support for the latest stable Flutter version #138

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,5 @@ pubspec.lock

# Old files
*.old

.DS_Store
130 changes: 58 additions & 72 deletions lib/src/chips_input.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ import 'text_cursor.dart';

typedef ChipsInputSuggestions<T> = FutureOr<List<T>> Function(String query);
typedef ChipSelected<T> = void Function(T data, bool selected);
typedef ChipsBuilder<T> = Widget Function(
BuildContext context, ChipsInputState<T> state, T data);
typedef ChipsBuilder<T> = Widget Function(BuildContext context, ChipsInputState<T> state, T data);

const kObjectReplacementChar = 0xFFFD;

Expand All @@ -19,9 +18,7 @@ extension on TextEditingValue {
text.codeUnits.where((ch) => ch != kObjectReplacementChar),
);

List<int> get replacementCharacters => text.codeUnits
.where((ch) => ch == kObjectReplacementChar)
.toList(growable: false);
List<int> get replacementCharacters => text.codeUnits.where((ch) => ch == kObjectReplacementChar).toList(growable: false);

int get replacementCharactersCount => replacementCharacters.length;
}
Expand Down Expand Up @@ -84,12 +81,10 @@ class ChipsInput<T> extends StatefulWidget {
ChipsInputState<T> createState() => ChipsInputState<T>();
}

class ChipsInputState<T> extends State<ChipsInput<T>>
implements TextInputClient {
class ChipsInputState<T> extends State<ChipsInput<T>> with TextInputClient {
Set<T> _chips = <T>{};
List<T?>? _suggestions;
final StreamController<List<T?>?> _suggestionsStreamController =
StreamController<List<T>?>.broadcast();
final StreamController<List<T?>?> _suggestionsStreamController = StreamController<List<T>?>.broadcast();
int _searchId = 0;
TextEditingValue _value = const TextEditingValue();
TextInputConnection? _textInputConnection;
Expand All @@ -107,15 +102,12 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
textCapitalization: widget.textCapitalization,
);

bool get _hasInputConnection =>
_textInputConnection != null && _textInputConnection!.attached;
bool get _hasInputConnection => _textInputConnection != null && _textInputConnection!.attached;

bool get _hasReachedMaxChips =>
widget.maxChips != null && _chips.length >= widget.maxChips!;
bool get _hasReachedMaxChips => widget.maxChips != null && _chips.length >= widget.maxChips!;

FocusNode? _focusNode;
FocusNode get _effectiveFocusNode =>
widget.focusNode ?? (_focusNode ??= FocusNode());
FocusNode get _effectiveFocusNode => widget.focusNode ?? (_focusNode ??= FocusNode());
late FocusAttachment _nodeAttachment;

RenderBox? get renderBox => context.findRenderObject() as RenderBox?;
Expand All @@ -126,9 +118,7 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
void initState() {
super.initState();
_chips.addAll(widget.initialValue);
_suggestions = widget.initialSuggestions
?.where((r) => !_chips.contains(r))
.toList(growable: false);
_suggestions = widget.initialSuggestions?.where((r) => !_chips.contains(r)).toList(growable: false);
_suggestionsBoxController = SuggestionsBoxController(context);

_effectiveFocusNode.addListener(_handleFocusChanged);
Expand Down Expand Up @@ -183,19 +173,14 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
final renderBoxOffset = renderBox!.localToGlobal(Offset.zero);
final topAvailableSpace = renderBoxOffset.dy;
final mq = MediaQuery.of(context);
final bottomAvailableSpace = mq.size.height -
mq.viewInsets.bottom -
renderBoxOffset.dy -
size.height;
final bottomAvailableSpace = mq.size.height - mq.viewInsets.bottom - renderBoxOffset.dy - size.height;
var suggestionBoxHeight = max(topAvailableSpace, bottomAvailableSpace);
if (null != widget.suggestionsBoxMaxHeight) {
suggestionBoxHeight =
min(suggestionBoxHeight, widget.suggestionsBoxMaxHeight!);
suggestionBoxHeight = min(suggestionBoxHeight, widget.suggestionsBoxMaxHeight!);
}
final showTop = topAvailableSpace > bottomAvailableSpace;
// print("showTop: $showTop" );
final compositedTransformFollowerOffset =
showTop ? Offset(0, -size.height) : Offset.zero;
final compositedTransformFollowerOffset = showTop ? Offset(0, -size.height) : Offset.zero;

return StreamBuilder<List<T?>?>(
stream: _suggestionsStreamController.stream,
Expand Down Expand Up @@ -288,7 +273,7 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
Future.delayed(const Duration(milliseconds: 300), () {
WidgetsBinding.instance.addPostFrameCallback((_) async {
final renderBox = context.findRenderObject() as RenderBox;
await Scrollable.of(context)?.position.ensureVisible(renderBox);
await Scrollable.of(context).position.ensureVisible(renderBox);
});
});
}
Expand All @@ -297,8 +282,7 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
final localId = ++_searchId;
final results = await widget.findSuggestions(value);
if (_searchId == localId && mounted) {
setState(() => _suggestions =
results.where((r) => !_chips.contains(r)).toList(growable: false));
setState(() => _suggestions = results.where((r) => !_chips.contains(r)).toList(growable: false));
}
_suggestionsStreamController.add(_suggestions ?? []);
if (!_suggestionsBoxController.isOpened && !_hasReachedMaxChips) {
Expand All @@ -320,20 +304,16 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
final oldTextEditingValue = _value;
if (value.text != oldTextEditingValue.text) {
setState(() => _value = value);
if (value.replacementCharactersCount <
oldTextEditingValue.replacementCharactersCount) {
if (value.replacementCharactersCount < oldTextEditingValue.replacementCharactersCount && _chips.isNotEmpty) {
final removedChip = _chips.last;
setState(() =>
_chips = Set.of(_chips.take(value.replacementCharactersCount)));
setState(() => _chips = Set.of(_chips.take(value.replacementCharactersCount)));
widget.onChanged(_chips.toList(growable: false));
String? putText = '';
if (widget.allowChipEditing && _enteredTexts.containsKey(removedChip)) {
putText = _enteredTexts[removedChip]!;
_enteredTexts.remove(removedChip);
}
_updateTextInputState(putText: putText);
} else {
_updateTextInputState();
}
_onSearchChanged(_value.normalCharactersText);
}
Expand All @@ -342,9 +322,7 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
void _updateTextInputState({replaceText = false, putText = ''}) {
if (replaceText || putText != '') {
final updatedText =
String.fromCharCodes(_chips.map((_) => kObjectReplacementChar)) +
(replaceText ? '' : _value.normalCharactersText) +
putText;
String.fromCharCodes(_chips.map((_) => kObjectReplacementChar)) + (replaceText ? '' : _value.normalCharactersText) + putText;
setState(() => _value = _value.copyWith(
text: updatedText,
selection: TextSelection.collapsed(offset: updatedText.length),
Expand All @@ -355,6 +333,7 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
_closeInputConnectionIfNeeded(); //Hack for #34 (https://github.com/danvick/flutter_chips_input/issues/34#issuecomment-684505282). TODO: Find permanent fix
_textInputConnection ??= TextInput.attach(this, textInputConfiguration);
_textInputConnection?.setEditingState(_value);
_textInputConnection?.show();
}

@override
Expand Down Expand Up @@ -415,9 +394,7 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
@override
Widget build(BuildContext context) {
_nodeAttachment.reparent();
final chipsChildren = _chips
.map<Widget>((data) => widget.chipBuilder(context, this, data))
.toList();
final chipsChildren = _chips.map<Widget>((data) => widget.chipBuilder(context, this, data)).toList();

final theme = Theme.of(context);

Expand All @@ -434,8 +411,7 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
_value.normalCharactersText,
maxLines: 1,
overflow: widget.textOverflow,
style: widget.textStyle ??
theme.textTheme.subtitle1!.copyWith(height: 1.5),
style: widget.textStyle ?? theme.textTheme.titleMedium!.copyWith(height: 1.5),
),
),
Flexible(
Expand All @@ -447,38 +423,48 @@ class ChipsInputState<T> extends State<ChipsInput<T>>
),
);

return NotificationListener<SizeChangedLayoutNotification>(
onNotification: (SizeChangedLayoutNotification val) {
WidgetsBinding.instance.addPostFrameCallback((_) async {
_suggestionsBoxController.overlayEntry?.markNeedsBuild();
});
return true;
return RawKeyboardListener(
focusNode: _focusNode!, // or FocusNode()
onKey: (event) {
final str = currentTextEditingValue.text;
if (event.runtimeType.toString() == 'RawKeyDownEvent' && event.logicalKey == LogicalKeyboardKey.backspace && str.isNotEmpty) {
final sd = str.substring(0, str.length - 1);
updateEditingValue(TextEditingValue(text: sd, selection: TextSelection.collapsed(offset: sd.length)));
}
},
child: SizeChangedLayoutNotifier(
child: Column(
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
requestKeyboard();
},
child: InputDecorator(
decoration: widget.decoration,
isFocused: _effectiveFocusNode.hasFocus,
isEmpty: _value.text.isEmpty && _chips.isEmpty,
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 4.0,
runSpacing: 4.0,
children: chipsChildren,
child: NotificationListener<SizeChangedLayoutNotification>(
onNotification: (SizeChangedLayoutNotification val) {
WidgetsBinding.instance.addPostFrameCallback((_) async {
_suggestionsBoxController.overlayEntry?.markNeedsBuild();
});
return true;
},
child: SizeChangedLayoutNotifier(
child: Column(
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
requestKeyboard();
},
child: InputDecorator(
decoration: widget.decoration,
isFocused: _effectiveFocusNode.hasFocus,
isEmpty: _value.text.isEmpty && _chips.isEmpty,
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 4.0,
runSpacing: 4.0,
children: chipsChildren,
),
),
),
),
CompositedTransformTarget(
link: _layerLink,
child: Container(),
),
],
CompositedTransformTarget(
link: _layerLink,
child: Container(),
),
],
),
),
),
);
Expand Down
2 changes: 1 addition & 1 deletion lib/src/suggestions_box_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class SuggestionsBoxController {
void open() {
if (_isOpened) return;
assert(overlayEntry != null);
Overlay.of(context)!.insert(overlayEntry!);
Overlay.of(context).insert(overlayEntry!);
_isOpened = true;
}

Expand Down
9 changes: 3 additions & 6 deletions lib/src/text_cursor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,10 @@ class TextCursor extends StatefulWidget {
final bool resumed;

@override
_TextCursorState createState() => _TextCursorState();
State<TextCursor> createState() => _TextCursorState();
}

class _TextCursorState extends State<TextCursor>
with SingleTickerProviderStateMixin {
class _TextCursorState extends State<TextCursor> with SingleTickerProviderStateMixin {
bool _displayed = false;
late Timer _timer;

Expand Down Expand Up @@ -46,9 +45,7 @@ class _TextCursorState extends State<TextCursor>
opacity: _displayed && widget.resumed ? 1.0 : 0.0,
child: Container(
width: 2.0,
color: theme.textSelectionTheme.cursorColor ??
theme.textSelectionTheme.selectionColor ??
theme.primaryColor,
color: theme.textSelectionTheme.cursorColor ?? theme.textSelectionTheme.selectionColor ?? theme.primaryColor,
),
),
);
Expand Down