变量不会超出范围

变量不会超出范围

本文介绍了变量不会超出范围,不会发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个未来<动态>对象列表和对象列表,我正在访问Future<动态>使用'.then'列出,在同一范围内,我将对象添加到对象列表中。这是代码:

i have a Future< dynamic > List and List of objects , i am accessing the Future < dynamic > List using '.then' and in the same scope i am adding objects into the List of objects . This is the code :

   List<Etablissement> etablist = new List<Etablissement>() ;
   //AfficherEtablissement() returns Future<dynamic>
    etabController.AfficherEtablissement().then((value) =>
    value.forEach((entry) {
      int id = entry["id"];
      Etablissement et = new Etablissement(id);
      this.etablist.add(et) ;
      print("etablist length inside the loop "+etablist.length().toString());
    })
    ) ;
      print("etablist length outside the loop "+etablist.length().toString());

循环内部的etablist长度为prinitng'2',因此有一些对象被添加到列表中,但不在循环范围内

the etablist length inside the loop is prinitng '2' so there are objects being added to the list but outside the loop scope it's empty like nothing has been added .

推荐答案

然后是一个 async 调用,该调用未按顺序调用,这就是为什么第二个打印语句未给出长度的原因

then is an async call which not called sequentially, that why the second print statement is not giving length

用法:

@override
  void initState() {
    super.initState();
    asyncInitState(); // async is not allowed on initState() directly
  }

  void asyncInitState() async {
     var value = await etabController.AfficherEtablissement();
    value.forEach((entry) {
      int id = entry["id"];
      Etablissement et = new Etablissement(id);
      this.etablist.add(et) ;
      print("etablist length inside the loop "+etablist.length().toString());
    })
      print("etablist length outside the loop "+etablist.length().toString());
  }

这篇关于变量不会超出范围,不会发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:39