Created
October 16, 2022 09:09
-
-
Save Taosif7/99579ef9332a2baafe4f9ab90ba904ee to your computer and use it in GitHub Desktop.
TempFile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:http/http.dart' as http; | |
void main() async { | |
var empResponse = await getEmployeeById(256); | |
if(empResponse.employee != null){ | |
print("EMPLOYEE NAME: "+empResponse.employee.name); | |
}else{ | |
print("EMPLOYEE DOES NOT EXIST"); | |
} | |
} | |
Future<EmployeeResponse> getEmployeeById(int id) async { | |
try{ | |
var response = await http.get(Uri.parse("example.com/api/emp/${id}")); | |
if(response.statusCode == 200){ | |
var data = json.decode(response.body); | |
return EmployeeResponse.fromMap(data); | |
}else{ | |
return EmployeeResponse(); | |
} | |
} catch(e) { | |
return EmployeeResponse(); | |
} | |
} | |
class EmployeeResponse { | |
EmployeeResponse({ | |
this.employee, | |
}); | |
final Employee? employee; | |
factory EmployeeResponse.fromMap(Map<String, dynamic> json) => EmployeeResponse( | |
employee: json["employee"] == null ? null : Employee.fromMap(json["employee"]), | |
); | |
} | |
class Employee { | |
Employee({ | |
required this.name, | |
required this.age, | |
required this.joinYear, | |
}); | |
final String name; | |
final int age; | |
final String joinYear; | |
factory Employee.fromMap(Map<String, dynamic> json) => Employee( | |
name: json["name"], | |
age: json["age"], | |
joinYear: json["join_year"], | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment