【问题标题】:Why private variable doesn't initialize in dart?为什么私有变量不在飞镖中初始化?
【发布时间】: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


【解决方案1】:

你试过这样吗?

static ShoppingBasketData? _instance;

【讨论】:

  • 我之前尝试过,但没有成功,但这次成功了,我很感激。
  • 如果有帮助,欢迎您接受答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多