Harsh J
Harsh J

Reputation: 503

I am getting a error in flutter that method "+" was called on null

Presently I am playing around with a course on flutter on Udemy with the app named as Personal Expenses

and

I am getting a error in flutter that method "+" was called on null

Error message :-

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

My Code :-


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(),
      ),
    );
  }
}

Upvotes: 1

Views: 866

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 268114

You were getting that error because you didn't provide any value to your double at the time of declaration, and in Dart every field is of type Object and by default its value is null unlike java where double gets 0 as default value.

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

Solution:

 double totalSum = 0; // assign some value
 totalSum += 10; // works

Upvotes: 1

Harsh J
Harsh J

Reputation: 503

I solved it by :-

making the value of totalSum = 0

double totalSum = 0

Upvotes: 3

Related Questions