how can I retrieve the list of my card models here named "CardModele"

Viewed 41

I would like to be able to retrieve the "CardModele" list. which is inside the "Cart" class. Please kindly help me.

the responses from the API

{
    "MontantTotal": 264775,
    "MontantMaxLivraible": 20825,
    "qteMax_Livrable": "35",
    "prd": "essence",
    "id_entite_frs": "TG01-63189572",
    "id_entite_conso": "TGO36742859",
    "id_souscription": "TG01-63189572TGO367428597586AX",
    "CardModele": [
        {
            "id_model_card": "52893-TG01-63189572",
            "name_model_card": "Silver",
            "libelle": "Carburant",
            "id_opeartion_modCard": "49a813f11634468f3039d79460f27284b48f0d9b"
        },
        {
            "id_model_card": "52893-TG01-63189572",
            "name_model_card": "Silver",
            "libelle": "Entretien",
            "id_opeartion_modCard": "799eec86af09f5015f35663ae4769c0ba3db5467"
        }
    ]
}

My code

import 'dart:convert';

import 'package:argon_flutter/screens/Selling.dart';
import 'package:argon_flutter/screens/carteContent.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:scan/scan.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'Constantes.dart';
import 'login.dart';

class ScanPage extends StatefulWidget {
  @override
  _ScanPageState createState() => _ScanPageState();
}
class _ScanPageState extends State<ScanPage> {
  ScanController Qrscan = ScanController();
  SharedPreferences sharedPreferences;
  dynamic responserecuID;
  String RecupCardId;
  String Device;
  String Usertoken;
  var Idcard ;




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: true,
        bottom: true,
        child: Stack(
          children: [
            ScanView(
              controller: Qrscan,
              scanAreaScale: .7,
              scanLineColor: Colors.green,
              onCapture: (data) {
                this.Idcard = (data);
                print("ID est "+Idcard);
                _validator();
                // .then((value) {
                Qrscan.resume();
                // });
              },
            ),
            Positioned(
              bottom: 0,
              left: 0,
              child: Row(
                children: [
                  ElevatedButton(
                    child: Text("Torch"),
                    onPressed: () {
                      Qrscan.toggleTorchMode();
                    },
                  ),
                  ElevatedButton(
                    child: Text("pause"),
                    onPressed: () {
                      Qrscan.pause();
                    },
                  ),
                  ElevatedButton(
                    child: Text("Scan"),
                    onPressed: () {
                      Qrscan.resume();
                    },
                  ),
                ],
              ),
            ),

          ],
        ),
      ),
    );
  }

  _validator() async {
    sharedPreferences  = await SharedPreferences.getInstance();
    //print("element saisie" + TpeId.text );
    sharedPreferences.setString('ScanIDKey',Idcard);

    Qrscan.pause();
    getValidator();

  }
  Future getValidator() async {
    sharedPreferences = await SharedPreferences.getInstance();
    Device = sharedPreferences.getString('valideKey');
    Usertoken = sharedPreferences.getString('userid');
    await http.get(Uri.parse(Constantes.scannerUrl+
        Device+"&id_card="+Idcard
        +"&user_token="+Usertoken)).then((response) {
      setState(() {
        responserecuID = (response.body);
        String objText = responserecuID;
        Cart reponse = Cart.fromJson(jsonDecode(objText));
        print(reponse.my_alert);
        sharedPreferences.setString('Qtelvr',reponse.qteMax_Livrable);
        sharedPreferences.setInt('Mttlvr',reponse.MontantMaxLivraible);
        sharedPreferences.setInt('Mttotal',reponse.MontantTotal);
        sharedPreferences.setString('RefPdt',reponse.prd);
        sharedPreferences.setString('SousId',reponse.id_souscription);

        if(reponse.id_souscription != null && reponse.qteMax_Livrable != null) {
          Navigator.of(context).pushAndRemoveUntil(
              new MaterialPageRoute(
                  builder: (BuildContext context) => new carteContent()),
                  (Route<dynamic> route) => false);
            }else {
          showDialog(
              builder: (context) => new CupertinoAlertDialog(
                content: new Text(
                  reponse.my_alert,
                  style: new TextStyle(fontSize: 16.0),
                ),
                actions: <Widget>[
                  new FlatButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: new Text("OK"))
                ],
              ),
              context: context,
              barrierDismissible: false);
        }
      });

    });
 }
}
class Cart {
  int MontantTotal;
  int MontantMaxLivraible;
  String qteMax_Livrable;
  String prd;
  String id_entite_frs;
  String id_entite_conso;
  String id_souscription;
  List<CartMod>CardModele;
  String my_alert;
  String type_alert;
  String titre_alert;
  Cart(
      this.MontantTotal,
      this.MontantMaxLivraible,
      this.qteMax_Livrable,
      this.prd,
      this.id_entite_frs,
      this.id_entite_conso,
      this.id_souscription,
       this.CardModele,
      this.my_alert,
      this.type_alert,
      this.titre_alert);

