期望一个“用户”类型的值,但在尝试将 Firestore 数据获取到 Flutter Web 上的 PaginatedDataTable 时得到一个“Null”类型的值?

Posted

技术标签:

【中文标题】期望一个“用户”类型的值,但在尝试将 Firestore 数据获取到 Flutter Web 上的 PaginatedDataTable 时得到一个“Null”类型的值?【英文标题】:Expected a value of type 'User', but got one of type 'Null' while trying to get firestore data in to PaginatedDataTable on flutter web? 【发布时间】:2022-01-08 16:09:13 【问题描述】:

我正在尝试在 Flutter Web 应用程序的 PaginatedDataTable 上显示我的 Firestore 收集数据之一。但得到错误。请在下面修改我的代码和调试错误。如果以下方法不正确,请告诉我最佳方法。我想在 PaginatedDataTable 上显示我的 Firestore 字段作为流生成器方法。需要帮助如何做到这一点?如果在 PaginatedDataTable 中不可能,如果有其他方法请告诉我。 如何实现 User 类?

下面是我的示例代码:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class AdminDashboard extends StatefulWidget 
  const AdminDashboard(Key? key) : super(key: key);

  @override
  _AdminDashboardState createState() => _AdminDashboardState();


class _AdminDashboardState extends State<AdminDashboard> 
  //final DataTableSource _allUsers = UsersData();

  @override
  Widget build(BuildContext context) 
    List<User>? users;
    return StreamBuilder(
        //padding: const EdgeInsets.all(16),
        stream: FirebaseFirestore.instance.collection("users").snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snap) 
          users = snap.data!.docs.map((e) => User.fromMap(e.data)).cast<User>().toList();
          final DataTableSource _allUsers = UsersData(users!);
          if (snap.hasData) 
            return PaginatedDataTable(
              header: const Text("Header Text"),
              rowsPerPage: 9,
              columns: const [
                DataColumn(label: Text('Uid')),
                DataColumn(label: Text('Name')),
                DataColumn(label: Text('Email')),
                DataColumn(label: Text('Role'))
              ],
              source: _allUsers,
            );
           else 
            return const Text('No data...');
          
        );
  


class User 
  
  late String name;

  late String email;

  late String role;

  late String uid;

  static fromMap(Object? Function() data) 


class UsersData extends DataTableSource 
  final List<User> users;

  UsersData(this.users);

  @override
  DataRow getRow(int index) 
    return DataRow.byIndex(cells: [
      DataCell(Text(users[index].uid)),
      DataCell(Text(users[index].name)),
      DataCell(Text(users[index].email)),
      DataCell(Text(users[index].role)),
    ], index: index);
  

  @override
  bool get isRowCountApproximate => false;

  @override
  int get rowCount => users.length;

  @override
  int get selectedRowCount => 0;

下面是调试控制台错误:

Launching lib\main.dart on Chrome in debug mode...
This app is linked to the debug service: ws://127.0.0.1:54737/8r23hBREOEg%3D/ws
Debug service listening on ws://127.0.0.1:54737/8r23hBREOEg=/ws
 Running with sound null safety
Connecting to VM Service at ws://127.0.0.1:54737/8r23hBREOEg=/ws

════════ Exception caught by widgets library ═══════════════════════════════════
The following TypeErrorImpl was thrown building StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Map<String, dynamic>>, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>>>#58793):
Unexpected null value.

The relevant error-causing widget was
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>
When the exception was thrown, this was the stack
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49      throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 528:63  nullCheck
packages/pma/admin_dir/admin_dashboard.dart 21:81                                                                              <fn>
packages/flutter/src/widgets/async.dart 545:81                                                                                 build
packages/flutter/src/widgets/async.dart 124:48                                                                                 build
packages/flutter/src/widgets/framework.dart 4782:27                                                                            build
packages/flutter/src/widgets/framework.dart 4665:15                                                                            performRebuild
packages/flutter/src/widgets/framework.dart 4840:11                                                                            performRebuild
packages/flutter/src/widgets/framework.dart 4355:5                                                                             rebuild
packages/flutter/src/widgets/framework.dart 4643:5                                                                             [_firstBuild]
packages/flutter/src/widgets/framework.dart 4831:11                                                                            [_firstBuild]
packages/flutter/src/widgets/framework.dart 4638:5                                                                             mount
packages/flutter/src/widgets/framework.dart 3673:13                                                                            inflateWidget
packages/flutter/src/widgets/framework.dart 3425:18                                                                            updateChild
packages/flutter/src/widgets/framework.dart 4690:16                                                                            performRebuild
packages/flutter/src/widgets/framework.dart 4355:5                                                                             rebuild
packages/flutter/src/widgets/framework.dart 5020:5                                                                             update
packages/flutter/src/widgets/framework.dart 3412:14                                                                            updateChild
packages/flutter/src/widgets/framework.dart 4690:16                                                                            performRebuild
packages/flutter/src/widgets/framework.dart 4840:11                                                                            performRebuild
packages/flutter/src/widgets/framework.dart 4355:5                                                                             rebuild
packages/flutter/src/widgets/framework.dart 2620:31                                                                            buildScope
packages/flutter/src/widgets/binding.dart 882:9                                                                                drawFrame
packages/flutter/src/rendering/binding.dart 319:5                                                                              [_handlePersistentFrameCallback]
packages/flutter/src/scheduler/binding.dart 1143:15                                                                            [_invokeFrameCallback]
packages/flutter/src/scheduler/binding.dart 1080:9                                                                             handleDrawFrame
packages/flutter/src/scheduler/binding.dart 996:5                                                                              [_handleDrawFrame]
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 1003:13               invoke
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/platform_dispatcher.dart 157:5                 invokeOnDrawFrame
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine.dart 440:45                                    <fn>
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════
Expected a value of type 'User', but got one of type 'Null'
The relevant error-causing widget was
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>
════════════════════════════════════════════════════════════════════════════════ 

【问题讨论】:

您可以参考类似的*** case,其中提到了使用streambuilder 进行flutter firestore 分页。让我知道这是否有帮助! 【参考方案1】:

错误日志表明User.fromMap(e.data) 没有返回用户(而是返回 null)。而且我发现你的User.fromMap(e.data) 实现是空的:

class User 
  
  late String name;

  late String email;

  late String role;

  late String uid;

  static fromMap(Object? Function() data) 

【讨论】:

如何实现用户类?如果您有任何想法,请告诉我。

以上是关于期望一个“用户”类型的值,但在尝试将 Firestore 数据获取到 Flutter Web 上的 PaginatedDataTable 时得到一个“Null”类型的值?的主要内容,如果未能解决你的问题,请参考以下文章

如何将Int类型的值转换为期望的布尔类型参数

Hardhat 编译错误“期望 HttpNetworkConfig 类型的值”

无法将类型“([AnyObject]!,NSError!)-> Void”的值转换为期望参数类型“CLGeocodeCompletionHandler”

石墨烯:“期望 XXX 类型的值,但收到:...”

Flutter 错误:期望一个类型为“Map<String, dynamic>”的值,但出现了一个类型为“List<dynamic>”的值

如何将“AVAudioPlayer.Type”类型的值分配给“AVAudioPlayer?”