I have this class name calculatorscreen inside that class I have function onBtnTap
import 'buttonWidget.dart';
import 'button_values.dart';
class CalculatorScreen extends StatefulWidget {
const CalculatorScreen({super.key});
@override
State<CalculatorScreen> createState() => _CalculatorScreenState();
}
class _CalculatorScreenState extends State<CalculatorScreen> {
String firstNumber = ""; //. 0-9
String operand = ""; //+-*/
String secondNumber = "";
@override
Widget build(BuildContext context) {
}
void onBtnTap(String value){
setState((){
firstNumber+=value;
});
}
}
and trying to access onBtnTap inside my widget file buildButton
import 'calculator_screen.dart';
import 'button_values.dart';
Widget buildButton(value){
return Padding(
);
}
i tried global key but it didn’t work also
final CalculatorScreen calScreen = new CalculatorScreen();
this method didn’t work
Notei removed most of the code that was unnecessary for my question.
2
Answers
You could put your
buildButton
function inside the_CalculatorScreenState
, then usesetState
directly inbuildButton
.Otherwise, pass
onBtnTap
as a parameter to the child widget, or the build function.More detailed answer on how to create reusable component with callback.
First create
Button
componentThen you can use above component in your stateful widget as shown below