  factory Cart.fromJson(dynamic json) {
    return Cart(
        json['MontantTotal'] as int,
        json['MontantMaxLivraible'] as int,
        json['qteMax_Livrable'] as String,
        json['prd'] as String,
        json['id_entite_frs'] as String,
        json['id_entite_conso'] as String,
        json['id_souscription'] as String,
         json['CardModele'] as List ,
        json['my_alert'] as String,
        json['type_alert'] as String,
        json['titre_alert'] as String);
  }
  @override
  String toString() {
    return '{ ${this.MontantTotal},  ${this.MontantMaxLivraible}, ${this.qteMax_Livrable},  ${this.prd},${this.id_entite_frs}, ${this.id_entite_conso},${this.id_souscription},${this.CardModele}, ${this.my_alert}, ${this.type_alert}, ${this.titre_alert} }';
  }

}


class CartMod{
  String id_model_card;
  String name_model_card;
  String libelle;
  String id_opeartion_modCard;

}


I manage to recover the other elements of the answers but I have trouble recovering the list which is inside

2 Answers

The thing is that CardModele is a JSON object and it should be converted from JSON to a CartMod instance. The CartMod class needs then a fromJson constructor the same way the Cart class has one.

The following should do the trick:

class Cart {
  int MontantTotal;
  int MontantMaxLivraible;
  String qteMax_Livrable;
  String prd;
  String id_entite_frs;
  String id_entite_conso;
  String id_souscription;
  List<CartMod> CardModele;
  String my_alert;
  String type_alert;
  String titre_alert;
  Cart(
      this.MontantTotal,
      this.MontantMaxLivraible,
      this.qteMax_Livrable,
      this.prd,
      this.id_entite_frs,
      this.id_entite_conso,
      this.id_souscription,
      this.CardModele,
      this.my_alert,
      this.type_alert,
      this.titre_alert);

  factory Cart.fromJson(dynamic json) {
    return Cart(
        json['MontantTotal'] as int,
        json['MontantMaxLivraible'] as int,
        json['qteMax_Livrable'] as String,
        json['prd'] as String,
        json['id_entite_frs'] as String,
        json['id_entite_conso'] as String,
        json['id_souscription'] as String,
        json['CardModele'] == null
            ? []
            : (json['CardModele'] as List)       // <- Here
                .map((j) => CartMod.fromJson(j)) // <- Here
                .toList(),                       // <- Here
        json['my_alert'] as String,
        json['type_alert'] as String,
        json['titre_alert'] as String);
  }
  @override
  String toString() {
    return '{ ${this.MontantTotal},  ${this.MontantMaxLivraible}, ${this.qteMax_Livrable},  ${this.prd},${this.id_entite_frs}, ${this.id_entite_conso},${this.id_souscription},${this.CardModele}, ${this.my_alert}, ${this.type_alert}, ${this.titre_alert} }';
  }
}

class CartMod {
  String id_model_card;
  String name_model_card;
  String libelle;
  String id_opeartion_modCard;

  CartMod.fromJson(dynamic json)                             // <- Here
      : id_model_card = json['id_model_card'],               // <- Here
        name_model_card = json['name_model_card'],           // <- Here
        libelle = json['libelle'],                           // <- Here
        id_opeartion_modCard = json['id_opeartion_modCard']; // <- Here
}

Here CartModele is a list so you have to use

cart.CardModele[0].id_model_card

Here 0 is the index of the element in its list

Related