I have a class where I declare an optional void function
as parameter
for the constructor of that class.
If the parameter (that optional void function) is not null I want to show a button.
On my second class I call the constructor and I pass a function to that optional parameter.
The problem is that my button never shows up on the screen and I don’t know what I’m doing wrong.
Can someone please help me to figure out where is the issue in my code ?
Here is my code:
import 'package:flutter/material.dart';
class Login extends StatefulWidget {
final Function(void)?
showCreateAccountBtn; // This parameter is optional and represent a void function.
const Login({
Key? key,
this.showCreateAccountBtn,
}) : super(key: key);
@override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("First Screen")
),
body: Column(children: [
widget.showCreateAccountBtn != null
? TextButton(
style: ButtonStyle(
foregroundColor:
MaterialStateProperty.all<Color>(Colors.blue)),
onPressed: () => widget.showCreateAccountBtn,
child: const Text('Create an account'))
: const SizedBox()
]));
}
}
class FirstScreen extends StatefulWidget {
const FirstScreen({Key? key}) : super(key: key);
@override
State<FirstScreen> createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
@override
Widget build(BuildContext context) {
return Login(showCreateAccountBtn: _onCreateAccountTapped());
}
Function(void)? _onCreateAccountTapped() {
print("Click on Create Acc");
return null;
}
}
Here is the GIST link (not working for unknown reasons): https://dartpad.dev/?id=58294fa8eed37b016d0b257fee2f1317
Thanks for reading this !
3
Answers
Here is the full fix:
to this :
onPressed: () => widget.showCreateAccountBtn,
to this
onPressed: widget.showCreateAccountBtn?.call(),
more info here What is the implementation of call() in dart?