Home > Mobile >  how to initize late variable in flutter? LateInitializationError
how to initize late variable in flutter? LateInitializationError

Time:08-27

I have an initialization error of my variable late Future<List?> listTest;. I understand that I have an error because I try to use the variable inside a futureBuilder but it has not yet been initialized. I tried to make the variable nullable (Future<List?>? listTest;), giving no more compilation error, but not working in my case.

Searching the internet I saw that I have to initialize it within the void initState, but I didn't understand how to do that. Can anybody help me? Piece of code:

late Future<List<CursoTO>?> listTest;

void initState() {
  super.initState();

  Future.delayed(Duration.zero, () {
    setState(() {
      final routeArgs1 =
          ModalRoute.of(context)!.settings.arguments as Map<String, String>;


    var curso = Curso(); //nao entra aqui
    listTest= curso.lista(
        nomeImagem!,
        idSite!);
     });
   });
  }

  @override
  Widget build(BuildContext context) {
    var futureBuilder = FutureBuilder(
      future: listTest,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
         if (snapshot.hasData) {
           return createScreen(context, snapshot);
          } else if (snapshot.hasError) {
           return Text("${snapshot.error}");
          }
          return const Center(child: CircularProgressIndicator());
         },
        );
    return Scaffold(
        body: futureBuilder);
   }

CodePudding user response:

Try to initialize listTest in constructor. Otherwise make you variable to static and initialize with empty list and aging put value in initstate

CodePudding user response:

From a syntactical perspective (I can't test your code), there's no need to use the keyword late as you're handling the various states of this object in the builder function already. Simply initialise an empty list then update it in the initState() method.


// late Future<List<CursoTO>?> listTest;
Future<List<CursoTO>?> listTest = Future.value([]);
  • Related