my_cart_num.dart 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import 'package:cs_resources/theme/app_colors_theme.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:widgets/my_text_view.dart';
  4. class MyCartNum extends StatefulWidget {
  5. final int initialNum;
  6. final ValueChanged<int> onChange; // 添加回调函数
  7. MyCartNum({Key? key, this.initialNum = 1, required this.onChange}) : super(key: key);
  8. @override
  9. _MyCartNumState createState() => _MyCartNumState();
  10. }
  11. class _MyCartNumState extends State<MyCartNum> {
  12. late int _num;
  13. @override
  14. void initState() {
  15. super.initState();
  16. _num = widget.initialNum;
  17. }
  18. void _incrementNum() {
  19. setState(() {
  20. _num++;
  21. widget.onChange(_num); // 调用回调函数
  22. });
  23. }
  24. void _decrementNum() {
  25. setState(() {
  26. if (_num >= 1) {
  27. _num--;
  28. widget.onChange(_num); // 调用回调函数
  29. }
  30. });
  31. }
  32. @override
  33. Widget build(BuildContext context) {
  34. return Row(
  35. mainAxisAlignment: MainAxisAlignment.start,
  36. crossAxisAlignment: CrossAxisAlignment.center,
  37. mainAxisSize: MainAxisSize.min,
  38. children: [
  39. RawMaterialButton(
  40. constraints: const BoxConstraints.tightFor(
  41. width: 27.5,
  42. height: 27.5,
  43. ),
  44. elevation: 1,
  45. shape: CircleBorder(
  46. side: BorderSide(width: 1.0, color: context.appColors.textPrimary),
  47. ),
  48. fillColor: context.appColors.textPrimary,
  49. splashColor: context.appColors.textPrimary,
  50. textStyle: TextStyle(color: Colors.white),
  51. onPressed: _decrementNum,
  52. child: const Icon(Icons.remove),
  53. ),
  54. MyTextView(
  55. '$_num',
  56. fontSize: 15,
  57. isFontRegular: true,
  58. textAlign: TextAlign.center,
  59. boxWidth: 30,
  60. ),
  61. RawMaterialButton(
  62. constraints: const BoxConstraints.tightFor(
  63. width: 27.5,
  64. height: 27.5,
  65. ),
  66. elevation: 1,
  67. shape: CircleBorder(
  68. side: BorderSide(width: 1.0, color: context.appColors.textPrimary),
  69. ),
  70. fillColor: context.appColors.textPrimary,
  71. splashColor: context.appColors.textPrimary,
  72. textStyle: TextStyle(color: Colors.white),
  73. onPressed: _incrementNum,
  74. child: const Icon(Icons.add),
  75. ),
  76. ],
  77. );
  78. }
  79. }