import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class NumberStepper extends StatefulWidget { final ValueChanged onValueChanged; final double defaultValue; final double maxValue; final double minValue; NumberStepper({ required this.onValueChanged, required this.defaultValue, double? maxValue, // 设置 maxValue 的默认值 double? minValue, // minValue 现在是可选 }) : maxValue = maxValue ?? 9999.0, minValue = minValue ?? 0.0; // 没有传入时默认 0.0 @override _NumberStepperState createState() => _NumberStepperState(); } class _NumberStepperState extends State { var _currentValue = 0.0; @override void initState() { super.initState(); _currentValue = widget.defaultValue; } void _increment() { setState(() { _currentValue++; widget.onValueChanged(_currentValue); }); } void _decrement() { setState(() { if (_currentValue > 0) { _currentValue--; widget.onValueChanged(_currentValue); } }); } @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ CustomIconButton( icon: Icons.remove, onPressed: _currentValue > widget.minValue ? _decrement : null, // 禁用按钮 color: _currentValue > widget.minValue ? Colors.blue : Colors.grey, ), Container( margin: EdgeInsets.symmetric(horizontal: 4), constraints: BoxConstraints(maxWidth: 50, maxHeight: 40, minWidth: 20), decoration: BoxDecoration(), child: Center( child: Container( child: TextField( textAlign: TextAlign.center, style: TextStyle(fontSize: 12), keyboardType: TextInputType.number, controller: TextEditingController(text: _currentValue.toString()), onSubmitted: (value) { setState(() { _currentValue = _currentValue; }); }, decoration: InputDecoration( isCollapsed: true, border: InputBorder.none, contentPadding: EdgeInsets.symmetric( vertical: 0, horizontal: 2), // 添加padding ), ), ), )), CustomIconButton( icon: Icons.add, onPressed: _currentValue < widget.maxValue ? _increment : null, // 禁用按钮 color: _currentValue < widget.maxValue ? Colors.blue : Colors.grey, ), ], ); } } Widget CustomIconButton({ Function()? onPressed, IconData? icon, Color? color, }) { return Container( decoration: BoxDecoration( color: color, borderRadius: BorderRadius.circular(12), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.3), spreadRadius: 2, blurRadius: 5, offset: Offset(0, 3), ), ], ), child: Material( color: Colors.transparent, child: InkWell( onTap: onPressed, highlightColor: Colors.white10, child: Padding( padding: const EdgeInsets.all(0.0), child: Icon( icon, color: Colors.white, ), )), )); }