-
-
Save gopalkohli/e2fa1e2ffbf01d9f1ee55daa0ea15cd5 to your computer and use it in GitHub Desktop.
Call to Datamuse api to retreive the data.
This file contains hidden or 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:async'; | |
| import 'package:http/http.dart' as http; | |
| import 'dart:convert' as convert; | |
| class BackendService { | |
| static Future<List<Map<String, String>>> getSuggestions(String query) async { | |
| if (query.isEmpty && query.length < 3) { | |
| print('Query needs to be at least 3 chars'); | |
| return Future.value([]); | |
| } | |
| var url = Uri.https('api.datamuse.com', '/sug', {'s': query}); | |
| var response = await http.get(url); | |
| List<Suggestion> suggestions = []; | |
| if (response.statusCode == 200) { | |
| Iterable json = convert.jsonDecode(response.body); | |
| suggestions = | |
| List<Suggestion>.from(json.map((model) => Suggestion.fromJson(model))); | |
| print('Number of suggestion: ${suggestions.length}.'); | |
| } else { | |
| print('Request failed with status: ${response.statusCode}.'); | |
| } | |
| return Future.value(suggestions | |
| .map((e) => {'name': e.word, 'score': e.score.toString()}) | |
| .toList()); | |
| } | |
| } | |
| class Suggestion { | |
| final int score; | |
| final String word; | |
| Suggestion({ | |
| required this.score, | |
| required this.word, | |
| }); | |
| factory Suggestion.fromJson(Map<String, dynamic> json) { | |
| return Suggestion( | |
| word: json['word'], | |
| score: json['score'], | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment