import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class SettingsNumberModal extends StatefulWidget { final String title; final int currentValue; final int minValue; final int maxValue; final ValueChanged onValueChanged; const SettingsNumberModal({ Key? key, required this.title, required this.currentValue, required this.minValue, required this.maxValue, required this.onValueChanged, }) : super(key: key); @override State createState() => _SettingsNumberModalState(); static Future show( BuildContext context, { required String title, required int currentValue, required int minValue, required int maxValue, required ValueChanged onValueChanged, }) { return showDialog( context: context, builder: (context) => SettingsNumberModal( title: title, currentValue: currentValue, minValue: minValue, maxValue: maxValue, onValueChanged: onValueChanged, ), ); } } class _SettingsNumberModalState extends State { late TextEditingController _controller; late int selectedValue; @override void initState() { super.initState(); selectedValue = widget.currentValue; _controller = TextEditingController(text: widget.currentValue.toString()); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AlertDialog( title: Text(widget.title), content: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( controller: _controller, keyboardType: TextInputType.number, decoration: InputDecoration( hintText: 'Enter a number', errorText: _validateInput(), ), inputFormatters: [FilteringTextInputFormatter.digitsOnly], onChanged: (value) { setState(() { selectedValue = int.tryParse(value) ?? widget.currentValue; }); }, ), ], ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('Cancel'), ), TextButton( onPressed: _validateInput() == null ? () { widget.onValueChanged(selectedValue); Navigator.of(context).pop(); } : null, child: const Text('OK'), ), ], ); } String? _validateInput() { final number = int.tryParse(_controller.text); if (number == null) { return 'Please enter a valid number'; } if (number < widget.minValue) { return 'Value must be at least ${widget.minValue}'; } if (number > widget.maxValue) { return 'Value must be at most ${widget.maxValue}'; } return null; } }