════════ 小部件库捕获的异常═════════════════════════════␕══以下NoSuchMethodError 被抛出构建:方法“[]”在 null 上被调用。接收者:null 尝试调用:
主要.dart
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: HomeScreen(title: 'Email Client App'),
);
}
}
home_screen.dart
class HomeScreen extends StatelessWidget {
HomeScreen({this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: MessagesScreen());
}
}
message_screen.dart
import 'dart:convert';
import 'package:email_client_app/models/message.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class MessagesScreen extends StatefulWidget {
@override
_MessagesScreenState createState() => _MessagesScreenState();
}
class _MessagesScreenState extends State<MessagesScreen> {
Future loadMessageFromAsset() async {
await Future.delayed(Duration(seconds: 2));
return await rootBundle.loadString("data/message.json");
}
Future<List<Message>> getMessagesFromAsset() async {
String jsonString = await loadMessageFromAsset();
List<dynamic> data = json.decode(jsonString);
List<Message> messages =
data.map((data) => Message.fromJson(data)).toList();
return messages;
}
@override
void initState() {
getMessagesFromAsset();
super.initState();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getMessagesFromAsset(),
builder: (context, messages) {
List<Message> messageList = messages.data;
return ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
** 这是捕获错误的地方!**
var message = messageList[index];
--
return ListTile(
isThreeLine: true,
leading: CircleAvatar(child: Text('ND')),
title: Text(messageList[index].title),
subtitle: Text(
message.body,
maxLines: 2,
),
trailing: Icon(
Icons.more_horiz_outlined,
color: Colors.blueAccent,
),
);
},
);
});
}
}
message.dart(消息模型类)。# 从 message.json 检索本地数据源
class Message {
Message({this.title, this.body});
String title, body;
factory Message.fromJson(Map<String, dynamic> data) {
return Message(title: data['title'], body: data['body']);
}
Map<String, dynamic> toJson() {
return {'title': title, 'body': body};
}
}
消息.json
[
{
"title": "Title 1",
"body": "Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consectetur adipisci elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua."
},
{
"title": "Title 2",
"body": "Lorem ipsum dolor sit amet. "
}
]