Home > Blockchain >  The instance member 'test' can't be accessed in an initializer (Flutter)
The instance member 'test' can't be accessed in an initializer (Flutter)

Time:11-03

I am trying to create a quiz app in flutter, the idea is that I have a JSON file that describes the questions to ask, and I should read the JSON files and print out the questions in my app, I can read the JSON file just fine but when I try to print it out to the app I get the error above

I read the Json file like so:`

   var  items = [];

   

  /********** Function to read Json file **************************/
  @override
  void initState() {
    super.initState();
    readJson();


  }
  Future<void> readJson() async
  {

    final String response = await rootBundle.loadString('assets/questions.json');
    final data = await json.decode(response);

    setState(() {
      items = data["Questions"];

    });

    print(items);
    print(items[0]);
/*****************************************************************/


  }

The file is read correctly, since the data is printed correctly in the console, however, when I try to use it in a Text Widget like so:

Widget question = Column(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [
    Container(
      margin:
          const EdgeInsets.only(left: 20.0, right: 20.0, top: 40, bottom: 30),
      alignment: Alignment.centerLeft,
      child: const Text(
        "Question 1:",
        style: TextStyle(
            fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white),
      ),
    ),
    Container(
      alignment: Alignment.center,
      margin: const EdgeInsets.only(bottom: 80),
      child:   Text(
        items[0]["description"]
       /* style: TextStyle(
            fontWeight: FontWeight.w500, fontSize: 30, color: Colors.white),*/
      ),
    )
  ],
);

I get the error above, any ideas? thank you `

CodePudding user response:

you can't access a variable outside the build method. if you are creating a helper method, enclose it with a function like so for you to be able to access variables.

Widget question() => Column(
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  children: [
    Container(
      margin:
          const EdgeInsets.only(left: 20.0, right: 20.0, top: 40, bottom: 30),
      alignment: Alignment.centerLeft,
      child: const Text(
        "Question 1:",
        style: TextStyle(
            fontWeight: FontWeight.bold, fontSize: 16, color: Colors.white),
      ),
    ),
    Container(
      alignment: Alignment.center,
      margin: const EdgeInsets.only(bottom: 80),
      child:   Text(
        items[0]["description"]
       /* style: TextStyle(
            fontWeight: FontWeight.w500, fontSize: 30, color: Colors.white),*/
      ),
    )
  ],
);

  • Related