Created with <3 with dartpad.dev.
Created
January 19, 2023 00:52
-
-
Save leonino/65c543f8662ded12d080c7444847fee6 to your computer and use it in GitHub Desktop.
Consumir API Mock
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'; | |
void main() async { | |
final resultHttp = await Http.get("http://teste.com", filtro: "Maria"); | |
final lista = json.decode(resultHttp)['data'] as List; | |
final contatos = lista.map((contato) => Contato.fromJson(contato)).toList(); | |
contatos.forEach(print); | |
} | |
class Contato { | |
final int id; | |
final String name; | |
Contato({required this.id, required this.name}); | |
factory Contato.fromJson(json) => Contato( | |
id: json['id'], | |
name: json['name'], | |
); | |
@override | |
String toString() => // | |
'id: $id, name: $name'; | |
} | |
/// | |
/// Mock do Serviço Http | |
/// | |
class Http { | |
/// | |
/// [url] | |
/// | |
static Future<String> get(String url, {String? filtro}) { | |
String data; | |
if (filtro is String && filtro != "") { | |
final filtroLowercase = filtro.toLowerCase(); | |
var dataWhere = dados.where((Map<String, dynamic> e) { | |
final existe = e.values // | |
.whereType<String>() // | |
.where((v) => v.toLowerCase().contains(filtroLowercase)) // | |
.toList(); | |
return existe.isNotEmpty; | |
}).toList(); | |
data = json.encode({"data": dataWhere}); | |
} else { | |
data = json.encode({"data": dados}); | |
} | |
return Future<String>.value(data); | |
} | |
} | |
const dados = <Map<String, dynamic>>[ | |
{"id": 1, "name": "Maria Antonia"}, | |
{"id": 2, "name": "Antonio Maria"}, | |
{"id": 3, "name": "Antonio Marcos"}, | |
{"id": 4, "name": "Marcos Antonio"}, | |
{"id": 5, "name": "Maria Jose"}, | |
{"id": 6, "name": "Jose Maria"}, | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment