Home > Software design >  Flutter Using Map<String, dynamic> or Dedicated Models for JSON Responses
Flutter Using Map<String, dynamic> or Dedicated Models for JSON Responses

Time:01-11

Since http responses for APIs returns a Map<String, dynamic>, we can use this directly in our Widgets. But is this the right way? Or do we have to convert this Map into a dedicated model by using Model.fromJson() method? To be more precise, lets give pseudo-like code examples in short:

First way:

class example{
   List<Map<String, dynamic>> list;
   .
   .
   .
   readApi(){
      list = jsonDecode('apiResponseJsonString') //returns a List<Map<String, dynamic>>;
   }
   .
   .
   .
   child: Text(obj[0]['Title'])
}

Second way:

class CustomModel{
   String title;
   CustomModel.fromJson(Map<String, dynamic> json){
      return CustomModel(title: json['Title'] as String);
   }
}

class example{
   List<CustomModel> list;
   .
   .
   .
   readApi(){
      final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
      return parsed.map<CustomModel>((json) => CustomModel.fromJson(json)).toList();
   }
   .
   .
   .
   child: Text(list[0].title)
}

Which way is faster and safer to use?

Thanks

CodePudding user response:

The second way is definitely safer to use. It is because your code will be type-safe and you will be able to use all the cool language features like autocomplete. However, the first way may be a few milliseconds faster but it is definitely not worth it because it can save a lot more development time than those few milliseconds.

  •  Tags:  
  • Related