From 8477debb8dff5e23cdd525424642de6b4e04fadc Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 14:11:04 +0200 Subject: [PATCH 1/5] fix: ignore non-finite steps and steps rounded beyond the bounds setValue clamped the requested value and then formatted it with the configured number of decimals. A NaN or infinite value was written into the text field, and rounding could push a clamped value past a fractional bound (max: 0.29 with decimals: 1 accepted 0.3). Ignore non-finite values, round before validating, and drop a step whose rounded value falls outside [min, max]. onSubmitted now receives the already-rounded value. --- lib/src/base_spin_box.dart | 16 +++++++++--- test/value_input_lifecycle_test.dart | 38 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 test/value_input_lifecycle_test.dart diff --git a/lib/src/base_spin_box.dart b/lib/src/base_spin_box.dart index e38d4d3..b9df325 100644 --- a/lib/src/base_spin_box.dart +++ b/lib/src/base_spin_box.dart @@ -121,14 +121,22 @@ mixin SpinBoxMixin on State { } void setValue(double v) { - final newValue = v.clamp(widget.min, widget.max); - if (newValue == value) return; - + if (!v.isFinite) return; + final clamped = v.clamp(widget.min, widget.max); + final newValue = double.parse(_formatText(clamped)); + // Formatting can round a value beyond a fractional bound (for example + // 0.29 becomes 0.3 with one decimal place). Never submit an invalid step. + if (!newValue.isFinite || + newValue < widget.min || + newValue > widget.max || + newValue == _value) { + return; + } if (widget.canChange?.call(newValue) == false) return; widget.beforeChange?.call(); setState(() => _updateController(value, newValue)); - widget.onSubmitted?.call(double.parse(_formatText(newValue))); + widget.onSubmitted?.call(newValue); widget.afterChange?.call(); } diff --git a/test/value_input_lifecycle_test.dart b/test/value_input_lifecycle_test.dart new file mode 100644 index 0000000..ec573e2 --- /dev/null +++ b/test/value_input_lifecycle_test.dart @@ -0,0 +1,38 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_spinbox/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _app(SpinBox spinBox) { + return MaterialApp(home: Scaffold(body: Center(child: spinBox))); +} + +void main() { + testWidgets('step rounding never escapes fractional bounds', (tester) async { + await tester.pumpWidget( + _app(SpinBox(max: 0.29, value: 0.2, step: 0.1, decimals: 1)), + ); + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + + final state = tester.state(find.byType(SpinBox)); + expect(state.value, 0.2); + expect(state.controller.text, '0.2'); + }); + + testWidgets('non-finite programmatic steps are ignored', (tester) async { + final changes = []; + await tester.pumpWidget( + _app(SpinBox(value: 5, onChanged: changes.add)), + ); + final state = tester.state(find.byType(SpinBox)); + + state.setValue(double.nan); + state.setValue(double.infinity); + state.setValue(double.negativeInfinity); + await tester.pump(); + + expect(state.value, 5); + expect(state.controller.text, '5'); + expect(changes, isEmpty); + }); +} From 8764040058f92f5356e3ec282493ae582a99e8fe Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 14:11:56 +0200 Subject: [PATCH 2/5] fix: notify a button or key step once, without re-entering the listener A +/-, arrow or page step wrote the new text into the controller and relied on the controller listener to update the value and call onChanged. That listener ran inside setValue's setState, called canChange a second time for the same value and triggered a second setState. Suppress the listener while the widget writes its own text, update the value directly and call onChanged explicitly, once per step. _updateController now shifts the selection by the oldValue it is given (instead of the current value, which didUpdateWidget had already replaced), clamps it to the new text, and clears any IME composing range that referred to the old text. --- lib/src/base_spin_box.dart | 42 ++++++++++++++++++++-------- test/value_input_lifecycle_test.dart | 10 +++++++ 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/lib/src/base_spin_box.dart b/lib/src/base_spin_box.dart index b9df325..cded3fa 100644 --- a/lib/src/base_spin_box.dart +++ b/lib/src/base_spin_box.dart @@ -51,6 +51,7 @@ mixin SpinBoxMixin on State { late double _cachedValue; late final FocusNode _focusNode; late final TextEditingController _controller; + bool _updatingController = false; double get value => _value; bool get hasFocus => _focusNode.hasFocus; @@ -105,6 +106,7 @@ mixin SpinBoxMixin on State { void _pageStepDown() => setValue(value - widget.pageStep!); void _updateValue() { + if (_updatingController) return; final v = _parseValue(_controller.text); if (v == _value) return; @@ -135,7 +137,11 @@ mixin SpinBoxMixin on State { if (widget.canChange?.call(newValue) == false) return; widget.beforeChange?.call(); - setState(() => _updateController(value, newValue)); + setState(() { + _updateController(_value, newValue); + _value = newValue; + }); + widget.onChanged?.call(newValue); widget.onSubmitted?.call(newValue); widget.afterChange?.call(); } @@ -143,16 +149,30 @@ mixin SpinBoxMixin on State { void _updateController(double oldValue, double newValue) { final text = _formatText(newValue); final selection = _controller.selection; - final oldOffset = value.isNegative ? 1 : 0; - final newOffset = _parseValue(text).isNegative ? 1 : 0; - - _controller.value = _controller.value.copyWith( - text: text, - selection: selection.copyWith( - baseOffset: selection.baseOffset - oldOffset + newOffset, - extentOffset: selection.extentOffset - oldOffset + newOffset, - ), - ); + final oldOffset = oldValue.isNegative ? 1 : 0; + final newOffset = newValue.isNegative ? 1 : 0; + + final updatedSelection = selection.isValid + ? selection.copyWith( + baseOffset: (selection.baseOffset - oldOffset + newOffset) + .clamp(0, text.length), + extentOffset: (selection.extentOffset - oldOffset + newOffset) + .clamp(0, text.length), + ) + : selection; + + // Updating the text controller already notifies EditableText. Suppress + // our own listener to avoid a second setState/onChanged per button press. + _updatingController = true; + try { + _controller.value = _controller.value.copyWith( + text: text, + selection: updatedSelection, + composing: TextRange.empty, + ); + } finally { + _updatingController = false; + } } @protected diff --git a/test/value_input_lifecycle_test.dart b/test/value_input_lifecycle_test.dart index ec573e2..867c5b7 100644 --- a/test/value_input_lifecycle_test.dart +++ b/test/value_input_lifecycle_test.dart @@ -7,6 +7,16 @@ Widget _app(SpinBox spinBox) { } void main() { + testWidgets('button step sends one numeric change callback', (tester) async { + final changes = []; + await tester.pumpWidget( + _app(SpinBox(value: 2, onChanged: changes.add)), + ); + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + expect(changes, [3]); + }); + testWidgets('step rounding never escapes fractional bounds', (tester) async { await tester.pumpWidget( _app(SpinBox(max: 0.29, value: 0.2, step: 0.1, decimals: 1)), From 4f15909706020373b99cd4c383a280c523875a5b Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 14:12:53 +0200 Subject: [PATCH 3/5] fix: do not report incomplete input as zero, roll back to the last valid value Text that does not parse as a number yet (an empty field, "-", ".") was treated as 0: the state value became 0 and onChanged(0) was called while the user was still typing. The same happened for a number below min while typing towards a valid value (e.g. "1" on the way to "15" with min: 10). - Incomplete text keeps the current value and does not call onChanged. - An out-of-range number updates the internal value but calls onChanged only once it is within [min, max]. - The rollback value used on blur/submit and after a canChange rejection is the last accepted value (typed or stepped), instead of the value from the previous focus session. - A canChange rejection restores the previous text without re-entering the controller listener. The shared input tests now expect the value to stay at 1 after the field is cleared. --- lib/src/base_spin_box.dart | 45 +++++++++++++--------- test/test_spinbox.dart | 4 +- test/value_input_lifecycle_test.dart | 57 ++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 20 deletions(-) diff --git a/lib/src/base_spin_box.dart b/lib/src/base_spin_box.dart index cded3fa..0b01053 100644 --- a/lib/src/base_spin_box.dart +++ b/lib/src/base_spin_box.dart @@ -60,7 +60,6 @@ mixin SpinBoxMixin on State { SpinFormatter get formatter => SpinFormatter( min: widget.min, max: widget.max, decimals: widget.decimals); - static double _parseValue(String text) => double.tryParse(text) ?? 0; String _formatText(double value) { return value.toStringAsFixed(widget.decimals).padLeft(widget.digits, '0'); } @@ -107,19 +106,26 @@ mixin SpinBoxMixin on State { void _updateValue() { if (_updatingController) return; - final v = _parseValue(_controller.text); - if (v == _value) return; - - if (widget.canChange?.call(v) == false) { - controller.text = _formatText(_cachedValue); - setState(() { - _value = _cachedValue; - }); + // Empty input, a lone sign, or a decimal separator is incomplete text. + // Keep the last numeric value rather than broadcasting a spurious zero. + final parsed = double.tryParse(_controller.text); + if (parsed == null || !parsed.isFinite || parsed == _value) return; + + if (widget.canChange?.call(parsed) == false) { + final previous = + _value >= widget.min && _value <= widget.max ? _value : _cachedValue; + _updateController(_value, previous); + if (previous != _value) setState(() => _value = previous); return; } - setState(() => _value = v); - widget.onChanged?.call(v); + setState(() => _value = parsed); + // A temporarily out-of-range number is allowed while typing, but must + // not trigger expensive client-side work until it is a valid value. + if (parsed >= widget.min && parsed <= widget.max) { + _cachedValue = parsed; + widget.onChanged?.call(parsed); + } } void setValue(double v) { @@ -139,7 +145,7 @@ mixin SpinBoxMixin on State { widget.beforeChange?.call(); setState(() { _updateController(_value, newValue); - _value = newValue; + _value = _cachedValue = newValue; }); widget.onChanged?.call(newValue); widget.onSubmitted?.call(newValue); @@ -176,13 +182,16 @@ mixin SpinBoxMixin on State { } @protected - double fixupValue(String value) { - final v = _parseValue(value); - if (value.isEmpty || (v < widget.min || v > widget.max)) { - // will trigger notify to _updateValue() - _controller.text = _formatText(_cachedValue); + double fixupValue(String text) { + final parsed = double.tryParse(text); + if (parsed == null || + !parsed.isFinite || + parsed < widget.min || + parsed > widget.max) { + _updateController(_value, _cachedValue); + _value = _cachedValue; } else { - _cachedValue = _value; + _value = _cachedValue = parsed; } return _cachedValue; } diff --git a/test/test_spinbox.dart b/test/test_spinbox.dart index 5436cf0..0740e6d 100644 --- a/test/test_spinbox.dart +++ b/test/test_spinbox.dart @@ -240,7 +240,7 @@ void testInput(TestBuilder builder) { tester.testTextInput.updateEditingValue(TextEditingValue.empty); await tester.idle(); - expect(tester.state(find.byType(S)), hasValue(0)); + expect(tester.state(find.byType(S)), hasValue(1)); expect(find.editableText, hasText('')); await tester.testTextInput.receiveAction(TextInputAction.done); @@ -257,7 +257,7 @@ void testInput(TestBuilder builder) { tester.testTextInput.updateEditingValue(TextEditingValue.empty); await tester.idle(); - expect(tester.state(find.byType(S)), hasValue(0)); + expect(tester.state(find.byType(S)), hasValue(1)); find.editableText.focusNode.unfocus(); await tester.idle(); diff --git a/test/value_input_lifecycle_test.dart b/test/value_input_lifecycle_test.dart index 867c5b7..b331be8 100644 --- a/test/value_input_lifecycle_test.dart +++ b/test/value_input_lifecycle_test.dart @@ -7,6 +7,63 @@ Widget _app(SpinBox spinBox) { } void main() { + testWidgets('clearing input does not notify a false zero', (tester) async { + final changes = []; + await tester.pumpWidget( + _app(SpinBox(value: 5, autofocus: true, onChanged: changes.add)), + ); + await tester.pump(); + + await tester.enterText(find.byType(TextField), ''); + await tester.pump(); + + expect(changes, isEmpty); + final state = tester.state(find.byType(SpinBox)); + expect(state.value, 5); + expect(state.controller.text, ''); + + state.focusNode.unfocus(); + await tester.pump(); + expect(state.value, 5); + expect(state.controller.text, '5'); + }); + + testWidgets('steps update rollback value', (tester) async { + await tester.pumpWidget(_app(SpinBox(value: 2, autofocus: true))); + await tester.pump(); + + await tester.tap(find.byIcon(Icons.add)); + await tester.pump(); + final state = tester.state(find.byType(SpinBox)); + expect(state.value, 3); + + await tester.enterText(find.byType(TextField), ''); + state.focusNode.unfocus(); + await tester.pump(); + expect(state.value, 3); + expect(state.controller.text, '3'); + }); + + testWidgets('accepted text updates the empty-input rollback', (tester) async { + final changes = []; + await tester.pumpWidget( + _app(SpinBox(value: 2, autofocus: true, onChanged: changes.add)), + ); + await tester.pump(); + + await tester.enterText(find.byType(TextField), '7'); + await tester.pump(); + expect(changes, [7]); + + await tester.enterText(find.byType(TextField), ''); + final state = tester.state(find.byType(SpinBox)); + state.focusNode.unfocus(); + await tester.pump(); + + expect(state.value, 7); + expect(state.controller.text, '7'); + }); + testWidgets('button step sends one numeric change callback', (tester) async { final changes = []; await tester.pumpWidget( From 66e4a4acad258efd90f6bbf954aa8203e20ecec7 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 14:13:29 +0200 Subject: [PATCH 4/5] perf: reuse the input formatter and shortcut bindings across rebuilds The formatter and bindings getters built a new SpinFormatter and a new shortcut map on every build. A new inputFormatters instance and a new CallbackShortcuts map make the text field and shortcut manager treat the configuration as changed on each rebuild. Create them in initState and recreate them only when min, max or decimals (formatter) or the presence of pageStep (bindings) change. --- lib/src/base_spin_box.dart | 27 ++++++++++++++++++++++++--- test/value_input_lifecycle_test.dart | 17 +++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/lib/src/base_spin_box.dart b/lib/src/base_spin_box.dart index 0b01053..1f24b54 100644 --- a/lib/src/base_spin_box.dart +++ b/lib/src/base_spin_box.dart @@ -51,20 +51,28 @@ mixin SpinBoxMixin on State { late double _cachedValue; late final FocusNode _focusNode; late final TextEditingController _controller; + late SpinFormatter _formatter; + late Map _bindings; bool _updatingController = false; double get value => _value; bool get hasFocus => _focusNode.hasFocus; FocusNode get focusNode => _focusNode; TextEditingController get controller => _controller; - SpinFormatter get formatter => SpinFormatter( - min: widget.min, max: widget.max, decimals: widget.decimals); + SpinFormatter get formatter => _formatter; + Map get bindings => _bindings; String _formatText(double value) { return value.toStringAsFixed(widget.decimals).padLeft(widget.digits, '0'); } - Map get bindings { + SpinFormatter _createFormatter() => SpinFormatter( + min: widget.min, + max: widget.max, + decimals: widget.decimals, + ); + + Map _createBindings() { return { // ### TODO: use SingleActivator fixed in Flutter 2.10+ // https://github.com/flutter/flutter/issues/92717 @@ -82,6 +90,8 @@ mixin SpinBoxMixin on State { super.initState(); _value = widget.value; _cachedValue = widget.value; + _formatter = _createFormatter(); + _bindings = _createBindings(); _controller = TextEditingController(text: _formatText(_value)); _controller.addListener(_updateValue); _focusNode = widget.focusNode ?? FocusNode(); @@ -215,6 +225,17 @@ mixin SpinBoxMixin on State { @override void didUpdateWidget(T oldWidget) { super.didUpdateWidget(oldWidget); + + final boundsChanged = + oldWidget.min != widget.min || oldWidget.max != widget.max; + final precisionChanged = oldWidget.decimals != widget.decimals; + if (boundsChanged || precisionChanged) { + _formatter = _createFormatter(); + } + if ((oldWidget.pageStep == null) != (widget.pageStep == null)) { + _bindings = _createBindings(); + } + if (oldWidget.value != widget.value) { _controller.removeListener(_updateValue); _value = _cachedValue = widget.value; diff --git a/test/value_input_lifecycle_test.dart b/test/value_input_lifecycle_test.dart index b331be8..f816c16 100644 --- a/test/value_input_lifecycle_test.dart +++ b/test/value_input_lifecycle_test.dart @@ -64,6 +64,23 @@ void main() { expect(state.controller.text, '7'); }); + testWidgets('input helpers are reused on rebuild', (tester) async { + await tester.pumpWidget(_app(SpinBox(value: 5, pageStep: 10))); + final state = tester.state(find.byType(SpinBox)); + final formatter = state.formatter; + final bindings = state.bindings; + + await tester.pumpWidget(_app(SpinBox(value: 6, pageStep: 10))); + expect(state.formatter, same(formatter)); + expect(state.bindings, same(bindings)); + + await tester.pumpWidget( + _app(SpinBox(value: 6, decimals: 2, pageStep: 10)), + ); + expect(state.formatter, isNot(same(formatter))); + expect(state.bindings, same(bindings)); + }); + testWidgets('button step sends one numeric change callback', (tester) async { final changes = []; await tester.pumpWidget( From 7c361cd9ba728ff28a91250e6312e5d4707d2b78 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 14:14:06 +0200 Subject: [PATCH 5/5] fix: handle focusNode, bounds and controlled value updates from the parent didUpdateWidget only handled a changed value, and initState used the initial value as given: - Replacing the focusNode kept listening to (and reporting focus of) the old node; an internally owned node was never released. - An initial value outside [min, max] was shown and reported as is. - Changing min/max no longer clamped the current value, and changing decimals or digits did not reformat the text. - A controlled parent that echoes onChanged back into value replaced the text on every keystroke, turning "3.4" into "3.40" and moving the cursor while the user was typing. Rebind the focus listener when the node changes, clamp the initial value and the value after a bounds change (without calling onChanged), reformat on decimals/digits changes, and keep the user's text while focused when the parent echoes the value it already shows. --- lib/src/base_spin_box.dart | 37 ++++++++++++++++---- test/value_input_lifecycle_test.dart | 50 ++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/lib/src/base_spin_box.dart b/lib/src/base_spin_box.dart index 1f24b54..f651b2e 100644 --- a/lib/src/base_spin_box.dart +++ b/lib/src/base_spin_box.dart @@ -49,7 +49,7 @@ abstract class BaseSpinBox extends StatefulWidget { mixin SpinBoxMixin on State { late double _value; late double _cachedValue; - late final FocusNode _focusNode; + late FocusNode _focusNode; late final TextEditingController _controller; late SpinFormatter _formatter; late Map _bindings; @@ -88,8 +88,8 @@ mixin SpinBoxMixin on State { @override void initState() { super.initState(); - _value = widget.value; - _cachedValue = widget.value; + _value = widget.value.clamp(widget.min, widget.max); + _cachedValue = _value; _formatter = _createFormatter(); _bindings = _createBindings(); _controller = TextEditingController(text: _formatText(_value)); @@ -226,9 +226,19 @@ mixin SpinBoxMixin on State { void didUpdateWidget(T oldWidget) { super.didUpdateWidget(oldWidget); + // A parent can replace an externally owned FocusNode without replacing + // this widget's State. Rebind to the new node and release owned nodes. + if (oldWidget.focusNode != widget.focusNode) { + _focusNode.removeListener(_handleFocusChanged); + if (oldWidget.focusNode == null) _focusNode.dispose(); + _focusNode = widget.focusNode ?? FocusNode(); + _focusNode.addListener(_handleFocusChanged); + } + final boundsChanged = oldWidget.min != widget.min || oldWidget.max != widget.max; final precisionChanged = oldWidget.decimals != widget.decimals; + final digitsChanged = oldWidget.digits != widget.digits; if (boundsChanged || precisionChanged) { _formatter = _createFormatter(); } @@ -237,10 +247,23 @@ mixin SpinBoxMixin on State { } if (oldWidget.value != widget.value) { - _controller.removeListener(_updateValue); - _value = _cachedValue = widget.value; - _updateController(oldWidget.value, widget.value); - _controller.addListener(_updateValue); + final nextValue = widget.value.clamp(widget.min, widget.max); + // Preserve a user's partially formatted text and cursor when a + // controlled parent echoes the same numeric value on each keystroke. + final sameEditingValue = hasFocus && + !precisionChanged && + !digitsChanged && + double.tryParse(_controller.text) == nextValue; + if (!sameEditingValue) _updateController(_value, nextValue); + _value = _cachedValue = nextValue; + } else if (boundsChanged || precisionChanged || digitsChanged) { + final nextValue = _value.clamp(widget.min, widget.max); + if (nextValue != _value || precisionChanged || digitsChanged) { + _updateController(_value, nextValue); + _value = _cachedValue = nextValue; + } else { + _cachedValue = _cachedValue.clamp(widget.min, widget.max); + } } } } diff --git a/test/value_input_lifecycle_test.dart b/test/value_input_lifecycle_test.dart index f816c16..3b28ad7 100644 --- a/test/value_input_lifecycle_test.dart +++ b/test/value_input_lifecycle_test.dart @@ -64,6 +64,56 @@ void main() { expect(state.controller.text, '7'); }); + testWidgets('focus node replacement updates state', (tester) async { + final first = FocusNode(); + final second = FocusNode(); + addTearDown(first.dispose); + addTearDown(second.dispose); + + await tester.pumpWidget(_app(SpinBox(value: 5, focusNode: first))); + await tester.pumpWidget(_app(SpinBox(value: 5, focusNode: second))); + + final state = tester.state(find.byType(SpinBox)); + expect(state.focusNode, same(second)); + second.requestFocus(); + await tester.pump(); + expect(state.hasFocus, isTrue); + }); + + testWidgets('shrinking bounds constrains the value', (tester) async { + await tester.pumpWidget(_app(SpinBox(max: 30, value: 10))); + await tester.pumpWidget(_app(SpinBox(min: 11, max: 30, value: 10))); + + final state = tester.state(find.byType(SpinBox)); + expect(state.value, 11); + expect(state.controller.text, '11'); + }); + + testWidgets('controlled parent preserves typed text', (tester) async { + double value = 1; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) => SpinBox( + value: value, + decimals: 2, + autofocus: true, + onChanged: (v) => setState(() => value = v), + ), + ), + ), + ), + ); + await tester.pump(); + + await tester.enterText(find.byType(TextField), '3.4'); + await tester.pump(); + final state = tester.state(find.byType(SpinBox)); + expect(state.controller.text, '3.4'); + expect(state.value, 3.4); + }); + testWidgets('input helpers are reused on rebuild', (tester) async { await tester.pumpWidget(_app(SpinBox(value: 5, pageStep: 10))); final state = tester.state(find.byType(SpinBox));