[英]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.