【发布时间】:2021-08-22 21:50:59
【问题描述】:
我想从我自己的其他班级初始化_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;
}
}
这是我其他类的部分代码,它必须通过单击来初始化_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,
),
),
【问题讨论】:
-
在 getinstance 方法中你没有初始化它。考虑 _instance 不为空的情况。它将返回从未初始化的_instance。
-
@Benyamin 差不多。
getInstance方法检查if (_instance == null),它在初始化之前尝试访问_instance,这将立即触发LateInitializationError。同时检查_instance以获取null并使其成为late是没有意义的。只要让它可以为空。
标签: android flutter android-studio dart initialization