Home > database >  I tried to fetch data from firestore but in the console show empty array on flutter
I tried to fetch data from firestore but in the console show empty array on flutter

Time:10-15

I tried to fetch data from firestore to chips but the console showed an empty array. And when click chips colour change to blue colour.To fetch data I used model that's class name "Words12" My collection name is "12words" at that collection have two fields "wordName"and "categoryName". I want display only "wordName" as chips

this..

I/flutter (14273): []

my full code

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:kathana/utils/config.dart';

import '../screens/wordsBefore18/database/words12model.dart';

class uitry4 extends StatefulWidget {
  const uitry4({Key? key}) : super(key: key);

  @override
  State<uitry4> createState() => _uitry4State();
}

class _uitry4State extends State<uitry4> {
  List<Words12> wordList = [];
  Future<List<Words12>> fetchRecords() async {
    var records = await FirebaseFirestore.instance.collection('12words').get();
    return mapRecords(records);
  }

  List<Words12> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
    var _wordList =
        records.docs.map((data) => Words12.fromJson(data.data())).toList();

    return _wordList;
  }

  @override
  void initState() {
    super.initState();
    print(wordList);
  }

  List<String> selectedWord = [];
  List<String>? deSelectedWord = [];

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage(Config.app_background4), fit: BoxFit.fill),
        ),
        child: SafeArea(
            child: Center(
                child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 14, right: 0),
              child: Column(
                children: [
                  SizedBox(
                    width: width * 0.94,
                    height: height * 0.30,
                    child: Column(
                      children: <Widget>[
                        const SizedBox(height: 16),
                        FutureBuilder<List<Words12>>(
                            future: fetchRecords(),
                            builder: (context, snapshot) {
                              if (snapshot.hasError) {
                                return Text('Error: ${snapshot.error}');
                              } else {
                                wordList = snapshot.data ?? [];

                                return Wrap(
                                  children: wordList.map(
                                    (word) {
                                      bool isSelected = false;
                                      if (selectedWord!
                                          .contains(word.wordName)) {
                                        isSelected = true;
                                      }
                                      return GestureDetector(
                                        onTap: () {
                                          if (!selectedWord!
                                              .contains(word.wordName)) {
                                            if (selectedWord!.length < 50) {
                                              selectedWord!.add(word.wordName);
                                              deSelectedWord!.removeWhere(
                                                  (element) =>
                                                      element == word.wordName);
                                              setState(() {});
                                              print(selectedWord);
                                            }
                                          } else {
                                            selectedWord!.removeWhere(
                                                (element) =>
                                                    element == word.wordName);
                                            deSelectedWord!.add(word.wordName);
                                            setState(() {
                                              // selectedHobby.remove(hobby);
                                            });
                                            print(selectedWord);
                                            print(deSelectedWord);
                                          }
                                        },
                                        child: Container(
                                          margin: const EdgeInsets.symmetric(
                                              horizontal: 5, vertical: 4),
                                          child: Container(
                                            padding: const EdgeInsets.symmetric(
                                                vertical: 5, horizontal: 12),
                                            decoration: BoxDecoration(
                                                color: isSelected
                                                    ? HexColor('#0000FF')
                                                    : HexColor('#D9D9D9'),
                                                borderRadius:
                                                    BorderRadius.circular(18),
                                                border: Border.all(
                                                    color: isSelected
                                                        ? HexColor('#0000FF')
                                                        : HexColor('#D9D9D9'),
                                                    width: 2)),
                                            child: Text(
                                              word.wordName,
                                              style: TextStyle(
                                                  color: isSelected
                                                      ? Colors.black
                                                      : Colors.black,
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w600),
                                            ),
                                          ),
                                        ),
                                      );
                                    },
                                  ).toList(),
                                );
                              }
                            }),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ))),
      ),
    );
  }
}

model

import 'dart:convert';

Words12 words12FromJson(String str) => Words12.fromJson(json.decode(str));

String words12ToJson(Words12 data) => json.encode(data.toJson());

class Words12 {
  Words12({
    required this.id,
    required this.wordName,
    required this.categoryName,
  });
  String id;
  String wordName;
  String categoryName;

  factory Words12.fromJson(Map<String, dynamic> json) => Words12(
        id: json["id"],
        wordName: json["wordName"],
        categoryName: json["categoryName"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "wordName": wordName,
        "categoryName": categoryName,
      };
}

How I get data from firestore?

CodePudding user response:

Try change mapRecords() to this :

List<Words12> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
    var _wordList = records.docs
        .map(
          (data) => Words12.fromJson(data.data()) 
        )
        .toList();

    return _wordList;
}

and also change your if condition in your FutureBuilder:

if (snapshot.hasError) {
       return Text('Error: ${snapshot.error}');
} else {
  wordList = snapshot.data ?? []; //<--- change this
  ...
}

also change wordList to this:

class _uitry4State extends State<uitry4> {
  List<Words12> wordList = []; //<--- change this
  ...
}

and this:

children: wordList.map(
    (word) {
        bool isSelected = false;
        if (selectedWord!.contains(word.wordName)) {
           isSelected = true;
        }
        return GestureDetector(
             onTap: () {
                if (!selectedWord!.contains(word.wordName)) {
                    if (selectedWord!.length < 50) {
                        selectedWord!.add(word.wordName);        
                        deSelectedWord!.removeWhere(
                            (element) => element == word.wordName);
                        setState(() {});
                        print(selectedWord);
                    }
                } else {
                   selectedWord!.removeWhere(
                       (element) => element == word.wordName);
                   deSelectedWord!.add(word.wordName);
                   setState(() {
                          // selectedHobby.remove(hobby);
                   });
                   print(selectedWord);
                   print(deSelectedWord);
                }
             },
             child: Container(
                 margin: const EdgeInsets.symmetric(horizontal: 5, vertical: 4),
                 child: Container(
                             padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 12),
                             decoration: BoxDecoration(
                                    color: isSelected ? HexColor('#0000FF'): HexColor('#D9D9D9'),
                                    borderRadius: BorderRadius.circular(18),
                                    border: Border.all(
                                            color: isSelected ? HexColor('#0000FF') : HexColor('#D9D9D9'),
                                            width: 2)),
                             child: Text(
                                 word.wordName,
                                 style: TextStyle(color: isSelected
                                                      ? Colors.black
                                                      : Colors.black,
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w600),
                                 ),
                             ),
              ),

CodePudding user response:

Just convert

 List<Words12> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
    var wordList = records.docs
        .map(
          (words12) => Words12(
            id: words12.id,
            wordName: words12['wordName'],
            categoryName: words12['categoryName'],
          ),
        )
        .toList();

    return wordList;
  }

to

 List<Words12> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
    var wordList = records.docs
        .map(
          (words12) { 
           print(words12);
          return
           Words12(
            id: words12.id,
            wordName: words12['wordName'],
            categoryName: words12['categoryName']
        );}
        .toList();

    return wordList;
  }

and check what you get , also on a sidenote the way your using FutureBuilder is not ideal

Future _fetch = Future(() async {
    var records = await FirebaseFirestore.instance.collection('12words').get();
    return mapRecords(records);
  })
  • Related