findBestPage function
Searches Wikipedia using the opensearch
API for the most suitable page
(wikiTitle, null) or (null, errorMessage)
Implementation
Future<(String?, String?)> findBestPage(String query) async {
final response = await http
.get(Uri.parse('https://en.wikipedia.org/w/api.php?action=opensearch&search=${const HtmlEscape().convert(query)}&limit=1&namespace=0&format=json'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
try {
var json = jsonDecode(response.body) as List<dynamic>;
_log.fine(json);
if ((json[1] as List).isNotEmpty) {
return (json[1][0] as String, null);
}
else {
return (null, 'Wikipedia entry not found: $query');
}
} catch (e) {
_log.fine('error parsing JSON: $e');
return (null, '$e');
}
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
return (null, 'Failed to load wiki result - Response: ${response.statusCode}');
}
}