简体   繁体   中英

Why private variable doesn't initialize in dart?

I want initialize the _instance from other my own class but when i run it says LateInitializationError: Field '_instance@26074107' has not been initialized.

here's my code:

import 'package:firstpage/Product.dart';

class ShoppingBasketData {
  static late ShoppingBasketData _instance;
  late List<Product> _basketItems;

  ShoppingBasketData() {
    _basketItems = <Product>[];
  }

  List<Product> get basketItems => _basketItems;

  set basketItems(List<Product> value) {
    _basketItems = value;
  }

  static ShoppingBasketData getInstance() {
    if (_instance == null) {
      _instance = ShoppingBasketData();
    }
    return _instance;
  }
}

and here's part of code of my other class which is has to initializes the _Instance by clicking but it doesn't:

body:
Expanded(
            child: Align(
              child: Padding(
                padding: EdgeInsets.only(bottom: 20),
                child: GestureDetector(
                  onTap: () {
                    print("added to basket${_product.productName}");
                    ShoppingBasketData.getInstance().basketItems.add(_product);
                    print(ShoppingBasketData.getInstance().basketItems.length);
                  },
                  child: Container(
                    decoration: BoxDecoration(
                        color: Colors.red[600],
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: Center(
                      child: Text(
                        "add to basket",
                        style: TextStyle(
                            fontFamily: "Vazir",
                            fontSize: 18,
                            color: Colors.white),
                      ),
                    ),
                    width: MediaQuery.of(context).size.width - 50,
                    height: 70,
                  ),
                ),
              ),
              alignment: Alignment.bottomCenter,
            ),
          ),

did you tried like that?

static ShoppingBasketData? _instance;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM