Flutter : appel d’API

Utilisez le package : https://pub.dev/packages/http

Ajoutez dans le fichier AndroidManifest.xml la permision internet :

<uses-permission android:name="android.permission.INTERNET" />

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 :

  • 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,

Outils :

Ajouter à Chrome l’extension de visualisation JSON.

https://reqbin.com/req/enuzjzmm/test-json-api

Références :

https://docs.flutter.dev/cookbook/networking/fetch-data

https://medium.com/@electrophile172/json-parsing-in-flutter-d542797663c0

Articles récents
Commentaires récents
fatima dans Bienvenue !
AdminDroid dans Bienvenue !
fatima dans Bienvenue !
Archives
Catégories
%d blogueurs aiment cette page :