Partage
  • Partager sur Facebook
  • Partager sur Twitter

flutter api json est vide

mon json generer par l'api est vide

    1 septembre 2023 à 3:23:20

    bonsoir je developpe une application mobile avec flutter et j'aimerais utiliser le local storage pour stocker des information evitant ici d'avoir besoin de la connexion internet a tout moment. 

    voici mon code :

    import 'dart:convert';
    import 'package:flutter/services.dart';
    import 'package:http/http.dart' as http;
    import 'package:path_provider/path_provider.dart';
    import 'dart:io';
    
    class Item {
      int id;
      String thematique;
      String image;
    
      Item({
        required this.id,
        required this.thematique,
        required this.image,
      });
    
      factory Item.fromJson(Map<String, dynamic> json) {
        return Item(
          id: json['id'],
          thematique: json['thematique'],
          image: json['image'],
        );
      }
    }
    
    class ItemRepository {
      Future<void> updateItemsFromApi() async {
        final apiUrl = 'http://172.20.10.13/Rubis/php-flutter-api/quiz_items.php';
    
        try {
          final response = await http.post(Uri.parse(apiUrl));
    
          if (response.statusCode == 200) {
            final jsonData = json.decode(response.body) as Map<String, dynamic>;
            print('JSON Data from API: $jsonData'); // Affichage avant convertion
    
            final localDir = await getApplicationDocumentsDirectory();
            final localFilePath = '${localDir.path}/quiz.json';
    
            final localFile = File(localFilePath);
    
            // Supprimer le fichier existant s'il existe
            if (localFile.existsSync()) {
              await localFile.delete();
            }
    
            await localFile.writeAsString(json.encode(jsonData));
    
            final localImagePath = '${localDir.path}/images';
    
            List<Map<String, dynamic>> updatedJsonData = [];
    
            for (var jsonItem in jsonData.values) {
              if (jsonItem is Map<String, dynamic>) {
                final imageUrl = jsonItem['image'];
                final imageName = imageUrl.split('/').last;
                final imageFile = File('$localImagePath/$imageName');
    
                final imageResponse = await http.get(Uri.parse(imageUrl));
    
                if (imageResponse.statusCode == 200) {
                  await imageFile.writeAsBytes(imageResponse.bodyBytes);
                  jsonItem['image'] = imageFile.path;
                }
    
                updatedJsonData.add(jsonItem);
              }
            }
    
            print('Updated JSON Data: $updatedJsonData'); // Affiche le contenu de updatedJsonData
    
            final updatedLocalFilePath = '${localDir.path}/quiz.json';
            final updatedLocalFile = File(updatedLocalFilePath);
            await updatedLocalFile.writeAsString(json.encode(updatedJsonData));
    
            print('Items updated successfully from API.');
          } else {
            print('HTTP Error: ${response.statusCode}');
            print('Response Body: ${response.body}');
            throw Exception('Failed to update items from API');
          }
        } catch (e) {
          print('Error updating items from API: $e');
        }
      }
    
      Future<List<Item>> loadItemsFromLocalStorage() async {
        try {
          final localDir = await getApplicationDocumentsDirectory();
          final localFilePath = '${localDir.path}/quiz.json';
    
          final jsonData = await File(localFilePath).readAsString();
          final jsonItems = json.decode(jsonData) as List<dynamic>;
    
          final itemList = jsonItems.map((jsonItem) {
            print('JSON Item: $jsonItem'); // Affiche le JSON extrait
            return Item.fromJson(jsonItem);
          }).toList();
    
          print('Number of items: ${itemList.length}'); // Affiche le nombre d'éléments
    
          return Future.value(itemList);
        } catch (e) {
          print('Error loading items from local storage: $e');
          return []; // Retourne une liste vide en cas d'erreur
        }
      }
    
    }
    

    lorsque je valide tout est ok sauf souci le json generer est vide, j'ai bien verifier le json contient dans element lorsqu'il est generer sur le server mais vide lorsqu'il est enregister dans mon emulateur android studio et donc ma page est egalement vide.

    • Partager sur Facebook
    • Partager sur Twitter

    détermination réussite savoir 

    flutter api json est vide

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown