Home > Enterprise >  'Null' is not a subtype of type 'String' in flutter model class
'Null' is not a subtype of type 'String' in flutter model class

Time:08-26

I am using google place search api to have place predictions and display it using listtile. But I dont knenter image description hereow why I am getting this error. I have tried to do everything such as adding some text in above mentioned variables or marking them late. However, this issue is not resolved.

here is the code:
// ignore_for_file: non_constant_identifier_names

class placePredictions{
  String secondary_text = "pla";
  String main_text = "plac" ;
  String place_id = "plac";

  // ignore: non_constant_identifier_names
  placePredictions({required this.secondary_text, required this.main_text, required this.place_id});

  placePredictions.fromJson(Map<String, dynamic> json){
    place_id = json["place_id"];
    main_text = json["structured_formatting"]["main_text"];
    secondary_text = json["secondary_text"];
  }
}



Code of location where this model class is being used:
        (placePredictions_lst.length>0)? Padding(padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16), child: ListView.separated(
          padding: EdgeInsets.all(0),
          itemBuilder: (context, index){
            return PredictionTile(placePredictions_obj: placePredictions_lst[index],);

          },
          separatorBuilder: (BuildContext context, int index) => Divider_Widget(),
          itemCount:placePredictions_lst.length,
          shrinkWrap: true,
          physics: ClampingScrollPhysics(),
        ),):Container(),
      ]),
    );
  }
  void find_location(String placeName, Position current_pos) async{
   if(placeName !=  null){
    final main_screen_obj = Main_Screen();
      final current_lat = current_pos.latitude;
      final current_lon = current_pos.latitude;
  

      
      String auto_complete_url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$placeName&key=$google_map_api_key&components=country:pk&radius=100000&location=$current_lat%$current_lon";

      var response = await placeSearcher.getRequest(auto_complete_url);

      if (response =="failed"){
        return;
      }

      print(response);

      if (response["status"] == "OK"){
        var predictions = response["predictions"];
        // this will basically convery the json data in list format
        var place_lst = (predictions as List).map((e) => placePredictions.fromJson(e)).toList();
        placePredictions_lst = place_lst;
        
        setState(() {
          placePredictions_lst = place_lst;
        });

      }

   }
}

CodePudding user response:

You can assign a value if its null like this

secondary_text = json["secondary_text"] ?? "";
  • Related