-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
item_quantity_dialog.dart
87 lines (77 loc) · 2.6 KB
/
item_quantity_dialog.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
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:genshindb/application/bloc.dart';
import 'package:genshindb/generated/l10n.dart';
class ItemQuantityDialog extends StatefulWidget {
final int quantity;
final int quantityLength;
const ItemQuantityDialog({
Key? key,
required this.quantity,
this.quantityLength = 10,
}) : super(key: key);
@override
_ItemQuantityDialogState createState() => _ItemQuantityDialogState();
}
class _ItemQuantityDialogState extends State<ItemQuantityDialog> {
late TextEditingController _textEditingController;
late String _currentValue;
@override
void initState() {
_currentValue = '${widget.quantity}';
_textEditingController = TextEditingController(text: _currentValue);
_textEditingController.addListener(_textChanged);
super.initState();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final s = S.of(context);
return AlertDialog(
title: Text(s.quantity),
content: BlocBuilder<ItemQuantityFormBloc, ItemQuantityFormState>(
builder: (ctx, state) => TextField(
maxLength: widget.quantityLength,
controller: _textEditingController,
autofocus: true,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: '0',
alignLabelWithHint: true,
labelText: s.quantity,
errorText: !state.isQuantityValid ? s.invalidValue : null,
),
),
),
actions: [
OutlinedButton(
onPressed: _close,
child: Text(s.cancel, style: TextStyle(color: theme.primaryColor)),
),
BlocBuilder<ItemQuantityFormBloc, ItemQuantityFormState>(
builder: (ctx, state) => ElevatedButton(
onPressed: state.isQuantityValid ? _onSave : null,
child: Text(s.save),
),
)
],
);
}
@override
void dispose() {
_textEditingController.removeListener(_textChanged);
_textEditingController.dispose();
super.dispose();
}
void _textChanged() {
//Focusing the text field triggers text changed, that why we used it like this
if (_currentValue == _textEditingController.text) {
return;
}
_currentValue = _textEditingController.text;
final quantity = int.tryParse(_currentValue) ?? -1;
context.read<ItemQuantityFormBloc>().add(ItemQuantityFormEvent.quantityChanged(quantity: quantity));
}
void _onSave() => Navigator.pop(context, int.parse(_currentValue));
void _close() => Navigator.pop(context);
}