HTTP call on screen load in flutter

Sam*_*mer 4 dart flutter

We have a Features class that we are trying to fill when a screen loads. Its an http call that returns the object. Im struggling with how to do this. All of our http calls are done on a button click:

here is the call

      Future<Features> getFeatureStatus(String userID) async {

      Features _features;

     final response =
     await http.post('http://url/api/Features',
     headers: {"Content-Type": "application/json", 
             'Accept': 'application/json',},
  body: json.encode({'userID' : userID }));

 _features = Features.fromJson(json.decode(response.body));

   return _features;


  } 
Run Code Online (Sandbox Code Playgroud)

When i try to call it at the top of the class I get errors and cant get to the values.

class FlutterReduxApp extends StatelessWidget {
static final User user;
static final Features features = getFeatureStatus(user.userId);
Run Code Online (Sandbox Code Playgroud)

The error I get is -- "A value of type 'Future' can't be assigned to a variable of type 'Features'. Try changing the type of the variable, or casting the right-hand type to 'Features'.dart(invalid_assignment)"

Im sure im doing something incorrect here but I havent done a screen load call yet.

osa*_*xma 5

当您尝试将其读取为无状态小部件中的类型时,该getFeatureStatus函数正在返回。Future<Features>Features

有不同的方法来读取值,但由于您有一个按钮,您可以将小部件转换为然后StatefulWidget使用该onPressed函数来读取值并随后更新状态,例如。

onPressed: () async {
  features = await getFeatureStatus(user.userId);

  setState((){
  // do something
  });
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,该值features不能是静态最终值,因此您必须将其更改为Features features.

根据评论进行编辑:

你也可以在 initState 中执行此操作:

Features features;
@override
void initState () {
 super.initState();
 _asyncMethod();
}

_asyncMethod() async {
 features = await getFeatureStatus(user.userId);
 setState((){});
}
Run Code Online (Sandbox Code Playgroud)

所以在小部件构建方法中你可以这样做:

return (features == null) 
       ? CircularProgressIndicator()
       : MyWidget(...); // where features is used.
Run Code Online (Sandbox Code Playgroud)