Flutter stuck with a "DatabaseEvent subtype" error

Issue

The below code gives an error of subtype

Data Structure

code

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(...);
       }); 
      }    

Now I’m getting below error

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

Solution

This code works fine.

map the first snapshot as <Object, dynamic>.

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(...)

Answered By – Buddy Ramesh

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.