-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathspin_box.dart
489 lines (425 loc) · 14.1 KB
/
spin_box.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// MIT License
//
// Copyright (c) 2020 J-P Nurmi <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import 'dart:math';
import 'package:flutter/material.dart';
import '../base_spin_box.dart';
import 'spin_box_theme.dart';
import 'spin_button.dart';
/// A material design spinbox.
///
/// {@macro flutter_spinbox.SpinBox}
///
/// 
///
/// ```dart
/// import 'package:flutter_spinbox/material.dart'; // or flutter_spinbox.dart for both
///
/// SpinBox(
/// min: 1,
/// max: 100,
/// value: 50,
/// onChanged: (value) => print(value),
/// )
/// ```
///
/// See also [Material Components widgets](https://flutter.dev/docs/development/ui/widgets/material) package.
class SpinBox extends BaseSpinBox {
/// Creates a spinbox.
SpinBox({
Key? key,
this.min = 0,
this.max = 100,
this.step = 1,
this.pageStep,
this.value = 0,
this.interval = const Duration(milliseconds: 100),
this.acceleration,
this.decimals = 0,
this.digits = 0,
bool? enabled,
this.readOnly = false,
this.autofocus = false,
TextInputType? keyboardType,
this.textInputAction,
this.decoration,
this.validator,
this.keyboardAppearance,
Icon? incrementIcon,
Icon? decrementIcon,
this.iconSize,
this.iconColor,
this.showButtons = true,
this.direction = Axis.horizontal,
this.textAlign = TextAlign.center,
this.textDirection = TextDirection.ltr,
this.textStyle,
this.contextMenuBuilder,
this.showCursor,
this.cursorColor,
this.enableInteractiveSelection = true,
this.spacing = 8,
this.onChanged,
this.onSubmitted,
this.canChange,
this.beforeChange,
this.afterChange,
this.focusNode,
this.decimalSeparator = ".",
}) : assert(min <= max),
keyboardType = keyboardType ??
TextInputType.numberWithOptions(
signed: min < 0,
decimal: decimals > 0,
),
enabled = (enabled ?? true) && min < max,
incrementIcon = incrementIcon ?? const Icon(Icons.add),
decrementIcon = decrementIcon ?? const Icon(Icons.remove),
super(key: key);
/// The minimum value the user can enter.
///
/// Defaults to `0.0`. Must be less than or equal to [max].
///
/// If min is equal to [max], the spinbox is disabled.
@override
final double min;
/// The maximum value the user can enter.
///
/// Defaults to `100.0`. Must be greater than or equal to [min].
///
/// If max is equal to [min], the spinbox is disabled.
@override
final double max;
/// The step size for incrementing and decrementing the value.
///
/// Defaults to `1.0`.
@override
final double step;
/// An optional page step size for incrementing and decrementing the value.
///
/// Defaults to `null`.
@override
final double? pageStep;
/// The current value.
///
/// Defaults to `0.0`.
@override
final double value;
/// The number of decimal places used for formatting the value.
///
/// Defaults to `0`.
@override
final int decimals;
/// The number of digits used for formatting the value.
///
/// Defaults to `0`.
@override
final int digits;
/// The interval used for auto-incrementing and -decrementing.
///
/// When holding down the increment and decrement buttons, respectively.
///
/// Defaults to `100` milliseconds.
final Duration interval;
/// The amount of acceleration that is added to the value on each step.
///
/// When holding down the increment and decrement buttons, respectively.
///
/// Defaults to `null` (no acceleration).
final double? acceleration;
/// The visual direction of the spinbox layout.
///
/// In horizontal mode the increment and decrement buttons are on the sides,
/// and in vertical mode the buttons are above and below the input field.
///
/// Defaults to [Axis.horizontal].
final Axis direction;
/// The visual spacing of the spinbox layout.
///
/// In horizontal mode the increment and decrement buttons are on the sides,
/// and in vertical mode the buttons are above and below the input field.
///
/// Defaults to `8.0`.
final double spacing;
/// The visual icon for the increment button.
///
/// Defaults to [Icons.add].
final Icon incrementIcon;
/// The visual icon for the decrement button.
///
/// Defaults to [Icons.remove].
final Icon decrementIcon;
/// The size to use for [incrementIcon] and [decrementIcon].
///
/// If `null`, then the value of [SpinBoxThemeData.iconSize] is used. If
/// that is also `null`, then a pre-defined default is used.
final double? iconSize;
/// The color to use for [incrementIcon] and [decrementIcon].
///
/// If `null`, then the value of [SpinBoxThemeData.iconColor] is used. If
/// that is also `null`, then pre-defined defaults are used.
final MaterialStateProperty<Color?>? iconColor;
/// Whether the increment and decrement buttons are shown.
///
/// Defaults to `true`.
final bool showButtons;
/// See [TextField.focusNode].
@override
final FocusNode? focusNode;
/// Called when the user has changed the value.
@override
final ValueChanged<double>? onChanged;
@override
final bool Function(double value)? canChange;
@override
final VoidCallback? beforeChange;
@override
final VoidCallback? afterChange;
/// The decimal separator used for formatting the value.
///
/// Defaults to `.`.
@override
final String decimalSeparator;
/// See [TextField.enabled].
final bool enabled;
/// See [TextField.readOnly].
@override
final bool readOnly;
/// See [TextField.autofocus].
final bool autofocus;
/// See [TextField.keyboardType].
final TextInputType keyboardType;
/// See [TextField.textInputAction].
final TextInputAction? textInputAction;
/// See [TextField.decoration].
final InputDecoration? decoration;
/// See [FormField.validator].
final FormFieldValidator<String>? validator;
/// See [TextField.keyboardAppearance].
final Brightness? keyboardAppearance;
/// See [TextField.showCursor].
final bool? showCursor;
/// See [TextField.cursorColor].
final Color? cursorColor;
/// See [TextField.enableInteractiveSelection].
final bool enableInteractiveSelection;
/// See [TextField.textAlign].
final TextAlign textAlign;
/// See [TextField.textDirection].
final TextDirection textDirection;
/// See [TextField.style].
final TextStyle? textStyle;
/// See [TextField.contextMenuBuilder].
final EditableTextContextMenuBuilder? contextMenuBuilder;
/// See [TextField.onSubmitted].
///
/// Is also called when an increment or decrement button is pressed.
///
/// Value is formatted.
@override
final void Function(double)? onSubmitted;
@override
State<SpinBox> createState() => SpinBoxState();
}
class SpinBoxState extends State<SpinBox> with SpinBoxMixin {
Color? _iconColor(ThemeData theme, String? errorText) {
if (!widget.enabled) return theme.disabledColor;
if (hasFocus && errorText == null) return theme.colorScheme.primary;
switch (theme.brightness) {
case Brightness.dark:
return Colors.white70;
case Brightness.light:
return Colors.black45;
default:
return theme.iconTheme.color;
}
}
double _textHeight(String? text, TextStyle style) {
final painter = TextPainter(
textAlign: widget.textAlign,
textDirection: widget.textDirection,
text: TextSpan(style: style, text: text),
);
painter.layout();
return painter.height;
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final spinBoxTheme = SpinBoxTheme.of(context);
final decoration = (widget.decoration ??
spinBoxTheme?.decoration ??
const InputDecoration())
.applyDefaults(theme.inputDecorationTheme);
final errorText =
decoration.errorText ?? widget.validator?.call(controller.text);
final iconSize = widget.iconSize ?? spinBoxTheme?.iconSize ?? 24;
final iconColor = widget.iconColor ??
spinBoxTheme?.iconColor ??
MaterialStateProperty.all(_iconColor(theme, errorText));
final states = <MaterialState>{
if (!widget.enabled) MaterialState.disabled,
if (hasFocus) MaterialState.focused,
if (errorText != null) MaterialState.error,
};
final decrementStates = Set<MaterialState>.of(states);
if (value <= widget.min) decrementStates.add(MaterialState.disabled);
final incrementStates = Set<MaterialState>.of(states);
if (value >= widget.max) incrementStates.add(MaterialState.disabled);
var bottom = 0.0;
final isHorizontal = widget.direction == Axis.horizontal;
if (isHorizontal) {
final caption = theme.textTheme.bodySmall;
if (errorText != null) {
bottom = _textHeight(errorText, caption!.merge(decoration.errorStyle));
}
if (decoration.helperText != null) {
bottom = max(
bottom,
_textHeight(
decoration.helperText, caption!.merge(decoration.helperStyle)));
}
if (decoration.counterText != null) {
bottom = max(
bottom,
_textHeight(decoration.counterText,
caption!.merge(decoration.counterStyle)));
}
if (bottom > 0) bottom += 8.0; // subTextGap
}
final hasAnyBorder = decoration.border != null ||
decoration.errorBorder != null ||
decoration.enabledBorder != null ||
decoration.focusedBorder != null ||
decoration.disabledBorder != null ||
decoration.focusedErrorBorder != null;
Widget buildIcon(
Icon icon, {
Widget? prefix,
Widget? suffix,
}) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
if (suffix != null) suffix,
if (isHorizontal && widget.showButtons)
Padding(
padding: EdgeInsets.symmetric(horizontal: widget.spacing),
child: SizedBox(width: icon.size ?? iconSize, height: 0),
),
if (prefix != null) prefix,
],
);
}
final inputDecoration = decoration.copyWith(
border: !hasAnyBorder ? const OutlineInputBorder() : decoration.border,
errorText: errorText,
prefix: buildIcon(widget.decrementIcon, prefix: decoration.prefix),
suffix: buildIcon(widget.incrementIcon, suffix: decoration.suffix),
);
final textField = CallbackShortcuts(
bindings: bindings,
child: TextField(
controller: controller,
style: widget.textStyle,
textAlign: widget.textAlign,
textDirection: widget.textDirection,
keyboardType: widget.keyboardType,
textInputAction: widget.textInputAction,
contextMenuBuilder: widget.contextMenuBuilder,
keyboardAppearance: widget.keyboardAppearance,
inputFormatters: [formatter],
decoration: inputDecoration,
enableInteractiveSelection: widget.enableInteractiveSelection,
showCursor: widget.showCursor,
cursorColor: widget.cursorColor,
autofocus: widget.autofocus,
enabled: widget.enabled,
readOnly: widget.readOnly,
focusNode: focusNode,
onSubmitted: (v) {
final value = fixupValue(v);
widget.onSubmitted?.call(value);
},
),
);
final incrementButton = SpinButton(
step: widget.step,
color: iconColor.resolve(incrementStates),
icon: widget.incrementIcon,
iconSize: widget.incrementIcon.size ?? iconSize,
enabled: widget.enabled && value < widget.max,
interval: widget.interval,
acceleration: widget.acceleration,
onStep: (step) => setValue(value + step),
);
if (!widget.showButtons) return textField;
final decrementButton = SpinButton(
step: widget.step,
color: iconColor.resolve(decrementStates),
icon: widget.decrementIcon,
iconSize: widget.decrementIcon.size ?? iconSize,
enabled: widget.enabled && value > widget.min,
interval: widget.interval,
acceleration: widget.acceleration,
onStep: (step) => setValue(value - step),
);
if (isHorizontal) {
return Stack(
children: [
textField,
Positioned.fill(
bottom: bottom,
child: Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: widget.spacing),
child: decrementButton,
),
),
),
Positioned.fill(
bottom: bottom,
child: Align(
alignment: Alignment.centerRight,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: widget.spacing),
child: incrementButton,
),
),
)
],
);
} else {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
incrementButton,
SizedBox(height: widget.spacing),
textField,
SizedBox(height: widget.spacing),
decrementButton,
],
);
}
}
}