错误状态:试图读取在创建其值期间抛出的提供程序。颤振提供者

时间:2021-07-26 02:45:38

标签: flutter flutter-provider

昨天工作正常,现在我收到了标题中提到的这个错误。我已经搜索了与此问题相关的 SO,但找不到任何解决我的问题的方法。以下是我认为可能存在错误的必要代码。

我的提供者文件:

class StrategyOneProvider with ChangeNotifier {
  ChartLiveData _chartLiveData = {} as ChartLiveData; // 1
  ChartLiveData get chartLiveData => _chartLiveData; // 2

  Future<void> fetchLiveStockData(ref) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return ref.once().then((DataSnapshot data) {
      final cleanup = jsonDecode(jsonEncode(data.value));
      _chartLiveData = ChartLiveData.fromJson(cleanup['SBIN_Live']);
      notifyListeners();
    });
  }

当我注释掉“1”和“2”时,它起作用了。 (但那也没用)

我的模型类:ChartLiveData

class ChartLiveData {
  String? currDate;
  double? openPrice;
  double? dayHigh;
  double? dayLow;
  double? lastPrice;
  double? ttv;

  ChartLiveData(
      {required this.currDate,
      required this.openPrice,
      required this.dayHigh,
      required this.dayLow,
      required this.lastPrice,
      required this.ttv});

  ChartLiveData.fromJson(Map<String, dynamic> json) {
    currDate = json['currDate'];
    openPrice = json['openPrice'];
    dayHigh = json['dayHigh'];
    dayLow = json['dayLow'];
    lastPrice = json['lastPrice'];
    ttv = json['ttv'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['currDate'] = this.currDate;
    data['openPrice'] = this.openPrice;
    data['dayHigh'] = this.dayHigh;
    data['dayLow'] = this.dayLow;
    data['lastPrice'] = this.lastPrice;
    data['ttv'] = this.ttv;
    return data;
  }
}

这是我点击导航到 StrategyOneScreen 的轮播卡片时遇到的第一个错误:

The following _CastError was thrown building StrategyOneScreen(dirty, dependencies: [_InheritedProviderScope<StrategyOneProvider>], state: _StrategyOneScreenState#a2894):
type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'ChartLiveData' in type cast

The relevant error-causing widget was
StrategyOneScreen
lib\widgets\carousels.dart:25
When the exception was thrown, this was the stack
#0      new StrategyOneProvider
package:algoguru/providers/strategy1_provider.dart:10
#1      main.<anonymous closure>
package:algoguru/main.dart:17
#2      _CreateInheritedProviderState.value
package:provider/src/inherited_provider.dart:687
#3      _InheritedProviderScopeElement.value
package:provider/src/inherited_provider.dart:544
#4      Provider.of
package:provider/src/provider.dart:289
...

这是我在第一个错误之后点击 ctrl+s 时的第二个错误:

Bad state: Tried to read a provider that threw during the creation of its value.
The exception occurred during the creation of type StrategyOneProvider.
The relevant error-causing widget was
StrategyOneScreen
lib\widgets\carousels.dart:25

我认为,原因的根源在于提供者文件中的这一行:ChartLiveData _chartLiveData = {} as ChartLiveData;,因为没有它,一切正常。

如果有人能指出我做错了什么,我将不胜感激。

0 个答案:

没有答案