|
| 1 | +import 'package:flutter/material.dart'; |
| 2 | +import 'package:flutter_hooks/flutter_hooks.dart'; |
| 3 | + |
| 4 | +class NumberPad extends HookWidget { |
| 5 | + final Function(String) onKeyPressed; |
| 6 | + |
| 7 | + const NumberPad({required this.onKeyPressed, super.key}); |
| 8 | + |
| 9 | + @override |
| 10 | + Widget build(BuildContext context) { |
| 11 | + final pressedKey = useState<String>(''); |
| 12 | + |
| 13 | + return Container( |
| 14 | + padding: const EdgeInsets.all(16.0), |
| 15 | + child: Column( |
| 16 | + mainAxisAlignment: MainAxisAlignment.center, |
| 17 | + children: [ |
| 18 | + _buildRow(context, ['1', '2', '3'], pressedKey), |
| 19 | + _buildRow(context, ['4', '5', '6'], pressedKey), |
| 20 | + _buildRow(context, ['7', '8', '9'], pressedKey), |
| 21 | + _buildRow(context, ['.', '0', '<'], pressedKey), |
| 22 | + ], |
| 23 | + ), |
| 24 | + ); |
| 25 | + } |
| 26 | + |
| 27 | + Widget _buildRow( |
| 28 | + BuildContext context, |
| 29 | + List<String> keys, |
| 30 | + ValueNotifier<String> pressedKey, |
| 31 | + ) { |
| 32 | + return Row( |
| 33 | + mainAxisAlignment: MainAxisAlignment.center, |
| 34 | + children: keys.map((key) { |
| 35 | + return _buildKeyButton(context, key, pressedKey); |
| 36 | + }).toList(), |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + Widget _buildKeyButton( |
| 41 | + BuildContext context, |
| 42 | + String key, |
| 43 | + ValueNotifier<String> pressedKey, |
| 44 | + ) { |
| 45 | + return Expanded( |
| 46 | + child: Container( |
| 47 | + margin: const EdgeInsets.all(8.0), |
| 48 | + child: Center( |
| 49 | + child: FilledButton( |
| 50 | + onPressed: () { |
| 51 | + _handleKeyPress(pressedKey, key); |
| 52 | + }, |
| 53 | + style: FilledButton.styleFrom( |
| 54 | + backgroundColor: Theme.of(context).colorScheme.background, |
| 55 | + ), |
| 56 | + child: key.isNotEmpty |
| 57 | + ? Text( |
| 58 | + key, |
| 59 | + style: Theme.of(context).textTheme.displayMedium?.copyWith( |
| 60 | + fontWeight: FontWeight.bold, |
| 61 | + fontSize: pressedKey.value == key ? 34.0 : 20.0, |
| 62 | + ), |
| 63 | + ) |
| 64 | + : const Spacer(), |
| 65 | + ), |
| 66 | + ), |
| 67 | + ), |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + void _handleKeyPress(ValueNotifier<String> pressedKey, String key) { |
| 72 | + pressedKey.value = key; |
| 73 | + onKeyPressed(key); |
| 74 | + |
| 75 | + Future.delayed(const Duration(milliseconds: 100), () { |
| 76 | + pressedKey.value = ''; |
| 77 | + }); |
| 78 | + } |
| 79 | +} |
0 commit comments