flutter | Dart - NoSuchMethodError : The method 'map' was called on null

标签 flutter testing dart nosuchmethoderror

构建时收到错误:
NoSuchMethodError:在 null 上调用了方法“map”。
接收方:空
尝试调用:
map (关闭:交易=>容器)

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building TransactionList(dirty):
The method 'map' was called on null.
Receiver: null
Tried calling: map<Container>(Closure: (Transaction) => Container)

The relevant error-causing widget was: 
  TransactionList file:///C:/.../AndroidStudioProjects/money_tracker/lib/Widgets/user_transactions.dart:44:9
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      TransactionList.build (package:money_tracker/models/transaction_list.dart:14:30)
#2      StatelessElement.build (package:flutter/src/widgets/framework.dart:4576:28)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
我相信该错误与 user_transactions.dart 文件中的 TransactionList(_userTransactions) 行有关,但不确定如何解决。
代码:
来自 main.dart:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gradient_app_bar/gradient_app_bar.dart';
import 'package:money_tracker/Widgets/user_transactions.dart';

void main() {
  runApp(Home());
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: GradientAppBar(
          centerTitle: true,
          gradient: LinearGradient(
            colors: [Colors.green, Color(0xff01655e)],
          ),
          title: Text(
            'Money Tracker',
            style: TextStyle(color: Colors.white),
          ),
//          backgroundColorStart: Color(0xff01655e),
          actions: <Widget>[
            Icon(Icons.add),
          ],
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              width: double.infinity,
              margin: EdgeInsets.all(15.0),
              child: Card(
                //Card is a freestyle container
                color: Color(0xff01655e),
                child: Text('Chart'),
                elevation: 5.0,
              ),
            ),
            UserTransactions(),
          ],
        ),
      ),
    );
  }
}
来自 user_transactions.dart:
import 'package:flutter/material.dart';
import 'package:money_tracker/models/transaction_list.dart';
import 'new_transaction.dart';
import '../models/transaction.dart';

class UserTransactions extends StatefulWidget {
  @override
  _UserTransactionsState createState() => _UserTransactionsState();
}

class _UserTransactionsState extends State<UserTransactions> {
  final List<Transaction> _userTransactions = [
    Transaction(
      id: '1',
      title: 'course',
      amount: 11.99,
      dateTime: DateTime.now(),
    ),
    Transaction(
      id: '2',
      title: 'milk',
      amount: 2.87,
      dateTime: DateTime.now(),
    ),
  ];

  void _addNewTransaction(String txTitle, double amount) {
    final newTx = Transaction(
        title: txTitle,
        amount: amount,
        dateTime: DateTime.now(),
        id: DateTime.now().toString());

    setState(() {
      _userTransactions.add(newTx);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        NewTransaction(_addNewTransaction),
        TransactionList(_userTransactions),
      ],
    );
  }
}
来自 transaction_list.dart:
import 'package:flutter/material.dart';
import 'transaction.dart';
import 'package:intl/intl.dart';

class TransactionList extends StatelessWidget {
  TransactionList(List<Transaction> userTransactions, {this.transactions});
  final List<Transaction> transactions;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: transactions.map((tx) {
        return Container(
          margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
          padding: EdgeInsets.all(0.5),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey, width: 2.0),
            borderRadius: BorderRadius.all(
              Radius.circular(15.0),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Container(
                child: Text(
                  '\$${tx.amount}',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20.0,
                  ),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(tx.title,
                      style: TextStyle(
                          fontWeight: FontWeight.bold, fontSize: 18.0)),
                  Text(
                    DateFormat().format(tx.dateTime),
                    style: TextStyle(color: Colors.grey),
                  )
                ],
              ),
            ],
          ),
        );
      }).toList(),
    );
  }
}
来自 transaction.dart:
class Transaction {
  Transaction(
      {@required this.id,
      @required this.title,
      @required this.amount,
      @required this.dateTime});

  final String id;
  final String title;
  final double amount;
  final DateTime dateTime;
}
来自 new_transaction.dart:
class NewTransaction extends StatelessWidget {
  final Function addTx;
  final title = TextEditingController();
  final amount = TextEditingController();

  NewTransaction(addNewTransaction, {this.addTx});
  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 5.0,
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.all(15.0),
        child: Column(
          children: <Widget>[
            Text(
              'Add New Transaction',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 20.0,
              ),
            ),
            TextField(
              decoration: InputDecoration(labelText: 'Title'),
              controller: title,
//              onChanged: (value) {
//                title = value;
//              },
            ),
            TextField(
              decoration: InputDecoration(labelText: 'Amount'),
              controller: amount,
//              onChanged: (value) {
//                amount = value;
//              },
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: FlatButton(
                padding: EdgeInsets.all(10.0),
                color: Colors.green,
                onPressed: () {
                  addTx(
                    title.text,
                    double.parse(amount.text),
                  );
                },
                child: Text(
                  'Add',
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

最佳答案

错误表示 transactionsnull .您没有向该参数传递任何内容。
您的 TransactionList构造函数有 2 个参数,但只使用了一个。改变它从

TransactionList(List<Transaction> userTransactions, {this.transactions});
TransactionList(this.transactions);

关于 flutter | Dart - NoSuchMethodError : The method 'map' was called on null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63536823/

相关文章:

unit-testing - 在 Mule 中的流单元测试中模拟过滤器

dart - flutter 输入中只允许两位小数吗?

android - 如何从Native Android Activity获取数据到Flutter路由库?

ruby-on-rails - Rails 测试失败,但系统运行正常

flutter - flutter 中的 SlideTransition 在滑入之前占用空间

性能测试 Flex 客户端

Dart:将具有不同返回值的函数作为参数的函数的类型安全

flutter - 如何在Dart中创建证书(X509Certificate)?

flutter - 如何使用 flutter 将视频添加到 firebase 数据库

flutter - CustomPaint 在其下方的小部件上绘制。如何避免?