【发布时间】:2020-06-14 12:06:04
【问题描述】:
我正在运行我的应用程序并收到错误消息:
“NoSuchMethodError:方法'[]'在null上被调用。接收者:null。尝试调用:。”
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import '../model/Lesson.dart';
class MobileModeScreen extends StatefulWidget {
@override
_MobileModeScreenState createState() => _MobileModeScreenState();
}
class _MobileModeScreenState extends State<MobileModeScreen> {
List<Lesson> _lesson;
@override
void initState() {
super.initState();
Future.delayed(Duration.zero,() {
getLessonFromJSON(context);
});
print("lessonDescription: ${_lesson[0].lessonTitle}");
}
Future<List<Lesson>> getLessonFromJSON(BuildContext context) async {
String jsonString = await DefaultAssetBundle.of(context).loadString("assets/lessons/lessons.json");
return await Future.delayed(Duration.zero,() {
List<dynamic> data = jsonDecode(jsonString);
List<Lesson> lesson = data.map( (f) => Lesson.fromJSON(f) ).toList();
_lesson = lesson;
print("lessonDescription: ${_lesson[0].lessonTitle}");
return _lesson;
});
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
appBar: AppBar(
title: Container(
padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
decoration: BoxDecoration(
color: Color(0xffFFFFFF),
border: Border.all(
color: Color(0xffF5ED02),
width: 3,
),
borderRadius: BorderRadius.circular(25.0),
),
child: Text("lessonDescription: ${_lesson[0].lessonTitle}",
style: TextStyle(
//fontFamily: "Uthmani",
color: Color(0xff225587),
),
),
),
centerTitle: true,
backgroundColor: Color(0xff7F3F96),
),
body: ListView(
padding: const EdgeInsets.fromLTRB(5, 15, 5, 5),
children: <Widget>[
],
),
backgroundColor: Color(0xffF0E4F2),
),
);
}
}
当我尝试从 getLessonFromJSON 函数访问值时,我没有收到错误消息,但在函数之外,它根本不起作用。
我得到的错误:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building Builder:
The method '[]' was called on null.
Receiver: null
Tried calling: [](0)
The relevant error-causing widget was:
MaterialApp file:///home/hmalabeh/AndroidStudioProjects/Flutter/Bounyan/boynyan_final/lib/main.dart:12:12
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 _MobileModeScreenState.initState (package:boynyanfinal/screens/mobile_mode_screen.dart:26:40)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
#4 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
...
有人可以帮忙吗。
更新:
我希望能够在build 方法中使用我从函数getLessonFromJSON 获得的内容,就像我在AppBar 中提交的Text 中使用的一样
【问题讨论】: