我在颤抖中收到错误消息,称方法“ +”为null

时间:2020-02-29 12:33:31

标签: android-studio flutter

目前,我正在Udemy上使用名为Personal Expenses的应用程序在扑通课程中玩耍

在扑朔迷离的错误是,方法“ +”被调用为空

错误消息:-

The following NoSuchMethodError was thrown building Chart(dirty):
The method '+' was called on null.
Receiver: null

我的代码:-


import 'package:personal_expenses/models/transaction.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class Chart extends StatelessWidget {
  final List<Transaction> recentTransaction;
  Chart(this.recentTransaction);

  List<Map<String, Object>> get groupedTransactionValues {
    return List.generate(7, (index) {
      final weekDay = DateTime.now().subtract(
        Duration(days: index),
      );
      double totalSum ;

      for (var i = 0; i < recentTransaction.length; i++) {
        if (recentTransaction[i].date.day == weekDay.day &&
            recentTransaction[i].date.month == weekDay.month &&
            recentTransaction[i].date.year == weekDay.year) {
          totalSum += recentTransaction[i].amount;
        }
      }

      return {
        'day': DateFormat.E().format(weekDay).substring(0, 1),
        'amount': totalSum
      };
    });
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 6,
      margin: EdgeInsets.all(20.0),
      child: Row(
        children: groupedTransactionValues.map((data) {
          return Text('${data['day']}: ${data['amount']}');
        }).toList(),
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:2)

我通过:-

解决了

使totalSum的值= 0

double totalSum = 0

答案 1 :(得分:1)

您收到该错误是因为在声明时没有为double提供任何值,并且在Dart中,每个字段的类型均为Object,默认情况下其值为{{ 1}}与Java不同,在Java中double将null作为默认值。

0

解决方案:

double totalSum; // default value is null
totalSum += 10; // error, because totalSum is null