为什么私有变量不在飞镖中初始化?
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;
我想从我自己的 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;