I'm trying to test the VoidCallback so I created the main file, that have a function called from a flat button in the widget, which is in a separate file, but did not work.
main.dart
import 'package:flutter/material.dart';
import 'controller_test.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Retrieve Text Input',
      home: MyCustomForm(),
    );
  }
}
// Define a Custom Form Widget
class MyCustomForm extends StatefulWidget {
  @override
  _MyCustomFormState createState() => _MyCustomFormState();
}
class _MyCustomFormState extends State<MyCustomForm> {
  final myController = TextEditingController();
  @override
  void initState() {
    super.initState();
    myController.addListener(_printLatestValue);
  }
  _printLatestValue() {
    print("Second text field: ${myController.text}");
  }
  _test() {
    print("hi there");
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Retrieve Text Input'),
      ),
      body: Con(_test, myController)
    );
  }
}
controller_test.dart
import 'package:flutter/material.dart';
class Con extends StatelessWidget {
  Con(this.clickCallback, this.tc);
  final TextEditingController tc;
  final VoidCallback clickCallback;
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: <Widget>[
          TextField(
            onChanged: (text) {
              print("First text field: $text");
            },
          ),
          TextField(
            controller: tc,
          ),
          FlatButton(
            onPressed: () => clickCallback,
            child: Text("click me"),
          )
        ],
      ),
    );
  }
}
When I click the FlatButton in the widget, nothing is happening, I was expecting hi there to be printed
there are two options here.
onPressed: () => fun() is like onPressed argument is an anonymous method that calls fun.
onPressed: fun is like onPressed argument is the function fun.
I just found it in another answer here I was missing the (), so correct call is:
      FlatButton(
        onPressed: () => clickCallback(),
        child: Text("click me"),
      )
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With