Flutter : Maps et Json

1°) Utilisation du type MAP :

Les données map dans Dart sont une collection de paires clé-valeur. Chaque valeur est associée à une clé, ce qui signifie que chaque clé doit être unique, mais la même valeur peut être utilisée plusieurs fois . Deux éléments possédant la même valeur resteront uniques en ayant des clés distinctes.

var nombres = Map<int, String>(); 
nombres[1] = "Un"; 
nombres[2] = "Deux"; 
nombres[3] = "Trois"; 
nombres[4] = "Quatre"; 
print("nombres = $nombres");
Donne : nombres = {1: Un, 2: Deux, 3: Trois, 4: Quatre}
print(nombres.length);
Donne : 4

Pour afficher toutes les clefs et les valeurs :
print("Les clés sont : ${nombre.keys}");
print("Les valeurs sont : ${mombre.values}");

MAP dynamic :

Références :

2°) Utilisation du JSON :

JavaScript Object Notation (JSON) est un format de données textuelles dérivé de la notation des objets du langage JavaScript. Il permet de représenter de l’information structurée. Très utilisé pour les APIs

Références :

https://codewithandrea.com/articles/parse-json-dart/

3°) Récupération du résultat d’une API (liste de données) :

Référence : https://docs.flutter.dev/cookbook/networking/fetch-data

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<List<Album>> fetchAlbum() async {
  final response =
      await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
  // Reponse is a list of data Json [{"userId": 1,"id": 1,"title": "quidem molestiae enim"},
  // {"userId": 2,"id": 2,"title": "sunt qui excepturi placeat culpa"},
  if (response.statusCode == 200) {
    // If the server did return a 200 OK response, then parse the JSON.
    Iterable l = json.decode(response.body);
    List<Album> posts =
        List<Album>.from(l.map((model) => Album.fromJson(model)));
    //print(posts[0].title);
    return (posts);
  } 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;

  const Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

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> {
  @override
  void initState() {
    super.initState();
  }

  @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(
            future: fetchAlbum(),
            builder: (context, AsyncSnapshot snapshot)  {
              switch (snapshot.connectionState) {
                case ConnectionState.waiting: return Center(child: CircularProgressIndicator());
                default:
                  if (snapshot.hasError)
                    return Text('Error: ${snapshot.error}');
                  else
                    return //Text('Result: ${snapshot.data}');
                      ListView.builder(
                          itemCount: snapshot.data.length,
                         // scrollDirection: Axis.horizontal,
                          itemBuilder: (BuildContext context, int index) {
                            return Text('${snapshot.data[index].title}');
                          });
              }
            },
          ),
        ),
      ),
    );
  }
}

Stockage du résultat de l’API dans une base de données :

AndroidManifest.xml :

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

pubsepc.yaml :

  sqflite: ^2.0.2
  path_provider: ^2.0.9
  http: ^0.13.4

Fichier stationsclass.dart :

import 'dart:convert';

class Radios {
  Radios({
    required this.userId,
    required this.id,
    required this.title,
  });

  int userId;
  int id;
  String title;

  factory Radios.fromMap(Map<String, dynamic> json) => Radios(
    userId: json["userId"],
    id: json["id"],
    title: json["title"],
  );

  Map<String, dynamic> toMap() => {
    "userId": userId,
    "id": id,
    "title": title,
  };
}

Fichier Sqlite.dart

import 'dart:convert';
import "dart:io" as io;
import 'package:androdblite/stationsclass.dart';
import "package:path/path.dart";
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;

