Flutter 出现 "DatabaseEvent subtype" 错误

Flutter stuck with a "DatabaseEvent subtype" error

下面的代码给出了子类型的错误

Data Structure

代码

StreamBuilder(
        stream: _database.orderByKey().onValue,
        builder: (context, snapshot) {
          final valudisp = <Card>[];
          if (snapshot.hasData) {
            final firstdata = snapshot.data! as Map<String, dynamic>;
            firstdata.forEach((key, value) {
              final datalast = new Map<String, dynamic>.from(value);
              final coinname = datalast.keys;
              final displaycard = Card(...);
              valudisp.add(displaycard);
             });
          }
          return Expanded(...);
       }); 
      }    

现在我遇到错误

type 'DatabaseEvent' is not a subtype of type 'Map<String,dynamic>' in typecast

我想你正在寻找 DatabaseEvent class 那里:

(snapshot.data! as DatabaseEvent).snapshot.value
                 // 

这段代码工作正常。

将第一个快照映射为

StreamBuilder(
        stream: _database.onValue,
        builder: (context, snapshot) {
          final valudisp = <Card>[];
          if (snapshot.hasData) {
            final firstdata = (snapshot.data! as DatabaseEvent)
                .snapshot
                .value as Map<Object?, dynamic?>;
            firstdata.forEach((key, value) {
              final datalast = new Map<String, dynamic>.from(value);
              final coinname = datalast['namedata'];
              final _diff = datalast['dif'];
              final time = datalast['Time'];
              final Quantity = datalast['Quantity'];
              final tradep = datalast['tradep'];
              final displaycard =Card(...)