Flutter Hive -将数据从Box复制到List时引发溢出错误

2vuwiymt  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(162)

我正在尝试将数据从Box(具有TypeAdapter)复制到List。出现堆栈溢出错误。

代码

List<CardFields> starterlist = refilldb("starter");
List<CardFields> tlist = [];
List<CardFields> refilldb(String db) {
  if (db == "starter") {
    starterlist.clear();
    Box starterbox = Hive.box<CardFields>("starter");
    List<CardFields> tlist = starterbox.values.toList() as List<CardFields>;
    return tlist;
  }

错误

======== Exception caught by gesture ===============================================================
The following StackOverflowError was thrown while handling a gesture:
Stack Overflow

When the exception was thrown, this was the stack: 
#0      starterlist (package:partaykaratay/models/database_mechanics.dart:66:18)
#1      starterlist (package:partaykaratay/models/database_mechanics.dart)
#2      refilldb (package:partaykaratay/models/database_mechanics.dart:76:5)
...
...
#14423  refilldb (package:partaykaratay/models/database_mechanics.dart:76:5)
#14424  starterlist (package:partaykaratay/models/database_mechanics.dart:66:32)
#14425  starterlist (package:partaykaratay/models/database_mechanics.dart)
#14426  _GameCatsState.build.<anonymous closure> (package:partaykaratay/pages/game_cats.dart:50:27)

包含该代码的文件是database_mechanics. dart。当我尝试访问列表-print(starterlist);时,抛出了该错误

mftmpeh8

mftmpeh81#

这是因为您试图通过List调用一个方法,而List依赖于它首先返回的函数:

List<CardFields> starterlist = refilldb("starter"); // here you called the function to get the starterList

refilldb方法中:

List<CardFields> refilldb(String db) {
    /*...*/
    starterlist.clear(); // here you tried to clear that starterList that on the first place depends on the refilldb()

所以就像你写的:

List<CardFields> starterlist = refilldb("starter");
/*...*/
List<CardFields> refilldb(String db) {
  if (db == "starter") {
    refilldb("starter").clear();
/*...*/

这是一个递归函数,它没有退出的条件,所以它就像一个无限循环,这导致了StackOverflow错误。
我知道这个答案很晚了,但我希望它是有帮助的。

相关问题