Home > database >  Cannot display fetched data to the UI in Flutter
Cannot display fetched data to the UI in Flutter

Time:09-29

I tried to fetch data as List from database but data not display in UI. How I fix this? I tried fetch data using model class and my collection name is '12words'.

UI code:

class _WordsScreenState extends State<WordsScreenState> {
  List<Words12> wordList = [];
  @override
  void iniState() {
    fetchRecords();
    iniState();
  }

  fetchRecords() async {
    var records = await FirebaseFirestore.instance.collection('12words').get();
    mapRecords(records);
  }

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

    setState(() {
      wordList = _list;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: ListView.builder(
          itemCount: wordList.length,
          itemBuilder: (context, index) {
            return (ListTile(
              title: Text(wordList[index].wordName),
              subtitle: Text(wordList[index].categoryName),
            ));
          },
        ));
  }

Model: image

CodePudding user response:

First do not call async function in initState, instead of that, use FutureBuilder and also change your fetchRecords() to return a list. This is a full example of using FutureBuilder with your code:

class TestFuture extends StatefulWidget {
  const TestFuture({super.key});

  @override
  State<TestFuture> createState() => _TestFutureState();
}

class _TestFutureState extends State<TestFuture> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: FutureBuilder<List<Words12>>(
        future: fetchRecords(),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Text('Loading....');
            default:
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                List<Words12> data = snapshot.data ?? [];

                return ListView.builder(
                  itemCount: data.length,
                  itemBuilder: (context, index) {
                    return (ListTile(
                      title: Text(data[index].wordName),
                      subtitle: Text(data[index].categoryName),
                    ));
                  },
                );
              }
          }
        },
      ),
    );
  }

  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 _list = records.docs
        .map(
          (words12) => Words12(
            id: words12.id,
            wordName: words12['wordName'],
            categoryName: words12['categoryName'],
          ),
        )
        .toList();

    return _list;
  }
}
  • Related