Flutter GET请求报错NoSuchMethodError: 对null调用[]方法(depId相关)
问题描述
我尝试通过GET请求从API获取并展示列表,但持续出现以下错误:
NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling:
奇怪的是,当前请求并未使用depId,该字段也不在我用于请求的对象中,且之前的请求使用它时完全正常,我不清楚为何会出现null值。
API请求代码
static Future<List<Athlete>> getAthletesByTeamKey( int depId, int teamId) async { try { final response = await http.get( Uri.parse( '$uri/get-athletes-by-team-key?depId=$depId&teamId=$teamId&page=0&length=50'), headers: { 'Authorization': 'Basic ...', 'Content-Type': 'application/json', 'Accept': 'application/json' }); print('Response status: ${response.statusCode}'); print('Response body: ${response.body}'); if (response.statusCode == 200) { if (response.body.isNotEmpty) { print('response.body.isNotEmpty'); List jsonResponse = json.decode(utf8.decode(response.bodyBytes)); return jsonResponse .map((athlete) => Athlete.fromJson(athlete)) .toList(); } else if (response.body.isEmpty) { print('response.body.isEmpty'); throw Exception(); } } } catch (e) { print('catch'); logger.e(e.toString()); } return getAthletesByTeamKey(depId, teamId, context); }
代码会打印print('response.body.isNotEmpty');,随后进入catch块。
Athlete实体类
List<Athlete> athleteFromJson(String str) => List<Athlete>.from(json.decode(str).map((x) => Athlete.fromJson(x))); String athleteToJson(List<Athlete> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class Athlete { late int id; late String firstName; late String lastName; late String fatherName; late int currentMonthPresences; late bool isSelected = false; late bool hasDebt; Department? department; Team? team; Athlete( {required this.id, required this.firstName, required this.lastName, required this.fatherName, required this.currentMonthPresences, this.isSelected = false, required this.hasDebt, this.department, this.team}); Athlete.newSelectedAthlete(this.id, this.department, this.team); //I use it for another screen factory Athlete.fromJson(Map<String, dynamic> json) => Athlete( id: json['id'], firstName: json['firstName'], lastName: json['lastName'], fatherName: json['fatherName'], currentMonthPresences: json['currentMonthPresences'], hasDebt: json['hasDebt'], department: Department.fromJson(json['department']), team: Team.fromJson(json['team']), ); Map<String, dynamic> toJson() => { 'id': id, 'firstName': firstName, 'lastName': lastName, 'fatherName': fatherName, 'currentMonthPresences': currentMonthPresences, 'isSelected': isSelected, 'hasDebt': hasDebt, 'department': department, 'team': team, }; }
Department实体类
class Department { int id; String depName; Department({required this.id, required this.depName}); factory Department.fromJson(Map<String, dynamic> json) => Department( id: json['id'], depName: json['depName'], ); Map<String, dynamic> toJson() => { "id": id, "depName": depName, }; }
Team实体类
class Team { final TeamKey teamKey; final String teamName; final int hidden; final User user; final String depName; Team( {required this.teamKey, required this.teamName, required this.hidden, required this.user, required this.depName}); factory Team.fromJson(Map<String, dynamic> json) => Team( teamKey: TeamKey.fromJson(json['teamKey']), teamName: json['teamName'], hidden: json['hidden'], user: User.fromJson(json['user']), depName: json['depName'], ); Map<String, dynamic> toJson() => { 'teamKey': teamKey, 'teamName': teamName, 'hidden': hidden, 'user': user, 'depName': depName, }; }
TeamKey实体类(包含depId变量,未使用)
class TeamKey { int depId; int teamId; TeamKey({required this.depId, required this.teamId}); factory TeamKey.fromJson(Map<String, dynamic> json) => TeamKey( depId: json['depId'], teamId: json['teamId'], ); Map<String, dynamic> toJson() => { "depId": depId, "teamId": teamId, }; }
页面展示代码
class AthleteScreen extends StatefulWidget { const AthleteScreen(this._team, {Key? key}) : super(key: key); final Team _team; @override State<AthleteScreen> createState() => _AthleteScreenState(); } class _AthleteScreenState extends State<AthleteScreen> { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); final myController = TextEditingController(); final controller = TextEditingController(); Future<List<Athlete>>? futureAthletebyTeamKey; Future<List<Presence>>? futureGetPresences; final List<Athlete> _athlete = []; @override void initState() { futureAthletebyTeamKey = ApiService.getAthletesByTeamKey(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, body: Stack( children: [ SingleChildScrollView( child: Column(children: [ const SizedBox( height: 10, ), FutureBuilder<List<Athlete>>( future: futureAthletebyTeamKey, builder: (context, AsyncSnapshot snapshot) { if (snapshot.hasData) { List<Athlete> _athlete = snapshot.data; return ListView.builder( shrinkWrap: true, cacheExtent: 34, primary: true, physics: const ClampingScrollPhysics(), padding: const EdgeInsets.only( top: 10, bottom: 56, ), itemCount: _athlete.length, itemBuilder: (BuildContext context, int i) { return CheckboxListTile( title: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text( 'ID: ${_athlete[i].id}', style: const TextStyle( color: Colors.blue, fontSize: 14), ), const SizedBox( width: 5, ), ], ), Row( children: [ Flexible( child: Text( '${_athlete[i].lastName} ${_athlete[i].firstName}', style: const TextStyle( color: Colors.black, fontFamily: 'Cera', fontWeight: FontWeight.bold, fontSize: 18), ), ), ], ), const SizedBox( height: 5, ), }); } else if (snapshot.hasError) { logger.e('${snapshot.error}'); } return const Center( heightFactor: 20, child: CircularProgressIndicator.adaptive(), ); }, ), ]), ), Align( alignment: Alignment.bottomCenter, child: Container( width: double.infinity, height: 60, child: ElevatedButton( style: ElevatedButton.styleFrom( disabledBackgroundColor: Colors.grey), onPressed: () async { Navigator.of(context).pushNamed( SelectedAthletes.routeName, arguments: selectedAthlete.toList()); }), child: Column( children: [ const Text( 'ΝΕΧΤ', style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 18), ), ], ), ), ), ), ], ), ); } }
希望有人能帮忙解决这个问题,非常感谢!
内容的提问来源于stack exchange,提问作者kate_3dev
相关产品推荐
相关产品推荐

