-1

════════ 小部件库捕获的异常═════════════════════════════␕══以下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. "
    }
]
4

2 回答 2

1

连接状态等待时返回指示符或任何内容。

return FutureBuilder(
        future: getMessagesFromAsset(),
        builder: (context, messages) {

          // add this one
          if (messages.connectionState == ConnectionState.waiting) {
                return Text("Loading...");
          }
          List<Message> messageList = messages.data;
          return ListView.builder(
            itemCount: 5,
            itemBuilder: (context, 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,
                ),
              );
            },
          );
        });
于 2020-11-17T17:34:58.587 回答
1

我认为你做错了几件事。

  • getMessagesFromAsset在两个地方调用该方法:initState& FutureBuilder。从 中删除initState

  • 您的方法getMessageskFromAsset可能需要在 map 方法中使用不同的变量名:

    Future<List<Message>> getMessagesFromAsset() async {
         String jsonString = await loadMessageFromAsset();
         List<dynamic> data = json.decode(jsonString);
         List<Message> messages =
             data.map((messageData) => Message.fromJson(messageData)).toList(); // here
         return messages;
       }
    
  • 检查messages列表是否null存在。

    List<Message> messageList = messages.data ?? [];
    
  • 在里面ListView.builder,你使用的是一个固定值5,这会导致索引越界异常。

    return ListView.builder(
         itemCount: messages?.length ?? 0, // Use messages.length instead of `5`
    
于 2020-11-17T17:42:32.180 回答