num_counter.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import 'package:flutter/material.dart';
  2. import 'package:twong/utils/index.dart';
  3. import 'package:twong/config/style.dart';
  4. class NumCounter extends StatefulWidget {
  5. int num;
  6. final int max;
  7. final int min;
  8. final Color color;
  9. final Color btnColor;
  10. final Function(int) onChange;
  11. NumCounter({this.num = 0, this.max = 99, this.min = 1, this.onChange,
  12. this.color, this.btnColor });
  13. @override
  14. State<StatefulWidget> createState() {
  15. return _NumCounterState();
  16. }
  17. }
  18. class _NumCounterState extends State<NumCounter> {
  19. @override
  20. void initState() {
  21. super.initState();
  22. if (widget.num > widget.max) {
  23. setState(() {
  24. widget.num = widget.max;
  25. });
  26. }
  27. }
  28. @override
  29. Widget build(BuildContext context) {
  30. return Container(
  31. child: Row(
  32. children: [
  33. _buildCountBtn(false),
  34. Container(
  35. width: 44.px,
  36. height: 26.px,
  37. margin: EdgeInsets.all(6.px),
  38. padding: EdgeInsets.only(top: 3.px),
  39. decoration: BoxDecoration(
  40. borderRadius: BorderRadius.circular(6.px),
  41. color: widget.color == null ? Color.fromARGB(255, 228, 228, 228) : widget.color,
  42. ),
  43. child: Text("${widget.num}", style: TextStyle(fontSize: 15.px),
  44. textAlign: TextAlign.center),
  45. ),
  46. _buildCountBtn(true),
  47. ],
  48. ),
  49. );
  50. }
  51. Widget _buildCountBtn(bool add) {
  52. return InkWell(
  53. onTap: () {
  54. if (add) {
  55. setState(() {
  56. if (widget.num >= widget.max) return;
  57. widget.num ++;
  58. });
  59. } else {
  60. if (widget.num <= widget.min) return;
  61. setState(() {
  62. widget.num --;
  63. });
  64. }
  65. if(widget.onChange != null) {
  66. widget.onChange(widget.num);
  67. }
  68. },
  69. child: Container(
  70. width: 26.px,
  71. height: 26.px,
  72. decoration: BoxDecoration(
  73. borderRadius: BorderRadius.circular(6.px),
  74. color: widget.btnColor == null ? DColors.back : widget.btnColor,
  75. ),
  76. child: Text(add? "+" : "-", style: TextStyle(fontSize: 18.px), textAlign: TextAlign.center),
  77. ),
  78. );
  79. }
  80. }