I want to use some of the "awaited variables",how can I do?

Viewed 25

I already know the order of await code,now I want to use the variable name which is not null

class Test{
  late String name;
  init() async{
    await name="123";
  }
}
main(){
  Test().init();
//It's wrong
  print(Test().name);
}

I know it does print first and then assign values,this is an example.But in my real code,the await process is a must,can someone fix this bug?

Thanks!!!

1 Answers

change it as


class Test{
  late String name;
  Future<void> init() async{
    name = "123"; //you cannot use await here as String type is not a future.
    //you can only use await for a future type work.
  }
}
void main() async {
  var test = Test();
  test.init().then((v){
    print(test.name);
  });
  
  //or you can also use
    await test.init();// if you don't want to use this approach, remove the aysnc from main method
  print(test.name);
  
}
Related