状态初始化时如何进行API调用并加载数据?

时间:2019-06-13 11:41:34

标签: flutter

我想在初始化列表时通过调用API来填充列表。但是,由于init不是异步函数,因此无法将值加载到列表中。我怎样才能做到这一点?



class _CreateTaskScreenState extends State<CreateTaskScreen>{

 // List<Society> societies;

  @override
  void initState() {

    //societies = await getAllSocieties();

    super.initState();
  }

  Future<List<Society>> getAllSocieties() async{
   //API CALL 
  }


    return Scaffold(
....
    );
  }

}


1 个答案:

答案 0 :(得分:0)

创建异步函数/方法:

override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        val i = Intent()
        when (item.itemId) {
            R.id.nav_current_workout -> {
                i.setClass(this, CurrentWorkoutActivity::class.java)
                startActivity(i)
            }
            R.id.nav_log -> {
                //similarly start activity with Intent 
            }
            R.id.nav_exercises -> {}
            R.id.nav_workouts -> {}
            R.id.nav_stats -> {}
            R.id.nav_settings -> {}
        }
        val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
        drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }
}

并从您的methodDoStuff()async{}

调用
InitState();

并使用setState()将其填充到方法本身中:

 @override
 void initState() {

     methodDoStuff();

    super.initState();
 }