Home > Software engineering >  flutter await does not wait in initState
flutter await does not wait in initState

Time:03-06

I'm new to flutter , so i'm not sure my way of coding is correct.

I'm trying to get data from firebase , and want to load it in initState(). But, it can not wait. whlie the process is in await, it starts to build. How can I load data before build. Thanks

These are the codes and logs.

import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/entity/quiz.dart';

import '../result.dart';

class Question extends StatefulWidget {
  @override
  _QuestionState createState() => _QuestionState();
}

class _QuestionState extends State<Question> {
  @override
  void initState() {
    print("init State");
    super.initState();
    Future(() async {
      await Future.delayed(Duration(seconds: 5));
    });
    setQuiz();
  }

  List<Quiz> quiz = [];

  Future<void> setQuiz() async {
    // 検索結果は、一旦はFuture型で取得
    Future<QuerySnapshot<Map<String, dynamic>>> snapshot =
        FirebaseFirestore.instance.collection("quiz").get();
    print("inSetQuiz");

    // ドキュメントを取得
    quiz = await snapshot.then(
        (event) => event.docs.map((doc) => Quiz.fromDocument(doc)).toList());
    // await snapshot.then((value) {
    //   setState(() {
    //     quiz = value.docs.map((doc) => Quiz.fromDocument(doc)).toList();
    //   });
    // });

    print("afterSetQuiz");
    print("hoge"   quiz.length.toString());

    print("hoge"   quiz.elementAt(0).sentence);
  }

  // 問題番号
  int questionNumber = 0;

  // 正解問題数
  int numOfCorrectAnswers = 0;

  @override
  Widget build(BuildContext context) {
    print("in build");
    return Scaffold(
        appBar: AppBar(
          title: Text("問題ページ"),
        ),
        body: Center(
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
          Container(
            height: 50,
            color: Colors.red,
            child: const Center(
              child: Text(
                "一旦",
                style: TextStyle(fontSize: 20),
              ),
            ),
          ),
          Container(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                quiz.elementAt(questionNumber).sentence, ←error happens
                style: TextStyle(fontSize: 20),
              )),
omit

here logs↓

flutter: init State
flutter: inSetQuiz
flutter: in build

It load build before await function.

CodePudding user response:

You shouldn't be holding off the initState method. This message straight from a Flutter error says it all: "the initState method must be a void method without an async keyword; rather than waiting on asynchronous work directly inside of initState, just call a separate method to do this work without awaiting it".

That's what a FutureBuilder is for. I'd refactor the app this way:

  1. Keep your setQuiz method async, but return not a void Future, but a Future that wraps the data this method returns (in your case, a quiz).
Future<List<Quiz>> setQuiz() {

  // your existing code, just at the end do:
  return quiz;
}
  1. Feed the return of the setQuiz async method into a FutureBuilder widget:

@override
  Widget build(BuildContext context) {
    print("in build");
    return Scaffold(
        appBar: AppBar(
          title: Text("問題ページ"),
        ),
        body: FutureBuilder(
          future: setQuiz(),
          builder: (context, snapshot) {
            
             if (snapshot.hasData) {
   
               // out of the FutureBuilder's snapshot, collect the data
               var quiz = snapshot.data as List<Quiz>;

               // build your quiz structure here
               return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                         height: 50,
                         color: Colors.red,
                         child: const Center(
                            child: Text("一旦",
                              style: TextStyle(fontSize: 20),
                            ),
                         ),
                       ),
                       ListView.builder(
                         itemCount: quiz.length,
                         itemBuilder: (context, index) {
                            var singleQuestion = quiz[index];    
                            
                            return Text(singleQuestion.sentence);                     
                         }
                       )
                     ]
                   )
                 );
             }
             
             // while waiting for data to arrive, show a spinning indicator
             return CircularProgressIndicator();
          }
        )
    );
}
  • Related