Utilisez le package : https://pub.dev/packages/http
Pour convertir les caractères en UTF-8 :
String resApi = Utf8Decoder().convert(response.bodyBytes);
Ajoutez dans le fichier AndroidManifest.xml la permision internet :
<uses-permission android:name="android.permission.INTERNET" />
Et dans le pubspec.yaml :
dependencies:
flutter:
sdk: flutter
http: ^0.13.4
Exemple simple d’interrogation :
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; void main() { runApp( new MaterialApp( title: 'Fetch Data', home: Home(), ), ); } class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { @override void initState() { super.initState(); getData().then((value) { setState(() { infos = value; }); }); } var infos; getData() async { //https://jsonplaceholder.typicode.com/todos/1 /* { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false } */ var myUrl = Uri.https( 'jsonplaceholder.typicode.com', '/todos/1', {'q': '{http}'}); var req = await http.get(myUrl); infos = json.decode(req.body); print(infos['title']); return (infos['id'].toString()+') '+infos['title']); } @override Widget build(BuildContext context) { return new Scaffold( appBar: AppBar( title: new Text('hello'), backgroundColor: Colors.amber, ), body: new Center( child: infos == null ? new Text('test') : Text(infos), ), ); } }
B) Exemple avec un Classe
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response, then parse the JSON.
print (Album.fromJson(jsonDecode(response.body)[0]).title);
//print (Album.fromJson(jsonDecode(response.body)));
return Album.fromJson(jsonDecode(response.body)[0]);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
final String body;
Album({
required this.userId,
required this.id,
required this.title,
required this.body
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text("TITRE : "+snapshot.data!.title+"\nBODY :"+snapshot.data!.body);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
Créer une classe à partir d’un fichier JSON :
- Aller sur https://app.quicktype.io/.
- Donner un nom à la classe et coller le code JSON .
- Sélectionner le langage Dart et sélectionnez la méthode’ fromMap()’, et ‘make all properties required’
- Then, copy the model class code.
create a dart file in your project and paste the model class code.
The model class looks like this,
Ajouter à Chrome l’extension de visualisation JSON.
Puis copier le JSON obtenu dans la fenêtre à l’adresse : https://javiercbk.github.io/json_to_dart/
Ensuite, exemple d’exploitation d’un JSON complexe :
import 'dart:convert';
import 'package:http/http.dart' as http;
/*
Open URL https://javiercbk.github.io/json_to_dart/
Past the JSON (exemple (https://api.deezer.com/search?q=le%20bal%20des%20laze&index=0&limit=1&output=JSON))
*/
void main() async {
String url =
"https://api.deezer.com/search?q=le%20bal%20des%20laze&index=0&limit=1&output=JSON";
final response = await http.get(Uri.parse(url));
print(response.body);
Mp3Tag userDetails = Mp3Tag.fromJson(jsonDecode(response.body));
print(userDetails.data!.first.artist!.name);
}
class Mp3Tag {
List<Data>? data;
int? total;
String? next;
Mp3Tag({this.data, this.total, this.next});
Mp3Tag.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(new Data.fromJson(v));
});
}
total = json['total'];
next = json['next'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
data['total'] = this.total;
data['next'] = this.next;
return data;
}
}
class Data {
int? id;
bool? readable;
String? title;
String? titleShort;
String? titleVersion;
String? link;
int? duration;
int? rank;
bool? explicitLyrics;
int? explicitContentLyrics;
int? explicitContentCover;
String? preview;
String? md5Image;
Artist? artist;
Album? album;
String? type;
Data(
{this.id,
this.readable,
this.title,
this.titleShort,
this.titleVersion,
this.link,
this.duration,
this.rank,
this.explicitLyrics,
this.explicitContentLyrics,
this.explicitContentCover,
this.preview,
this.md5Image,
this.artist,
this.album,
this.type});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
readable = json['readable'];
title = json['title'];
titleShort = json['title_short'];
titleVersion = json['title_version'];
link = json['link'];
duration = json['duration'];
rank = json['rank'];
explicitLyrics = json['explicit_lyrics'];
explicitContentLyrics = json['explicit_content_lyrics'];
explicitContentCover = json['explicit_content_cover'];
preview = json['preview'];
md5Image = json['md5_image'];
artist =
json['artist'] != null ? new Artist.fromJson(json['artist']) : null;
album = json['album'] != null ? new Album.fromJson(json['album']) : null;
type = json['type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['readable'] = this.readable;
data['title'] = this.title;
data['title_short'] = this.titleShort;
data['title_version'] = this.titleVersion;
data['link'] = this.link;
data['duration'] = this.duration;
data['rank'] = this.rank;
data['explicit_lyrics'] = this.explicitLyrics;
data['explicit_content_lyrics'] = this.explicitContentLyrics;
data['explicit_content_cover'] = this.explicitContentCover;
data['preview'] = this.preview;
data['md5_image'] = this.md5Image;
if (this.artist != null) {
data['artist'] = this.artist!.toJson();
}
if (this.album != null) {
data['album'] = this.album!.toJson();
}
data['type'] = this.type;
return data;
}
}
class Artist {
int? id;
String? name;
String? link;
String? picture;
String? pictureSmall;
String? pictureMedium;
String? pictureBig;
String? pictureXl;
String? tracklist;
String? type;
Artist(
{this.id,
this.name,
this.link,
this.picture,
this.pictureSmall,
this.pictureMedium,
this.pictureBig,
this.pictureXl,
this.tracklist,
this.type});
Artist.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
link = json['link'];
picture = json['picture'];
pictureSmall = json['picture_small'];
pictureMedium = json['picture_medium'];
pictureBig = json['picture_big'];
pictureXl = json['picture_xl'];
tracklist = json['tracklist'];
type = json['type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['link'] = this.link;
data['picture'] = this.picture;
data['picture_small'] = this.pictureSmall;
data['picture_medium'] = this.pictureMedium;
data['picture_big'] = this.pictureBig;
data['picture_xl'] = this.pictureXl;
data['tracklist'] = this.tracklist;
data['type'] = this.type;
return data;
}
}
class Album {
int? id;
String? title;
String? cover;
String? coverSmall;
String? coverMedium;
String? coverBig;
String? coverXl;
String? md5Image;
String? tracklist;
String? type;
Album(
{this.id,
this.title,
this.cover,
this.coverSmall,
this.coverMedium,
this.coverBig,
this.coverXl,
this.md5Image,
this.tracklist,
this.type});
Album.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
cover = json['cover'];
coverSmall = json['cover_small'];
coverMedium = json['cover_medium'];
coverBig = json['cover_big'];
coverXl = json['cover_xl'];
md5Image = json['md5_image'];
tracklist = json['tracklist'];
type = json['type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['cover'] = this.cover;
data['cover_small'] = this.coverSmall;
data['cover_medium'] = this.coverMedium;
data['cover_big'] = this.coverBig;
data['cover_xl'] = this.coverXl;
data['md5_image'] = this.md5Image;
data['tracklist'] = this.tracklist;
data['type'] = this.type;
return data;
}
}
void main() async {
String url =
// "https://api.deezer.com/search?q=le%20bal%20des%20laze&index=0&limit=1&output=JSON";
// "https://api.deezer.com/search?q=Michel Polnareff";
//"https://api.deezer.com/search?q=They don't know";
"https://api.deezer.com/search?q=Tracey Ullman";
final response = await http.get(Uri.parse(url));
//print(response.body);
Mp3Tag userDetails = Mp3Tag.fromJson(jsonDecode(response.body));
print(userDetails.data!.first.artist!.name);
print(userDetails.data!.first.title);
print(userDetails.data!.length);
var nb=userDetails.data!.length;
var rest = userDetails.data! as List;
for (var i=0 ; i< nb ;i++) {
print(rest[i].artist!.name+" : "+rest[i].title);
}
}
Test :
https://reqbin.com/req/enuzjzmm/test-json-api
Autre tuto pour récupérer le résultat des APIs :
https://medium.datadriveninvestor.com/integrating-apis-in-flutter-897cc6bf3f73
Pour l’adapter à d’autres URLs/APIs, utiliser https://app.quicktype.io/ et cocher Use method names fromMap() & toMap() et Make all properties required.
Puis modifier le code en changeant fromMap à fromJson et Change toMap à toJson
Cet exemple utilise Fakestore API et les packages :
http package: pour les appels HTTP
cached_network_image: Pour mettre en cache les images
flutter_staggered_grid_view: Pour la présentation en grille (attention la version utilisée est la ^0.4.0)
get (GetX): Pour le state management
Le code source est ici
Pour récupérer le résultat d’une API et le stocker dans une Base de données : https://app.box.com/s/dlfphglfi0jr5ostv6e8ms0wky73z76f
EXEMPLE API :
Pour récupérer du contenu HTTP (avec la dépendance : http: ^0.13.5) JSON ou XML (avec la dépendance : xml: ^6.1.0), ajouter dans le fichier manifest.xml :
<uses-permission android:name="android.permission.INTERNET" />
cf. https://www.kindacode.com/article/how-to-parse-and-render-xml-data-in-flutter/
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'package:xml/xml.dart' as xml;
void main(List<String> arguments) async {
var url =
//Uri.https('www.googleapis.com', '/books/v1/volumes', {'q': '{http}'});
//http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=Kiss&song=detroit
Uri.http('api.chartlyrics.com', '/apiv1.asmx/SearchLyricDirect',
{'artist': '{Kiss}', 'song': '{detroit}'});
// Await the http get response, then decode the xml or json-formatted response.
var response = await http.get(url);
if (response.statusCode == 200) {
/*
//-------------- Pour récupérer du contenu JSON :
var jsonResponse =
convert.jsonDecode(response.body) as Map<String, dynamic>;
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
*/
//-------------- Pour récupérer du contenu XML :
final temporaryList = [];
final document = xml.XmlDocument.parse(response.body);
final employeesNode = document.findElements('GetLyricResult').first;
final ImageCoverUrl =
employeesNode.findElements('LyricCovertArtUrl').first.text;
print(ImageCoverUrl);
final LyricsTxt = employeesNode.findElements('Lyric').first.text;
print(LyricsTxt);
} else {
print('Request failed with status: ${response.statusCode}.');
}
}
Références :
https://docs.flutter.dev/cookbook/networking/fetch-data
https://medium.com/@electrophile172/json-parsing-in-flutter-d542797663c0