skip to Main Content

I am given task for creating counter widget which has two iconbutton for increment and decrement value..

increment by 1 and decrement by -1, no variation..its fix..

I have created design but dont know how to implement it with – and + functionality

can anyone suggest me how to solve it


class _HomeScreenState extends State<HomeScreen> {
  int age=30;
  int weight=39;
  int score=100;

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: Column(children: [
        const SizedBox(height: 100,),
        CartCounter(value: age,),
        const SizedBox(height: 100,),
        CartCounter(value: weight,),
        const SizedBox(height: 100,),
        CartCounter(value: score,),
      ],),
    );
  }
}


here is my effort but dont know how to implement increment coding and decrement coding


class CartCounter extends StatefulWidget {
  final int value;

  const CartCounter({Key? key,required this.value}) : super(key: key);

  @override
  State<CartCounter> createState() => _CartCounterState();
}

class _CartCounterState extends State<CartCounter> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      width: 200,
      decoration: BoxDecoration(

          borderRadius: BorderRadius.circular(20)
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
        IconButton(
            color: Colors.blue,
            onPressed: (){


            }, icon: Icon(Icons.remove)),
        SizedBox(width: 60,child: Center(child: Text(widget.value.toString(),style: Theme.of(context).textTheme.headlineSmall,)),),
        IconButton(
            color: Colors.blue,
            onPressed: (){}, icon: Icon(Icons.add)),

      ],),
    );
  }
}


3

Answers


  1. If I correctly understood your question, you want to implement the onPressed-Method in the IconButtons.

    Here is my updated code:

    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        IconButton(
          color: Colors.blue,
          onPressed: () {
            setState(() {
              if (widget.value > 0) {
                widget.value--;
              }
            });
          },
          icon: Icon(Icons.remove),
        ),
        SizedBox(
          width: 60,
          child: Center(
            child: Text(
              widget.value.toString(),
              style: Theme.of(context).textTheme.headlineSmall,
            ),
          ),
        ),
        IconButton(
          color: Colors.blue,
          onPressed: () {
            setState(() {
              widget.value++;
            });
          },
          icon: Icon(Icons.add),
        ),
      ],
    ),
    

    I hope I helped you 😉

    Login or Signup to reply.
  2. here is the solution…try..it will work

    u just missing to add a Function in ur custom widget and returning value to calling class

    add this Function to your custom widget and this widget should be stateful widget
    final Function(int) onChange;

    I have used a local variable named result and do increment and decrement it while tapping on iconbutton..

    import 'package:flutter/material.dart';
    
    class CartCounter extends StatefulWidget {
      final int value;
      final Function(int) onChange;
      const CartCounter({Key? key,required this.value,required this.onChange}) : super(key: key);
    
      @override
      State<CartCounter> createState() => _CartCounterState();
    }
    
    class _CartCounterState extends State<CartCounter> {
    late int result;
    
    
    @override
      void initState() {
        // TODO: implement initState
        super.initState();
        result=widget.value;
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          height: 80,
          width: 200,
          decoration: BoxDecoration(
    
              borderRadius: BorderRadius.circular(20)
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
            IconButton(
                color: Colors.blue,
                onPressed: (){
                  setState(() {
                    result--;
                    widget.onChange(result); // for returning value
                  });
    
    
                }, icon: Icon(Icons.remove)),
            SizedBox(width: 60,child: Center(child: Text(result.toString(),style: Theme.of(context).textTheme.headlineSmall,)),),
            IconButton(
                color: Colors.blue,
                onPressed: (){
                  setState(() {
                    result++;
                    widget.onChange(result);// for return value 
                  });
                }, icon: Icon(Icons.add)),
    
          ],),
        );
      }
    }
    
    
    
    Login or Signup to reply.
  3. Here, I have give the code: 
    
    Create a new CartCounter class that extends StatefulWidget. This is because we need to keep track of the count.
    
    import 'package:flutter/material.dart';
    
    class CartCounter extends StatefulWidget {
      final int initialValue;
      final VoidCallback onPressed;
    
      CartCounter({required this.initialValue, required this.onPressed});
    
      @override
      _CartCounterState createState() => _CartCounterState();
    }
    
    class _CartCounterState extends State<CartCounter> {
      int count = 0;
    
      @override
      void initState() {
        super.initState();
        count = widget.initialValue;
      }
    
      @override
      Widget build(BuildContext context) {
        return Row(
          children: [
            buildOutlineButton(Icons.remove, () {
              if (count > 0) {
                count--;
                widget.onPressed();
              }
            }),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Text(
                count.toString(),
                style: TextStyle(fontSize: 20),
              ),
            ),
            buildOutlineButton(Icons.add, widget.onPressed),
          ],
        );
      }
    
      OutlinedButton buildOutlineButton(IconData icon, Function onPressed) {
        return OutlinedButton(
          onPressed: onPressed as void Function()?,
          style: OutlinedButton.styleFrom(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            padding: EdgeInsets.zero,
          ),
          child: Icon(icon),
        );
      }
    }
    
    Now use like this as a reusable widget:
    
    CartCounter(
      initialValue: 0,
      onPressed: () {},
    ),
    
    Hope you found the answer.....
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search