Flutter:从 FutureBuilder 小部件中的 Future 检索关联对象
Flutter: Retrieve associated object from Future in FutureBuilder widget
我正在从对象 'event' 的未来获取用户 'event manager id' 数据。我现在想获取一个使用该 ID 的用户,以便在事件旁边显示他的名字。但是,我的 FutureBuilder 小部件仅考虑一个未来(事件),我无法根据该事件检索该用户的名称,因为我的 fetchUser 方法将仅 return 未来对象。
非常感谢任何帮助。
这是 FutureBuilder 小部件:
body: new FutureBuilder(
future: events,
builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
List<Event> availableEvents = snapshot.data;
if (!snapshot.hasData) return CircularProgressIndicator();
return new ListView.builder(
scrollDirection: Axis.vertical,
padding: new EdgeInsets.all(6.0),
itemCount: availableEvents.length,
itemBuilder: (BuildContext context, int index) {
user = fetchUserbyId( // Here, user is of type Future<user> and I cannot retrieve info such as the name of that user
(availableEvents[index].managerId).toString());
return new Container(
margin: new EdgeInsets.only(bottom: 6.0),
padding: new EdgeInsets.all(6.0),
color: Colors.white,
child: Column(
children: <Widget>[
new Text('${availableEvents[index].name}',
style: TextStyle(
fontWeight: FontWeight.bold,
height: _height,
fontSize: 18)),
new Text('${availableEvents[index].description}',
style: TextStyle(height: _height)),
new Text('${availableEvents[index].address}',
style: TextStyle(height: _height)),
new Text('${availableEvents[index].datetime}',
style: TextStyle(height: _height)),
//new Text('${availableEvents[index].managerId}', style: TextStyle(height: _height)),
new FlatButton(
onPressed: null,
// Simply call joinEvent for event 'availableEvents[index]'
color: Colors.redAccent,
textColor: Colors.white,
disabledColor: Colors.red,
disabledTextColor: Colors.white,
padding: EdgeInsets.all(8.0),
splashColor: Colors.redAccent,
child: Text('Join!'),
)
],
));
},
);
}));
这里是 fetchUserByID 方法:
Future<User> fetchUserbyId(String id) async {
final response =
await http.get('https://url-here.com' + id);
//print("response : " + response.body);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
return User.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
如果我的理解是您有两个异步调用,其中第二个调用需要第一个调用的结果才能执行。解决这个问题的最好方法是创建一个辅助方法,即 getData()
。在此方法中,您调用 events
,然后将其用于 fetchUserbyId
。这将导致您的 FutureBuilder 看起来像这样:
FutureBuilder(
future: getData()
builder: ... // get the results the same why you got your results from events in the given example.
);
然后在你的 getData()
方法中它看起来像这样:
Future<User> getData() async {
var availableEvents= await events; // not sure what your events data/method is
return fetchUserbyId((availableEvents[index].managerId).toString());
}
我想我回答了你的问题,但如果我错过了请评论。
注意:在一个完全不相关的主题上,您不再需要 Flutter 中的 new
关键字来实例化对象。希望能加快您的开发进程!
我正在从对象 'event' 的未来获取用户 'event manager id' 数据。我现在想获取一个使用该 ID 的用户,以便在事件旁边显示他的名字。但是,我的 FutureBuilder 小部件仅考虑一个未来(事件),我无法根据该事件检索该用户的名称,因为我的 fetchUser 方法将仅 return 未来对象。
非常感谢任何帮助。
这是 FutureBuilder 小部件:
body: new FutureBuilder(
future: events,
builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
List<Event> availableEvents = snapshot.data;
if (!snapshot.hasData) return CircularProgressIndicator();
return new ListView.builder(
scrollDirection: Axis.vertical,
padding: new EdgeInsets.all(6.0),
itemCount: availableEvents.length,
itemBuilder: (BuildContext context, int index) {
user = fetchUserbyId( // Here, user is of type Future<user> and I cannot retrieve info such as the name of that user
(availableEvents[index].managerId).toString());
return new Container(
margin: new EdgeInsets.only(bottom: 6.0),
padding: new EdgeInsets.all(6.0),
color: Colors.white,
child: Column(
children: <Widget>[
new Text('${availableEvents[index].name}',
style: TextStyle(
fontWeight: FontWeight.bold,
height: _height,
fontSize: 18)),
new Text('${availableEvents[index].description}',
style: TextStyle(height: _height)),
new Text('${availableEvents[index].address}',
style: TextStyle(height: _height)),
new Text('${availableEvents[index].datetime}',
style: TextStyle(height: _height)),
//new Text('${availableEvents[index].managerId}', style: TextStyle(height: _height)),
new FlatButton(
onPressed: null,
// Simply call joinEvent for event 'availableEvents[index]'
color: Colors.redAccent,
textColor: Colors.white,
disabledColor: Colors.red,
disabledTextColor: Colors.white,
padding: EdgeInsets.all(8.0),
splashColor: Colors.redAccent,
child: Text('Join!'),
)
],
));
},
);
}));
这里是 fetchUserByID 方法:
Future<User> fetchUserbyId(String id) async {
final response =
await http.get('https://url-here.com' + id);
//print("response : " + response.body);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
return User.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
如果我的理解是您有两个异步调用,其中第二个调用需要第一个调用的结果才能执行。解决这个问题的最好方法是创建一个辅助方法,即 getData()
。在此方法中,您调用 events
,然后将其用于 fetchUserbyId
。这将导致您的 FutureBuilder 看起来像这样:
FutureBuilder(
future: getData()
builder: ... // get the results the same why you got your results from events in the given example.
);
然后在你的 getData()
方法中它看起来像这样:
Future<User> getData() async {
var availableEvents= await events; // not sure what your events data/method is
return fetchUserbyId((availableEvents[index].managerId).toString());
}
我想我回答了你的问题,但如果我错过了请评论。
注意:在一个完全不相关的主题上,您不再需要 Flutter 中的 new
关键字来实例化对象。希望能加快您的开发进程!