class SqliteDB {
  static final SqliteDB _instance = new SqliteDB.internal();
  factory SqliteDB() => _instance;
  static Database? _db;
  Future<Database?> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();
    return _db;
  }

  SqliteDB.internal();

  /// Initialize DB
  initDb() async {
    io.Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, "RadiosStations.db");
    var taskDb = await openDatabase( //open the database or create a database if there isn't any
        path,
        version: 1,
        onCreate: (Database db,int version) async{
          await db.execute("""
          CREATE TABLE Radios(
          id     INTEGER,
          userid INTEGER,
          title  TEXT)"""
          );
        });
    return taskDb;
    //Pour id automatique : id     INTEGER PRIMARY KEY AUTOINCREMENT,
  }

  /// Batch insert data
  //-- Save API Result in DataBase
  Future StoreDataList(String lignesJson) async {
    List JsonList = json.decode(lignesJson);
    final dbClient = await SqliteDB().db;
    /// Initialize batch
    final batch = dbClient?.batch();
    JsonList.forEach((val) {
      Radios ligneradio = Radios.fromMap(val);
      batch!.insert("Radios", ligneradio.toMap());
      //print(ligneradio.toMap());
    });
    /// Commit
    await batch!.commit(noResult: true);
    return "success";
  }

  //////////////////
  // Retrieve all the data stored in dB
    Future<List<Radios>> retrieveAllRadios() async{ //returns the memos as a list (array)
       //-- Delete data if exists
      await deleteAll();
      //-- First, fetch the Data from the API and Store it in the DataBase
      await ReadWriteDataList();
      //-- Then display the DataBase
      final db = await initDb();
      final maps = await db.query("Radios"); //query all the rows in a table as an array of maps
      //await db.close();
      return List.generate(maps.length, (i) { //create a list of memos
        return Radios(
          id: maps[i]['id'] as int,
          userId: maps[i]['userid'] as int,
          title: maps[i]['title'] as String,
        );
      });
    }

  /// Get all users using raw query
  Future getAll() async {
    var dbClient = await SqliteDB().db;
    final res = await dbClient?.rawQuery("SELECT * FROM Radios");
    return res;
  }

  /// Simple query with WHERE raw query
  Future getAdults() async {
    var dbClient = await SqliteDB().db;
    final res = await dbClient?.rawQuery("SELECT id, name FROM Radios WHERE age > 18");
    return res;
  }

  /// deleteAllDatas
  Future deleteAll() async {
    var dbClient = await SqliteDB().db;
    final res = await dbClient?.rawQuery("DELETE from Radios");
    return res;
  }
  //::::::::::::::::::::::::::::
  Future ReadWriteDataList() async {
    //-- Initialize sq-lite
    final db = await initDb();
    final response =
    await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
    // Reponse is a list of data Json [{"userId": 1,"id": 1,"title": "quidem molestiae enim"},
    // {"userId": 2,"id": 2,"title": "sunt qui excepturi placeat culpa"},
    if (response.statusCode == 200) {
      // If the server did return a 200 OK response, then parse the JSON.
      String resApi = response.body;
      //print (resApi);
      //-- Insert Data into DB
      await StoreDataList(resApi);
    } else {
      // If the server did not return a 200 OK response, then throw an exception.
      throw Exception('Failed to load data');
    }
  }
}

Fichier main.dart :

import 'dart:async';
import 'dart:convert';
import 'package:androdblite/stationsclass.dart';
import 'package:flutter/material.dart';

import 'package:androdblite/sqlite.dart';
//////////
// Retrieve Data from API, store it in a database
// Display data from the database
//////

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  //-- Initialize sq-lite
  final db = SqliteDB();
  @override
  void initState() {
    super.initState();
  }
  @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(
            future: db.retrieveAllRadios(), //fetchAlbum(),
            builder: (context, AsyncSnapshot snapshot)  {
              switch (snapshot.connectionState) {
                case ConnectionState.waiting: return Center(child: CircularProgressIndicator());
                default:
                  if (snapshot.hasError)
                    return Text('Error: ${snapshot.error}');
                  else
                    return //Text('Result: ${snapshot.data}');
                      ListView.builder(
                          itemCount: snapshot.data.length,
                         // scrollDirection: Axis.horizontal,
                          itemBuilder: (BuildContext context, int index) {
                            return Text('${snapshot.data[index].title}');
                          });
              }
            },
          ),
        ),
      ),
    );
  }
}

https://thewebstorebyg.wordpress.com/2020/05/04/storing-rest-api-response-on-flutter-app-with-sqlite/

https://www.kindacode.com/article/how-to-fetch-data-from-apis-in-flutter/

Affichage de données d’une base dans une listview :

….

  Future<List<Employee>> getEmployees() async {
    var dbClient = await db;
    List<Map> list = await dbClient.rawQuery('SELECT * FROM Employee');
    List<Employee> employees = new List();
    for (int i = 0; i < list.length; i++) {
      employees.add(new Employee(list[i]["firstname"], list[i]["lastname"], list[i]["mobileno"], list[i]["emailid"]));
    }
    print(employees.length);
    return employees;
  }



https://www.kindacode.com/article/flutter-sqlite/

https://camposha.info/flutter/fr/flutter-sqflite/#gsc.tab=0

https://stackoverflow.com/questions/71158459/fetch-data-from-an-api-and-save-in-an-sqlite-database-flutter-dart-android

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