Home > database >  Store a api response data in firebase collections using flutter
Store a api response data in firebase collections using flutter

Time:02-12

So, I have been making a post request to a REST API and I want to store the response data in the firebase cloud store collection. What I have done so far: I have created the model class for the response data and have written a function that will make this post-call.

I am not getting any such error but still, neither the response is getting printed in the console nor the data is being uploaded in the firebase. Also, I have checked with almost all the StackOverflow questions that relate to my kind of problem.

Herewith I am attaching my code snippets:

Function: //This function is only not getting called I don't know why.

final List<KycDetails> _kyc = [];
  Dio dio = Dio();
  TextEditingController aadhar = TextEditingController();
  Future<List<KycDetails>> postData() async {
    const String pathUrl = 'https://jsonplaceholder.typicode.com/posts';
    dynamic data = {'title': aadhar.text, 'body': 'Flutter', 'userId': 1};
    List<KycDetails> details = [];
    var response = await dio.post(pathUrl,
        data: data,
        options: Options(
            headers: {'Content-Type': 'application/json; charset=UTF-8'}));
    if (response.statusCode == 200) {
      print('ok');
      var urjson = jsonDecode(response.data);
      for (var jsondata in urjson) {
        details.add(KycDetails.fromJson(jsondata));
      }
    }
    return details;
  }

Widget where I am calling the function and storing the data in firebase

     InkWell( 
                  hoverColor: Colors.red,
                  onTap: () async {
                    print('API CALLING');
                    await postData().then((value) {
                      setState(() {
                        _kyc.addAll(value);
                      });
                      print(value);
                      
                    });
                    Map<String, String> data = {
                      "aadhar": aadhar.text,
                      "title": _kyc[0].title,
                      "userId": _kyc[0].userId.toString(),
                    };
                    FirebaseFirestore.instance.collection('kyc').add(data);
                  },
                  child: const Text('Submit'),
                ),

API response data:

{"title": "resume", "body": "Flutter", "userId": 1, "id": 101}

Model Class:

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

  String title;
  String body;
  int userId;
  int id;

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

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

I hope I have provided you with the necessary information Am stuck on this problem for quite a few days Would appreciate it if anyone can solve my problem considering my code.

CodePudding user response:

For starters, when you make a post request the success code you're looking for is 201 indicating that a resource has been successfully created.

So nothing in this code block will run.

   if (response.statusCode == 200) {
      print('ok');
      var urjson = jsonDecode(response.data);
      for (var jsondata in urjson) {
        details.add(KycDetails.fromJson(jsondata));
      }
    }

response.data doesn't need jsonDecode here. It returns in the form of a map so you can cast it as such.

So this

var urjson = jsonDecode(response.data);

can be this

final urjson = response.data as Map<String, dynamic>;

As for this line

   for (var jsondata in urjson) {
        details.add(KycDetails.fromJson(jsondata));
      }

The response is a single map, not a list. That single map is in the form of your KycDetails model so you don't need to loop through anything.

So you can create your object with your fromJson method.

final kycDetail = KycDetails.fromJson(urjson);

Then you can just do this to add a properly initiated KycDetails object to the list.

details.add(kycDetail);

If all you're trying to do is add a single object to Firebase then none of this in your onTap is necessary. Also trying to access the property at index 0 will not be the most recent addition to the list. You'd need to add the index of the last item in the list.

Map<String, String> data = {
  "aadhar": aadhar.text,
  "title": _kyc[0].title,
  "userId": _kyc[0].userId.toString(),
};

FirebaseFirestore.instance.collection('kyc').add(data);

You can just add to Firebase from your postData function.

  if (response.statusCode == 201) {
    print('ok');
    final urjson = response.data as Map<String, dynamic>;
    final kycDetail = KycDetails.fromJson(urjson);
    details.add(kycDetail);
    FirebaseFirestore.instance.collection('kyc').add(kycDetail.toJson());
  }
  • Related