import 'dart:convert'; import 'package:http/http.dart' as http; class ApiService<T> { final String _baseUrl; ApiService(this._baseUrl); Future<List<T>> getAll(T Function(Map<String, dynamic>) fromJson) async { final response = await http.get(Uri.parse(_baseUrl)); if (response.statusCode == 200) { final jsonData = json.decode(response.body) as List; return jsonData.map((data) => fromJson(data)).toList(); } else { throw Exception('Failed to load data'); } } Future<List<T>> search(String query, T Function(Map<String, dynamic>) fromJson) async { final response = await http.get(Uri.parse('$_baseUrl?search=$query')); if (response.statusCode == 200) { final jsonData = json.decode(response.body) as List; return jsonData.map((data) => fromJson(data)).toList(); } else { throw Exception('Failed to search data'); } } Future<T> create(Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async { final response = await http.post( Uri.parse(_baseUrl), headers: {'Content-Type': 'application/json'}, body: json.encode(data), ); if (response.statusCode == 201) { return fromJson(json.decode(response.body)); } else { throw Exception('Failed to create data'); } } Future<T> update(int id, Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async { final response = await http.put( Uri.parse('$_baseUrl/$id'), headers: {'Content-Type': 'application/json'}, body: json.encode(data), ); if (response.statusCode == 200) { return fromJson(json.decode(response.body)); } else { throw Exception('Failed to update data'); } } Future<void> delete(int id) async { final response = await http.delete(Uri.parse('$_baseUrl/$id')); if (response.statusCode != 204) { throw Exception('Failed to delete data'); } } } //============================================= class Note { final int id; final String title; final String content; Note({required this.id, required this.title, required this.content}); factory Note.fromJson(Map<String, dynamic> json) { return Note( id: json['id'], title: json['title'], content: json['content'], ); } Map<String, dynamic> toJson() { return { 'id': id, 'title': title, 'content': content, }; } } final notesService = ApiService<Note>('http://10.0.2.2:8000/api/notes'); // Get all notes final notes = await notesService.getAll(Note.fromJson); // Search for notes final searchResults = await notesService.search('keyword', Note.fromJson); // Create a new note final newNote = await notesService.create( { 'title': 'New Note', 'content': 'This is a new note', }, Note.fromJson, ); // Update a note final updatedNote = await notesService.update( newNote.id, { 'title': 'Updated Note', 'content': 'This is an updated note', }, Note.fromJson, ); // Delete a note await notesService.delete(updatedNote.id);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter