skip to Main Content

I want to create a map in Firebase and get the slider values ​​from there. But it gives an error. "type ‘_Map<String, dynamic>’ is not a subtype of type ‘Map<Double, Double>’ in type cast
"

enter image description here

Expanded(
  child: StreamBuilder<DocumentSnapshot>(
      stream: FirebaseFirestore.instance
          .collection("deger").doc("1")
          .snapshots(),
      builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
       final  Map<Double, Double> map = snapshot.data!["item"] as  Map<Double, Double>;
          return VerticalSlider(
            min: parameters.minDecibels,
            max: parameters.maxDecibels,
            value: map as double,
            onChanged: band.setGain,
          );

      }),
),

I couldn’t find a solution.

2

Answers


  1. Chosen as BEST ANSWER
    Expanded(
                      child: StreamBuilder<DocumentSnapshot>(
                          stream: FirebaseFirestore.instance
                              .collection("deger").doc("1")
                              .snapshots(),
                          builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
                           final map = snapshot.data!["item"].map((key, value) => MapEntry(int.parse(key.substring(4)), value));
                           ;
                              return VerticalSlider(
                                min: parameters.minDecibels,
                                max: parameters.maxDecibels,
                                value: map,
                                onChanged: band.setGain,
                              );
    
                          }),
                    ),
    

    type '_Map<dynamic, dynamic>' is not a subtype of type 'double' it gives this error.


  2. The keys in the items are not a number. They’re strings like "item1", "item2", etc.

    If you want to interpret just the number part of those (i.e. 1, 2, etc), you will have to parse the key in your code.

    Something like:

    snapshot.data!["item"].map((key, value) => MapEntry(int.parse(key.substring(4)), value));
    

    So the above first removes the "item" prefix from the string, and then converts the remained to a number.

    A complete example I tested in DartPad:

    const item = {
      "item1": 1.5,
      "item2": 1.5,
      "item3": 1.5,
    };
    
    void main() {
      final updated = item.map((key, value) => MapEntry(int.parse(key.substring(4)), value));
      print(updated);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search