在 null 上调用了方法“[]”。接收器:null 尝试调用:[]("main") 控制台错误
The method '[]' was called on null. Receiver: null Tried calling: []("main") console error
你好,我正在开发一个我从课程中学到的天气应用程序,一切正常,直到我开始重构,它变得复杂,代码没有显示错误,但是当我热重启应用程序时,它崩溃显示
The method '[]' was called on null.
Receiver: null
Tried calling: []("main")
在控制台中
我什至不知道我的代码哪里出了问题,如果有人可以在下面的代码中做很多事情以及我如何修复它,我会很高兴:
networking.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
class NetworkHelper {
NetworkHelper(this.url);
final String url;
Future getData() async {
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
String data = response.body;
var output = jsonDecode(data);
} else {
print(response.statusCode);
print('not working');
}
}
}
loading_screen.dart
import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:clima/services/location.dart';
import 'package:clima/services/networking.dart';
import 'package:clima/screens/location_screen.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
const apiKey = '4c6ffd8e4e647128123739045f48d839';
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
@override
double? latitude;
double? longtitude;
void initState() {
super.initState();
getLocationData();
}
void getLocationData() async {
Location location = Location();
await location.geolocation();
latitude = location.latitude;
longtitude = location.longtitude;
NetworkHelper networkHelper = NetworkHelper(
'https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longtitude&appid=$apiKey&units=metric');
var weatherdata = await networkHelper.getData();
Navigator.push(context, MaterialPageRoute(builder: (context) {
return LocationScreen(
locationWeather: weatherdata,
);
}));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SpinKitDoubleBounce(
color: Colors.white,
size: 100.0,
),
),
);
}
}
location_screen.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:clima/utilities/constants.dart';
import 'package:clima/services/weather.dart';
class LocationScreen extends StatefulWidget {
final locationWeather;
LocationScreen({this.locationWeather});
@override
_LocationScreenState createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
WeatherModel weather = WeatherModel();
int? temperature;
String? weatherIcon;
String? cityName;
String? weatherMessage;
@override
void initState() {
UpdateUi(widget.locationWeather);
super.initState();
}
void UpdateUi(dynamic weatherData) {
setState(() {
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id '];
cityName = weatherData['name'];
weatherMessage = weather.getMessage(temperature!);
weatherIcon = weather.getWeatherIcon(condition);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/location_background.jpg'),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(
Colors.white.withOpacity(0.8), BlendMode.dstATop),
),
),
constraints: BoxConstraints.expand(),
child: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton(
onPressed: () {},
child: Icon(
Icons.near_me,
size: 50.0,
),
),
FlatButton(
onPressed: () {},
child: Icon(
Icons.location_city,
size: 50.0,
),
),
],
),
Padding(
padding: EdgeInsets.only(left: 15.0),
child: Row(
children: <Widget>[
Text(
weatherIcon!,
style: kTempTextStyle,
),
Text(
'☀️',
style: kConditionTextStyle,
),
],
),
),
Padding(
padding: EdgeInsets.only(right: 15.0),
child: Text(
"$weatherMessage in $cityName",
textAlign: TextAlign.right,
style: kMessageTextStyle,
),
),
],
),
),
),
);
}
}
这是 location_screen.dart 中我认为我犯了一个错误的部分其他之前:
void UpdateUi(dynamic weatherData) {
setState(() {
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id '];
cityName = weatherData['name'];
weatherMessage = weather.getMessage(temperature!);
weatherIcon = weather.getWeatherIcon(condition);
});
}
我尝试修复它,但没有用,我实际上是 flutter 的初学者,我想这就是我遇到这个问题的原因,
所以我希望有人能引导我走上正确的道路..以防万一我以后遇到这种情况我可以自己解决谢谢。
在 networking.dart 你必须 return 像这样
String data = response.body;
var output = jsonDecode(data);
return output;
因为您在 loading_screen.dart
中使用了变量
var weatherdata = await networkHelper.getData();
var weatherdata 需要一个值,因此 null 是 returned
检查您的 main.dart 文件以确保您没有解析与 home 相同的 locationscreen。可能是导航器推送过程中的错误。
你好,我正在开发一个我从课程中学到的天气应用程序,一切正常,直到我开始重构,它变得复杂,代码没有显示错误,但是当我热重启应用程序时,它崩溃显示
The method '[]' was called on null.
Receiver: null
Tried calling: []("main")
在控制台中
我什至不知道我的代码哪里出了问题,如果有人可以在下面的代码中做很多事情以及我如何修复它,我会很高兴: networking.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
class NetworkHelper {
NetworkHelper(this.url);
final String url;
Future getData() async {
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
String data = response.body;
var output = jsonDecode(data);
} else {
print(response.statusCode);
print('not working');
}
}
}
loading_screen.dart
import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:clima/services/location.dart';
import 'package:clima/services/networking.dart';
import 'package:clima/screens/location_screen.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
const apiKey = '4c6ffd8e4e647128123739045f48d839';
class LoadingScreen extends StatefulWidget {
@override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
@override
double? latitude;
double? longtitude;
void initState() {
super.initState();
getLocationData();
}
void getLocationData() async {
Location location = Location();
await location.geolocation();
latitude = location.latitude;
longtitude = location.longtitude;
NetworkHelper networkHelper = NetworkHelper(
'https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longtitude&appid=$apiKey&units=metric');
var weatherdata = await networkHelper.getData();
Navigator.push(context, MaterialPageRoute(builder: (context) {
return LocationScreen(
locationWeather: weatherdata,
);
}));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SpinKitDoubleBounce(
color: Colors.white,
size: 100.0,
),
),
);
}
}
location_screen.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:clima/utilities/constants.dart';
import 'package:clima/services/weather.dart';
class LocationScreen extends StatefulWidget {
final locationWeather;
LocationScreen({this.locationWeather});
@override
_LocationScreenState createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
WeatherModel weather = WeatherModel();
int? temperature;
String? weatherIcon;
String? cityName;
String? weatherMessage;
@override
void initState() {
UpdateUi(widget.locationWeather);
super.initState();
}
void UpdateUi(dynamic weatherData) {
setState(() {
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id '];
cityName = weatherData['name'];
weatherMessage = weather.getMessage(temperature!);
weatherIcon = weather.getWeatherIcon(condition);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/location_background.jpg'),
fit: BoxFit.cover,
colorFilter: ColorFilter.mode(
Colors.white.withOpacity(0.8), BlendMode.dstATop),
),
),
constraints: BoxConstraints.expand(),
child: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
FlatButton(
onPressed: () {},
child: Icon(
Icons.near_me,
size: 50.0,
),
),
FlatButton(
onPressed: () {},
child: Icon(
Icons.location_city,
size: 50.0,
),
),
],
),
Padding(
padding: EdgeInsets.only(left: 15.0),
child: Row(
children: <Widget>[
Text(
weatherIcon!,
style: kTempTextStyle,
),
Text(
'☀️',
style: kConditionTextStyle,
),
],
),
),
Padding(
padding: EdgeInsets.only(right: 15.0),
child: Text(
"$weatherMessage in $cityName",
textAlign: TextAlign.right,
style: kMessageTextStyle,
),
),
],
),
),
),
);
}
}
这是 location_screen.dart 中我认为我犯了一个错误的部分其他之前:
void UpdateUi(dynamic weatherData) {
setState(() {
double temp = weatherData['main']['temp'];
temperature = temp.toInt();
var condition = weatherData['weather'][0]['id '];
cityName = weatherData['name'];
weatherMessage = weather.getMessage(temperature!);
weatherIcon = weather.getWeatherIcon(condition);
});
}
我尝试修复它,但没有用,我实际上是 flutter 的初学者,我想这就是我遇到这个问题的原因,
所以我希望有人能引导我走上正确的道路..以防万一我以后遇到这种情况我可以自己解决谢谢。
在 networking.dart 你必须 return 像这样
String data = response.body;
var output = jsonDecode(data);
return output;
因为您在 loading_screen.dart
中使用了变量var weatherdata = await networkHelper.getData();
var weatherdata 需要一个值,因此 null 是 returned
检查您的 main.dart 文件以确保您没有解析与 home 相同的 locationscreen。可能是导航器推送过程中的错误。