必须向文本小部件提供非空字符串。/断言失败:第 380 行 pos 10:"data != null"



我只想从互联网上获取天气预报数据。我在下面写了这个代码,但每次我都会出现错误:

必须向文本窗口小部件提供非空字符串

由于某些原因,我无法获取解码的json数据

import 'package:flutter/material.dart';
import 'network.dart';
class HomePage extends StatefulWidget {
static String id;
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Map<String,dynamic> currentPositionWeatherData;
String temperature;
String weatherDescription;
String name;

void initState(){
super.initState();
getCurrentLocationWeather();
updateUI();
}
void getCurrentLocationWeather()async{
currentPositionWeatherData=await NetworkHelperForWeatherInfo().getCurrentPositionWeatherData();
}
void updateUI()async{
setState(() {
weatherDescription = currentPositionWeatherData["weather"][0]["description"];
temperature = currentPositionWeatherData["main"]["temp"];
name = currentPositionWeatherData["name"];
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Container(
color: Colors.black,
child: Text(
temperature,
),
),
);
}
}
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart';
const openWeatherURL="http://api.openweathermap.org/data/2.5/weather";
const apikey="57aad03f4e48ca815bb1184e74624f46";
class NetworkHelperForWeatherInfo{
Future getCurrentPositionWeatherData()async{
Position position = await Geolocator.getCurrentPosition();
Response response = await get("$openWeatherURL?lat=${position.latitude}&lon=${position.latitude}&appid=$apikey");
if(response.statusCode ==200){
String currentPositionWeatherData = response.body;
return jsonDecode(currentPositionWeatherData);
}
else{
return response.statusCode;
}
}

}
import 'package:flutter/material.dart';
import 'homepage.dart';
import 'package:geolocator/geolocator.dart';
class LocationFinder{
bool serviceEnabled;
LocationPermission permission;
Future<Position> determineCurrentPosition()async{
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if(serviceEnabled != true){
return Future.error("Location services are disabled");
}
permission = await Geolocator.checkPermission();
if (permission==LocationPermission.deniedForever) {
return Future.error("Location permissions are permantly denied,we cannot request permissions.");
}
if (permission == LocationPermission.denied){
permission = await Geolocator.requestPermission();
if(permission != LocationPermission.whileInUse &&
permission != LocationPermission.whileInUse){
return Future.error("Location permission are denied/ actual value:$permission");
}
}
Position position =await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
return position;
}
}
child: Text(
temperature ?? 'waiting data...',
)

首次构建_HomePageStateState小部件时,temperature变量将为null(直到检索到数据并通过setState调用重建小部件为止(。声明文本值不为null的Text小部件不允许使用null值。

temperature为空时,上述更改将提供文本waiting data...

相关内容

最新更新