Home > Blockchain >  [Flutter][Dart] Why do I get error of undefined name "index" after defining under void(sav
[Flutter][Dart] Why do I get error of undefined name "index" after defining under void(sav

Time:09-04

This project is a shopping app and the function I am trying to achieve with the following code is the add to cart function. I got an "Undefined Name" error for integer "index" despite defining it in the void(saveData). I'm very new to coding so I'm thinking there might be something I've overlooked.

The error is the highlighted line in this image here: [highlighted line of undefined name error][1]

The line of code where I defined "index" is in the following image: [defining "index" in void][2]

The full code for this dart file is as follows:

import 'package:provider/provider.dart';
import 'package:MyShoppingApp/provider/CartProvider.dart';
import 'package:MyShoppingApp/db/cart_database.dart';
import 'package:MyShoppingApp/model/cart.dart';
import 'model/products_repository.dart';


class ProductDetailsPage extends StatelessWidget {
  static const routeName = '/user-products';
   ProductDetailsPage({Key? key}) : super(key: key); //const
  DBHelper dbHelper = DBHelper();

  @override
  Widget build(BuildContext context) {
    //get particular productId using the ModalRoute class
    final productId = ModalRoute.of(context)!.settings.arguments as String;
    print(productId);
    //use Provider package to find out ID by accessing method declared in Product()
    final loadedProduct = ProductsRepository().findById(productId);
  
    //List<bool> clicked = List.generate(10, (index) => false, growable: true);
      final cart = Provider.of<CartProvider>(context);
      void saveData(int index) {
        dbHelper
            .insert(
          CartItem(
            id: index,
            title: loadedProduct.name,
            price: loadedProduct.price.toDouble(),
            quantity: ValueNotifier(1),
            image: loadedProduct.image,
          ),
        )
            .then((value) {
          cart.addTotalPrice(loadedProduct.price.toDouble());
          cart.addCounter();
          print('Product Added to cart');
        }).onError((error, stackTrace) {
          print(error.toString());
        });
      }

    return Scaffold(
      backgroundColor: Colors.orange[50],
      appBar: AppBar(
        backgroundColor: Colors.deepOrange[900],
        title: const Text("Product details "),
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back_ios_outlined,
            color: Colors.black,
            semanticLabel: 'back to home',
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
        body:
        SingleChildScrollView(
          child: Column(
            children: <Widget>[
               SizedBox(
                 height: 300,
                 width: double.infinity,
                 child: Image.network(
                   loadedProduct.image,
                   fit: BoxFit.cover,
                 ),
               ),
              const SizedBox(height: 10),
              Text(
                '\$${loadedProduct.price}',
                style: const TextStyle(
                  color: Colors.grey,
                  fontSize: 20,
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      primary: Colors.blueGrey.shade900),
                  onPressed: () {
                    saveData(index);
                  },
                  child: const Text('Add to Cart')),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                width: double.infinity,
                child: Text(
                  loadedProduct.description,
                  textAlign: TextAlign.center,
                  softWrap: true,
                ),
              ),
            ],
          ),
        ),
    );
  }
}

Any form of help would be so greatly appreciated, I have been struggling with this error for very long. Thank you!

Edit: CartProvider dart file code:

import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import '../model/cart.dart';
import 'package:MyShoppingApp/db/cart_database.dart';

class CartProvider with ChangeNotifier {
  DBHelper dbHelper = DBHelper();
  int _counter = 0;
  int _quantity = 1;
  int get counter => _counter;
  int get quantity => _quantity;

  double _totalPrice = 0.0;
  double get totalPrice => _totalPrice;

  List<CartItem> cart = [];

  Future<List<CartItem>> getData() async {
    cart = await dbHelper.getCartList();
    notifyListeners();
    return cart;
  }

  void _setPrefsItems() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt('cart_items', _counter);
    prefs.setInt('item_quantity', _quantity);
    prefs.setDouble('total_price', _totalPrice);
    notifyListeners();
  }

  void _getPrefsItems() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _counter = prefs.getInt('cart_items') ?? 0;
    _quantity = prefs.getInt('item_quantity') ?? 1;
    _totalPrice = prefs.getDouble('total_price') ?? 0;
  }

  void addCounter() {
    _counter  ;
    _setPrefsItems();
    notifyListeners();
  }

  void removeCounter() {
    _counter--;
    _setPrefsItems();
    notifyListeners();
  }

  int getCounter() {
    _getPrefsItems();
    return _counter;
  }

  void addQuantity(int id) {
    final index = cart.indexWhere((element) => element.id == id);
    cart[index].quantity!.value = cart[index].quantity!.value   1;
    _setPrefsItems();
    notifyListeners();
  }

  void deleteQuantity(int id) {
    final index = cart.indexWhere((element) => element.id == id);
    final currentQuantity = cart[index].quantity!.value;
    if (currentQuantity <= 1) {
      currentQuantity == 1;
    } else {
      cart[index].quantity!.value = currentQuantity - 1;
    }
    _setPrefsItems();
    notifyListeners();
  }

  void removeItem(int id) {
    final index = cart.indexWhere((element) => element.id == id);
    cart.removeAt(index);
    _setPrefsItems();
    notifyListeners();
  }

  int getQuantity(int quantity) {
    _getPrefsItems();
    return _quantity;
  }

  void addTotalPrice(double productPrice) {
    _totalPrice = _totalPrice   productPrice;
    _setPrefsItems();
    notifyListeners();
  }

  void removeTotalPrice(double productPrice) {
    _totalPrice = _totalPrice - productPrice;
    _setPrefsItems();
    notifyListeners();
  }

  double getTotalPrice() {
    _getPrefsItems();
    return _totalPrice;
  }
}```

  [1]: https://i.stack.imgur.com/V8OGs.png
  [2]: https://i.stack.imgur.com/JYE10.png

CodePudding user response:

The body is returning a ListView.builder, and index can be get from there,

    body: ListView.builder(
          padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
          shrinkWrap: true,
          itemCount: products.length,
          itemBuilder: (context, index) {
            return Card(

The original code can be found here

CodePudding user response:

You don't have any list to represent that index so, in your ElevatedButton instead of using index could use an other number. so there is a workaround for that and that is use random number for that.

ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      primary: Colors.blueGrey.shade900),
                  onPressed: () {
                    saveData(Random().nextInt(1000));
                  },
                  child: const Text('Add to Cart')),
  • Related