Home > Software design >  Flutter : Persist Data
Flutter : Persist Data

Time:11-02

I am building an online shop. I have a counter[-]0[ ] next to every product on the home page. I am able to add and remove products to the cart but when I switch to a different screen, my counter on the home page is reset back to 0. I would like to keep that data persistent. what would be the best way to achieve this?

cart_counter.dart

import 'package:flutter/material.dart';
import '../providers/cart.dart';
import 'package:provider/provider.dart';
import '../providers/products.dart';

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

  @override
  _CartCounterState createState() => _CartCounterState();
}

class _CartCounterState extends State<CartCounter> {
  int numOfItems = 0;
  @override
  Widget build(BuildContext context) {
    final product = Provider.of<Product>(context, listen: false);
    final cart = Provider.of<Cart>(context, listen: false);
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CounterButton(
          icon: Icons.remove,
          onPress: () {
            if (numOfItems > 0) {
              setState(() {
                numOfItems--;
              });
              cart.removeSingleItem(product.id);
            }
          },
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 13.0),
          child: Text(
            numOfItems.toString(),
            style: const TextStyle(
              fontSize: 20.0,
            ),
          ),
        ),
        CounterButton(
          icon: Icons.add,
          onPress: () {
            setState(() {
              numOfItems  ;

              cart.addItem(
                product.id,
                product.price,
                product.title,
              );
            });
          },
        ),
      ],
    );
  }
}

class CounterButton extends StatelessWidget {
  final IconData icon;
  final void Function() onPress;

  const CounterButton({
    Key? key,
    required this.icon,
    required this.onPress,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 60.0,
      height: 45.0,
      child: OutlinedButton(
        style: OutlinedButton.styleFrom(
          elevation: 2,
          backgroundColor: Theme.of(context).primaryColor,
          primary: Theme.of(context).primaryColor,
          padding: EdgeInsets.zero,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
        ),
        onPressed: onPress,
        child: Icon(
          icon,
          color: Colors.white,
          size: 30.0,
        ),
      ),
    );
  }
}

product_item.dart

import 'package:flutter/material.dart';
import 'cart_counter.dart';

class ProductItem extends StatelessWidget {
  final String id;
  final String title;
  final double price;
  final String image;

  const ProductItem(this.id, this.title, this.price, this.image, {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
      child: Card(
        elevation: 2.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.0),
        ),
        child: Column(
          children: [
            Row(
              children: [
                Container(
                  height: 50,
                  width: 70.0,
                  decoration: BoxDecoration(
                    borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(20.0),
                      bottomRight: Radius.circular(20.0),
                    ),
                    color: Theme.of(context).primaryColor,
                  ),
                  child: Center(
                    child: Text(
                      title,
                      style: const TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16.0,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Image.asset(image),
            const SizedBox(
              height: 10.0,
            ),
            Text(
              price.toStringAsFixed(2),
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 20.0,
              ),
            ),
            const SizedBox(
              height: 10.0,
            ),
            const CartCounter(),
            const SizedBox(
              height: 20.0,
            ),
          ],
        ),
      ),
    );
  }
}

CodePudding user response:

Use Shared Preferences or Secure Storage to store the values.

See this answer to a similar question.

CodePudding user response:

  1. Make a variable static(global) which you want to use on another screen.

  2. Make a class for saving variables and make it global.

Hope you get some hints.

  • Related