You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发遇Too many positional arguments参数传递错误求助

问题修复方案

报错原因

该错误是因为NewTransaction组件的类成员声明、构造函数位置错误,导致组件默认使用无参构造,你调用时传入1个位置参数就会触发参数不匹配的报错。

具体问题点

  • 你把NewTransaction的构造函数、addTx成员变量、输入框控制器全都写在了build方法内部,这部分属于类的全局成员,应该放在build方法外、类定义内部的位置。
  • addTx的函数类型没有声明参数,和你传入的_addNewTransaction(需要接收String、double两个参数)不匹配,就算参数传对后续调用也会报错。
  • build内给addTx赋值了空的无参实现,会覆盖你外部传入的函数,导致新增交易逻辑无法生效。

修复后的new_transaction.dart代码

import 'package:flutter/material.dart';

class NewTransaction extends StatelessWidget {
  // 类成员统一放在build方法外
  final Function(String txTitle, double txAmount) addTx;
  final titleController = TextEditingController();
  final amountController = TextEditingController();

  // 构造函数放在类内部、build外
  NewTransaction(this.addTx, {super.key});

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 5,
      child: Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            TextField(
              decoration: const InputDecoration(labelText: "Title"),
              controller: titleController,
            ),
            TextField(
              decoration: const InputDecoration(labelText: "Amount"),
              controller: amountController,
              keyboardType: const TextInputType.numberWithOptions(decimal: true),
            ),
            // 若你的Flutter版本仍支持FlatButton可保留原有代码
            TextButton(
              onPressed: () {
                addTx(
                  titleController.text,
                  double.parse(amountController.text),
                );
              },
              child: const Text("Add Transaction"),
              style: TextButton.styleFrom(foregroundColor: Colors.purple),
            )
          ],
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者Manan Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:39:01