0

I have created a class for new Transaction entry form.. where 2 TextField and a Button..

I have created a Function named myf(), I am almost successful but to improve my knowledge and better coding.... I wish to call function like pointer..but it does not work...where I am getting wrong?

I can solve by repeating code inside onsubmit but its not good level job...

POINTER WORKS WITH TEXTBUTTON AND DOES NOT WORK WITH TEXTFIELD ONSUBMIT..THIS IS MY CONFUSION...

here is my coding

import 'package:flutter/material.dart';
class NewTransaction extends StatelessWidget {
  final Function func;
  NewTransaction(
    this.func
  );
  void myf() {
    func(txttitle.text,double.parse(txtamount.text));
  }
  final txttitle = TextEditingController();
  final txtamount = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20.0,horizontal: 8.0),
      child: Card(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10.0)),
        elevation: 10,
        child: Container(
          padding: EdgeInsets.all(10),
          child: Column(
            children: [
              TextField(
                controller: txttitle,
                onSubmitted: (_){
                  myf();
                },
                decoration: InputDecoration(labelText: 'Enter Title'),
              ),
              TextField(
                onSubmitted: (_)=>myf, // this one is not working
                keyboardType: TextInputType.number,
                  controller: txtamount,
                  decoration: InputDecoration(labelText: 'Enter Amount')),
                  TextButton(
                  onPressed: myf,
                  child: Text('Add Record'))
            ],
          ),
        ),
      ),
    );
  }
}

Irfan Ganatra
  • 967
  • 3
  • 13

1 Answers1

1

While we do ()=>MyFunc() we create an anonymous(/inline) function.

onSubmitted: (_)=>myf, means , when onSubmitted will trigger, just return myf, here myf is just a variable, But we need to call the method, that's why you need to use onSubmitted: (_)=>myf()

A better way will be creating myf with parameter,

void myf(String value){}

And use

onSubmitted: myf,

Here is a great answer about inline function and you can check others answers.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • I agree with you..but I am confuse here that It works with TextButton onPressed without () – Irfan Ganatra Jun 11 '22 at 12:49
  • `onSubmitted` comes with a string , that's why we cant directly use assign it like `onTap:myf`, here `myf` is a variable/reference of method. but when we wrap it with another method we need use `()` to call the method, else it is just a reference/variable. – Md. Yeasin Sheikh Jun 11 '22 at 12:53