Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to execute the VoidCallback in flutter

Tags:

flutter

dart

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

like image 799
Hasan A Yousef Avatar asked Dec 17 '22 19:12

Hasan A Yousef


2 Answers

there are two options here.

  1. onPressed: () => fun() is like onPressed argument is an anonymous method that calls fun.

  2. onPressed: fun is like onPressed argument is the function fun.

like image 182
Harsh Bhikadia Avatar answered Feb 08 '23 06:02

Harsh Bhikadia


I just found it in another answer here I was missing the (), so correct call is:

      FlatButton(
        onPressed: () => clickCallback(),
        child: Text("click me"),
      )
like image 31
Hasan A Yousef Avatar answered Feb 08 '23 06:02

Hasan A Yousef