Home > database >  Create a dynamic "Add to car" with "quantity" Button
Create a dynamic "Add to car" with "quantity" Button

Time:06-04

I would like to create a dynamic button for my Flutter-Dart e-commerce App, the style needs to be like this:

When the item is added, you can choose the quantity, but when the quantity is back to 0, the "Add Item" button will appear again with a fade effect.

First Example

Second Example

CodePudding user response:

Here is a simple example how I would create this behavior.

You can test this code yourself on DartPad

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  int quantity = 0;

  @override
  Widget build(BuildContext context) {
    return Card(
        color: Colors.blue,
        child: SizedBox(
          height: 50,
          width: 100,
          child: quantity == 0
              ? TextButton(
                  child: const Text(
                    'Add Item',
                    style: TextStyle(
                      color: Colors.white,
                    ),
                  ),
                  onPressed: () {
                    setState(() {
                      quantity  ;
                    });
                  },
                )
              : Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IconButton(
                      icon: const Icon(Icons.remove),
                      onPressed: () {
                        setState(() {
                          quantity--;
                        });
                      },
                    ),
                    Text(quantity.toString()),
                    IconButton(
                      icon: const Icon(Icons.add),
                      onPressed: () {
                        setState(() {
                          quantity  ;
                        });
                      },
                    ),
                  ],
                ),
        ));
  }
}
  • Related