我正在嘗試創建一個應用程式,該應用程式從 open-meteo API 獲取資訊。我不斷遇到一些不知道如何解決的錯誤。將不勝感激任何幫助!
title: Text(snapshot.data[i].longitude), //這是產生錯誤的行
import 'dart:convert';
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false,
));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future getUserData() async {
var response = await http.get(Uri.parse( 'https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m'));
var jsonData = jsonDecode(response.body);
List<User> users = [];
for (var u in (jsonData)) {
User user = User(u['longitude'], u['latitude'], u['hourly'], u['time'],u['temperature']);
users.add(user);
}
print(users.length);
return users;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Rangers Tool'),
),
body: Container(
child: Card(
child: FutureBuilder(
future: getUserData(),
builder: (context, AsyncSnapshot snapshot) {
return ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: (context, i) {
return ListTile(
title: Text(snapshot.data[i].longitude),
subtitle: Text(snapshot.data[i].latitude),
);
});
}
},
))), ); } }
class User {
final String longitude, latitude, hourly, time, temperature;
User(this.longitude, this.latitude, this.hourly, this.time, this.temperature); }
}
uj5u.com熱心網友回復:
您需要添加一個條件以確保資料存在,方法是snapshot在使用它來構建您的串列之前檢查它的狀態。與此類似:
FutureBuilder(
future: _fetchListItems(),
builder:(context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
} else {
return ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: (context, i) {
return ListTile(
title: Text(snapshot.data[i].longitude),
subtitle: Text(snapshot.data[i].latitude),
);
}
}
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452170.html
