Search code examples
flutterdartdart-null-safety

I tried to get data from firestore but display this error "The instance member 'mapRecords' can't be accessed in an initializer. " on Flutter


I tried to get data from firestore but display this error "The instance member 'mapRecords' can't be accessed in an initializer. " on Flutter.

Screenshots of errors

https://drive.google.com/drive/folders/1toBdn9h4-LgBLl5ybG63brgXmk5G0h3F?usp=sharing

my 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 uitry5 extends StatefulWidget {
  const uitry5({Key? key}) : super(key: key);

  @override
  State<uitry5> createState() => _uitry5State();
}

class _uitry5State extends State<uitry5> {

  List<String> wordList = [];

  Future _fetch = Future(() 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(
            (words12) {
          print(words12);
          return
            Words12(
                id: words12.id,
                wordName: words12['wordName'],
                categoryName: words12['categoryName']
            );}
            .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),

                                Wrap(
                                  children: wordList.map(
                                    (word) {
                                      bool isSelected = false;
                                      if (selectedWord!.contains(word)) {
                                        isSelected = true;
                                      }
                                      return GestureDetector(
                                        onTap: () {
                                          if (!selectedWord!.contains(word)) {
                                            if (selectedWord!.length < 50) {
                                              selectedWord!.add(word);
                                              deSelectedWord!.removeWhere(
                                                  (element) => element == word);
                                              setState(() {});
                                              print(selectedWord);
                                            }
                                          } else {
                                            selectedWord!.removeWhere(
                                                (element) => element == word);
                                            deSelectedWord!.add(word);
                                            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,
                                              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 do I resolve this and get data from the database


Solution

  • You can use late before future.

     late Future _fetch = ...
    

    Also I will prefer shifting mapRecords before _fetch and FutureBuilder for future.