如何解决Flutter 中的 FutureBuilder - 调用 API 并使用地图标记的响应
我正在调用 API 并利用返回的 Json 数据在地图上发布标记
我有调用在单独的应用程序上返回一个 ListView 很好
在我的地图应用程序中实现相关的 FutureBuilder 代码之前,我收到了这个错误
type 'Future<Stations>' is not a subtype of type 'Iterable<dynamic>'
然后我意识到我没有在主构造函数中实现 Future Builder。
我尝试从调用相同 HTTP 的其他应用程序中实现我的 Future 构建器,并进行了一些修改。
在尝试实现 Future Builder 后,我现在从 Future Builder 构造中收到错误,我被告知将修复以前的错误,因为它是强制性的,尽我的初学者能力!
我正在拉动 stations.place.location.lat
和 stations.place.location.lng
Json 以在 GeoCoordinates 中使用以放置标记
这是我正在使用的 Dart 代码,感谢您的指导。我将排除与此问题无关的代码。
Future Builder(在下面的示例中留下了一些粗略的代码)需要进入我的 Main.dart
void main() {
SdkContext.init(IsolateOrigin.main);
runApp(MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<Stations> stations;
@override
void initState() {
stations = API_Call().fetchStations();
super.initState();
}
BuildContext _context;
MapMarkerExample _mapMarkerExample;
@override
Widget build(BuildContext context) {
_context = context;
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Example 1'),),body: Container(
child:
FutureBuilder<Stations>(
future: API_Call().fetchStations(),builder: (context,snapshot) {
if(snapshot.hasData) {
return ListView.builder(
itemBuilder: (context,index) {
var stations = snapshot.data.stations[index];
Stack(
children: [
HereMap(onMapCreated: _onMapCreated),Column(
mainAxisAlignment: MainAxisAlignment.start,children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: [
button('Call',_anchoredMapMarkersButtonClicked),button('Clear',_clearButtonClicked),],);
}
);
}
}
)
)
)
);
}
...
api_manager.dart
class MapMarkerExample{
void showAnchoredMapMarkers() {
var stations;
stations = API_Call().fetchStations();
for (Station stations in stations) {
GeoCoordinates geoCoordinates = GeoCoordinates (stations.place.location.lat,stations.place.location.lng);
}
GeoCoordinates geoCoordinates = stations.coordinates;
_addPOIMapMarker(geoCoordinates,1);
}
...
api_call.dart
class API_Call {
Future<Stations> fetchStations() async {
var client = http.Client();
final response = await client.get(
'https://transit.hereapi.com/v8/stations?in=x,-x&return=transport&apiKey=MY_API_KEY');
if (response.statusCode == 200) {
return Stations.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load stations');
}
}
}
解决方法
对于您的直接语法问题,您忘记了 await
:
stations = await API_Call().fetchStations();
但是,这会对您的代码产生连锁反应,因为现在该函数需要为 async
并且可能需要在其他地方等待。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。