Home > Blockchain >  _CastError (type '() => Map<String, dynamic>' is not a subtype of type 'Map&
_CastError (type '() => Map<String, dynamic>' is not a subtype of type 'Map&

Time:09-19

wrong here /* Cal.frommap(documentSnapshot.data as Map<String,dynamic>)) */ I want to fetch data from firebase into pie chart.

The first part is a widget to retrieve data from firebase. but i wonder Cal.frommap(documentSnapshot.data as Map<String,dynamic>)) I'm doing something wrong, it doesn't run.

Widget bulidChart(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection("chart").snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return LinearProgressIndicator();
          } else {
            
            List<Cal> cal = snapshot.data!.docs
                .map((documentSnapshot) =>
                    Cal.frommap(documentSnapshot.data as Map<String,dynamic>))
                .toList();

            return _buildChart(context, cal);
          }
        });
  }

This section shows the pie chart as an example.

  Widget _buildChart(BuildContext context, List<Cal> cal) {
    KcalData = cal;
    _generateData(KcalData);
    return Padding(
      padding: EdgeInsets.all(10),
      child: Container(
        child: Center(
            child: Column(
          children: [
            charts.PieChart(
              datachart!,
              animate: true,
              
              behaviors: [
                charts.DatumLegend(
                    entryTextStyle: charts.TextStyleSpec(
                        color: charts.MaterialPalette.purple.shadeDefault,
                        fontSize: 20,
                        fontFamily: 'Mitr'))
              ],
            )
          ],
        )),
      ),
    );
}
class Cal{
  String? foodName;
  double? kCal;
  String? colorVal;
  Cal(this.foodName,this.kCal,this.colorVal);
  
  Cal.frommap(Map<String,dynamic>map)
  :assert(map['foodName']!=null),
   assert(map['kCal']!=null),
   assert(map['colorVal']!=null),
  foodName=map['foodName'],
  kCal=map['kCal'],
  colorVal=map['colorVal'];


  String toString()=> "Record<$foodName:$kCal:$colorVal>";
}

CodePudding user response:

Your error is saying that what your are getting from documentSnapshot.data is a function which is returning Map<String, dynamic>. But you had casted it as simply Map<String, dynamic>.

To understand this, I suggest you read the following example, and read carefully this method in example getExpenseItems which is showing proper way to extract the data.

CodePudding user response:

  Cal.frommap(documentSnapshot.data as Map<String,dynamic>)

remove the casting and put () after data so it will be:

 Cal.frommap(documentSnapshot.data())

because data() will return a map

  • Related