Home > OS >  How to get data from flutter Map{}
How to get data from flutter Map{}

Time:08-03

I have created a map named starsMap in the class[step 1]. I have not initialized any value to it. after that, I am calling a function then assigning response data to value to it [step 2], and after that assigning data to a1Rating [step 3]. but I am getting the following error.

class _GiveFeedbackScreenState extends State<GiveFeedbackScreen> {
  // Getting feedback data | stars

// step : 1
  Map starsMap = {};

  getFeedbackStars() async {
    final prefss = await SharedPreferences.getInstance();
    var token = prefss.getString('token');
    var subject_id = widget.subjectId;
    var feedback_id = widget.feedbackId;
    var response = await http.get(
      Uri.parse(
          "https://xxxxxxx"),
      headers: {
        'Authorization': 'Bearer $token',
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    );
    var data = jsonDecode(response.body)['result'];
// step : 2
    this.starsMap = {
"a1": data['a1'],
"a1": data['a2'],
"a1": data['b1'],
"a1": data['b2'],
};
    // print(this.starsMap);
    return jsonDecode(response.body);
  }


//  [step : 3 ]
  double a1Rating = this.starsMap['a1']; // error here
//The instance member 'starsMap' can't be accessed in an initializer.
//Try replacing the reference to the instance member with a different expression

  double a2Rating = this.starsMap['a2'];
  double b1Rating = this.starsMap['b1'];
  double b2Rating = this.starsMap['b2'];
 

and I have to show that rating into RatingBar

  RatingBar(
                                    initialRating: this.a1Rating!,
                                    direction: Axis.horizontal,
                                    allowHalfRating: false,
                                    itemCount: 5,
                                    ratingWidget: RatingWidget(
                                        full: const Icon(Icons.star,
                                            color: Colors.orange),
                                        half: const Icon(
                                          Icons.star_half,
                                          color: Colors.orange,
                                        ),
                                        empty: const Icon(
                                          Icons.star_outline,
                                          color: Colors.orange,
                                        )),
                                    onRatingUpdate: (value) {
                                      a1Rating = value;
                                      // setState(() {});
                                    }),

CodePudding user response:

The error means that its directly trying to assign within the class without a method. You can try this

class _GiveFeedbackScreenState extends State<GiveFeedbackScreen> {
  // Getting feedback data | stars

// step : 1
  Map starsMap = {};

  getFeedbackStars() async {
    final prefss = await SharedPreferences.getInstance();
    var token = prefss.getString('token');
    var subject_id = widget.subjectId;
    var feedback_id = widget.feedbackId;
    var response = await http.get(
      Uri.parse(
          "https://xxxxxxx"),
      headers: {
        'Authorization': 'Bearer $token',
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    );
    var data = jsonDecode(response.body)['result'];
// step : 2
    this.starsMap = {
"a1": data['a1'],
"a1": data['a2'],
"a1": data['b1'],
"a1": data['b2'],
};
    // print(this.starsMap);
    return jsonDecode(response.body);
  }


//  [step : 3 ]
void fetchDate(){
  double a1Rating = this.starsMap['a1']; // error here
//The instance member 'starsMap' can't be accessed in an initializer.
//Try replacing the reference to the instance member with a different expression

  double a2Rating = this.starsMap['a2'];
  double b1Rating = this.starsMap['b1'];
  double b2Rating = this.starsMap['b2'];
}

Call this fetch data where you wish to fetch the data like

fetchData();

CodePudding user response:

Initialize this double a1Rating = this.starsMap['a1']; inside a function, you can not use this.starsMap['a1']; in an initializer. You need to define a1Rating, a2Rating, b1Rating, b2Rating first.

//use nullable
double? a1Rating;
double? a2Rating;
double? b1Rating;
double? b2Rating;

// or use late
late double a1Rating;
late double a2Rating;
late double b1Rating;
late double b2Rating;

// or set zero as default
double a1Rating = 0;
double a2Rating = 0;
double b1Rating = 0;
double b2Rating = 0;

then create the function to fetch or set data inside getFeedbackStars or wherever you want (make sure getFeedbackStars or hhtp already called).

void setData(){
  a1Rating = this.starsMap['a1'];
  a2Rating = this.starsMap['a2'];
  b1Rating = this.starsMap['b1'];
  b2Rating = this.starsMap['b2'];
}

full code

class _GiveFeedbackScreenState extends State<GiveFeedbackScreen> {
  // Getting feedback data | stars

// step : 1
  Map starsMap = {};

  double a1Rating = 0;
  double a2Rating = 0;
  double b1Rating = 0;
  double b2Rating = 0;

  getFeedbackStars() async {
    final prefss = await SharedPreferences.getInstance();
    var token = prefss.getString('token');
    var subject_id = widget.subjectId;
    var feedback_id = widget.feedbackId;
    var response = await http.get(
      Uri.parse(
          "https://xxxxxxx"),
      headers: {
        'Authorization': 'Bearer $token',
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    );
    var data = jsonDecode(response.body)['result'];
// step : 2
    this.starsMap = {
     "a1": data['a1'],
     "a2": data['a2'],
     "b1": data['b1'],
     "b2": data['b2'],
    };
    // print(this.starsMap);
    setData();
    return jsonDecode(response.body);
 }

 void setData(){
   a1Rating = this.starsMap['a1'];
   a2Rating = this.starsMap['a2'];
   b1Rating = this.starsMap['b1'];
   b2Rating = this.starsMap['b2'];
 }

 Widget setA1Rating() {
  return RatingBar(
           initialRating: this.a1Rating,
           direction: Axis.horizontal,
           allowHalfRating: false,
           itemCount: 5,
           ratingWidget: RatingWidget(
                           full: const Icon(Icons.star, color: Colors.orange),
                           half: const Icon(Icons.star_half, color: Colors.orange,
                            ),
                           empty: const Icon(Icons.star_outline, color: Colors.orange,)),
                           onRatingUpdate: (value) {
                                 a1Rating = value;
                                 // setState(() {});
                           }
  );
 }
}
  • Related