获取“未处理的异常:NoSuchMethodError:方法'map'在null上被调用”
Posted
技术标签:
【中文标题】获取“未处理的异常:NoSuchMethodError:方法\'map\'在null上被调用”【英文标题】:Getting "Unhandled Exception: NoSuchMethodError: The method 'map' was called on null"获取“未处理的异常:NoSuchMethodError:方法'map'在null上被调用” 【发布时间】:2021-09-26 20:15:55 【问题描述】:Main.dart 文件
import 'package:flutter/material.dart';
import 'package:weather_app/listModel.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:weather_app/model.dart';
void main()
runApp(MyApp());
class MyApp extends StatefulWidget
@override
_MyAppState createState() => _MyAppState();
class _MyAppState extends State<MyApp>
var listModel;
bool circular = true;
@override
void initState()
super.initState();
getData();
void getData() async
var res = await http.get(Uri.parse('https://www.metaweather.com/api/location/2295420/'));
var r = json.decode(res.body);
setState(()
listModel = ListModel.fromJson("data": r);
print(listModel);
circular = false;
);
//
@override
Widget build(BuildContext context)
// TODO: implement build
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('WEATHER REPORT'),
),
body: Center(
child: circular ? CircularProgressIndicator(): ListView.builder(itemCount: listModel.consolidatedWeather.length,itemBuilder: (BuildContext context, int index)=>
dataShow(listModel.consolidatedWeather[index],index)),
)
),
);
Widget dataShow(Model obj, index)
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Container(
height: 100,
// width: MediaQuery.of(context).size.width,
child: Card(
color: Colors.teal,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Name $index + 1 : $obj.weatherStateName",
style: TextStyle(fontSize: 18, color: Colors.white),
),
SizedBox(
height: 10,
),
Text(
"PhoneNumber : $obj.theTemp",
style: TextStyle(fontSize: 18, color: Colors.white),
),
],
),
),
),
);
列出 Model.dart
import 'package:weather_app/model.dart';
class ListModel
ListModel(
required this.consolidatedWeather,
);
List<Model> consolidatedWeather;
factory ListModel.fromJson(Map<String, dynamic> json) => ListModel(
consolidatedWeather: List<Model>.from(json["consolidated_weather"].map((x) => Model.fromJson(x))).toList(),
);
Map<String, dynamic> toJson() =>
"consolidated_weather": List<dynamic>.from(consolidatedWeather.map((x) => x.toJson())),
;
Model.dart
class Model
Model(
required this.weatherStateName,
required this.weatherStateAbbr,
required this.applicableDate,
required this.theTemp,
);
String weatherStateName;
String weatherStateAbbr;
DateTime applicableDate;
double theTemp;
factory Model.fromJson(Map<String, dynamic> json) => Model(
weatherStateName: json["weather_state_name"],
weatherStateAbbr: json["weather_state_abbr"],
applicableDate: DateTime.parse(json["applicable_date"]),
theTemp: json["the_temp"].toDouble(),
);
Map<String, dynamic> toJson() =>
"weather_state_name": weatherStateName,
"weather_state_abbr": weatherStateAbbr,
"applicable_date": "$applicableDate.year.toString().padLeft(4, '0')-$applicableDate.month.toString().padLeft(2, '0')-$applicableDate.day.toString().padLeft(2, '0')",
"the_temp": theTemp,
;
pupspec.yml
name: weather_app
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In ios, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
meta: ^1.0.2
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
http: ^0.13.3
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
错误
Performing hot restart...
Syncing files to device Redmi Note 9 Pro...
Restarted application in 1,965ms.
E/flutter (26913): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter (26913): Receiver: null
E/flutter (26913): Tried calling: map(Closure: (dynamic) => Model)
E/flutter (26913): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (26913): #1 new ListModel.fromJson (package:weather_app/listModel.dart:11:72)
E/flutter (26913): #2 _MyAppState.getData.<anonymous closure> (package:weather_app/main.dart:30:29)
E/flutter (26913): #3 State.setState (package:flutter/src/widgets/framework.dart:1088:30)
E/flutter (26913): #4 _MyAppState.getData (package:weather_app/main.dart:29:5)
E/flutter (26913): <asynchronous suspension>
E/flutter (26913):
W/Choreographer(26913): Frame time is 0.009381 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
W/Choreographer(26913): Frame time is 0.021302 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
W/Choreographer(26913): Frame time is 0.006804 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
W/Choreographer(26913): Frame time is 0.064763 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
接下来我可以尝试什么来解决这个问题?
【问题讨论】:
嗨!您将没有“consolidated_weather”字段的 json 传递给ListModel.fromJson
。注意这个:listModel = ListModel.fromJson("data": r);
和这个List<Model>.from(json["consolidated_weather"].map((x) => Model.fromJson(x))).toList()
对不起,我没听懂
如果上面是错误的,下面的模型类是什么 json "consolidated_weather":[ "weather_state_name":"Heavy Rain", "weather_state_abbr":"hr", "applicable_date":" 2021-07-19", "the_temp":25.11, ]
尝试使用listModel = ListModel.fromJson(r);
而不是listModel = ListModel.fromJson("data": r);
。它应该工作
非常感谢.. 成功了
【参考方案1】:
getData() fn 应该是这样的..
void getData() async
var res = await http.get(Uri.parse('https://www.metaweather.com/api/location/2295420/'));
var r = json.decode(res.body);
setState(()
listModel = ListModel.fromJson(r); // Change this line
print(listModel);
circular = false;
);
【讨论】:
以上是关于获取“未处理的异常:NoSuchMethodError:方法'map'在null上被调用”的主要内容,如果未能解决你的问题,请参考以下文章