[英]Why private variable doesn't initialize in dart?
我想从其他我自己的 class 初始化_instance
但是当我运行它时它说LateInitializationError: Field '_instance@26074107' has not been initialized.
这是我的代码:
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;
}
}
这是我的另一个 class 的部分代码,它必须通过单击来初始化_Instance
,但它不会:
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,
),
),
你试过吗?
static ShoppingBasketData? _instance;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.