Flutter StreamProvider 'List<dynamic>' 不是类型转换中类型 'List<??>' 的子类型

Flutter StreamProvider 'List<dynamic>' is not a subtype of type 'List<??>' in type cast

我正在尝试使用 StreamProvider 使来自 firestore 文档流的数据在我的整个应用程序中可用。这是一个食谱应用程序,这是购物清单。

我有一个模型 RecipeItem,其中包含有关食谱中的项目的详细信息。 firestore 文档包含一个数组值,称为 'list',其中包含列表中每个项目的映射。

下面是我与 firestore 的连接和设置流。我尝试获取文档,然后使用用户映射为列表中的每个项目创建一个 RecipeItem 实例。方法如下:

Stream<List<RecipeItem>> getPersonalList() {
    print('Fetching personal list');

    return _db.collection('shopping_lists').document(userId).snapshots().map(
          (DocumentSnapshot documentSnapshot) => documentSnapshot.data['list']
              .map(
                (item) =>
                    // print(item);
                    RecipeItem(
                  category: item['category'],
                  wholeLine: item['wholeLine'],
                  recipeTitle: item['recipeTitle'],
                  recipeId: item['recipeId'],
                  purchased: item['purchased'],
                ),
              )
              .toList(),
        );
  }

现在 main.dart 我有一个 StreamProvider 寻找类型 <List<RecipeItem>>

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider<FirebaseUser>(
            //Access withing the app -> var user = Provider.of<FirebaseUser>(context);
            create: (_) => AuthService().user),
        StreamProvider<List<RecipeItem>>(
          create: (_) => PersonalListDB().getPersonalList(),
          catchError: (context, error) {
            print('This is the error from stream provider *** $error');
          },
        ),
        ChangeNotifierProvider(
          create: (_) => RecipesDB(),
        )
      ],
      child: MaterialApp(
etc etc...

当我 运行 这个时,我得到这个错误:

type 'List' is not a subtype of type 'List' in type cast

解决此问题的唯一方法是将 List<RecipeItem> 的所有位置更改为 List<dynamic>。这可行,但似乎不是正确的解决方案。

我已经尝试了一些(一百万)件事。

我在这里 post 找到了这个:

这告诉我 .toList() 可能是问题所在,因为它创建了 List。所以我尝试使用 List.from 并使用 .cast 但没有成功。更让我困惑的是,我非常密切地关注其他教程做类似的事情。

非常感谢任何解决此问题并帮助我理解问题的帮助。

Firestore 的列表(db、httpRequest 等)是动态类型的,以避免在调用它们时出现问题,您可以尝试告诉地图您要投射对象的类型

return _db.collection('shopping_lists').document(userId).snapshots().map<List<RecipeItem>>( //I'm not sure what kind of object this map should return, is this the method map part of the stream? if it is then it should be of type List<RecipeItem>
      (DocumentSnapshot documentSnapshot) => documentSnapshot.data['list']
          .map<RecipeItem>( //now it will know it's not a dynamic value but of type RecipeItem
            (item) =>
                // print(item);
                RecipeItem(
              category: item['category'],
              wholeLine: item['wholeLine'],
              recipeTitle: item['recipeTitle'],
              recipeId: item['recipeId'],
              purchased: item['purchased'],
            ),
          )
          .toList(),
);