Flutter callback function could be scary idea for beginners. Here I explained everything in detail what you need create a callback function.
Using callback function we can pass data between classes. As we pass data, we can trigger new rebuild of UI using new data. Callback functions get trigged when certain events happen. Here we triggered an event from my_buttons.dart class on the onTap() event.
After events happen we need to use setState() to trigger rebuild of the UI.
First we need to pass the callback function to my_buttons.dart class. We did that when we called on MyButtons() constructor.
Since we are going to use setState() function, we need to have a StatefulWidget. MyApp class is a StatefulWidget.
main.dart
import 'package:flutter/material.dart';
import 'package:setstate_callback/my_buttons.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String topic="Packages";
callback(varTopic){
setState(() {
topic=varTopic;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Learning Flutter"),
),
body: Column(
children: [
Container(
width: double.maxFinite,
height: 70,
margin: const EdgeInsets.only(top:50,left: 40,right: 40, bottom: 20),
decoration: BoxDecoration(
color:Colors.lightBlue,
borderRadius: BorderRadius.circular(20)
),
child: Center(
child: Text(
"We are learning Flutter "+topic,
style: TextStyle(
fontSize: 20,
color:Colors.white
),
),
),
),
MyButtons(topic: "Cubit", callbackFunction:callback),
MyButtons(topic: "BLoc", callbackFunction:callback),
MyButtons(topic: "GetX", callbackFunction:callback)
],
),
),
);
}
}
We is code for MyButtons class which receives the callback function.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyButtons extends StatelessWidget {
final String topic;
final Function callbackFunction;
const MyButtons({Key? key, required this.topic, required this.callbackFunction}) : super(key: key);
@override
Widget build(BuildContext context) {
return
GestureDetector(
onTap: (){
callbackFunction(topic);
},
child: Container(
width: double.maxFinite,
height: 70,
margin: const EdgeInsets.only(top:20,left: 40,right: 40, bottom: 20),
decoration: BoxDecoration(
color:Colors.lightBlue,
borderRadius: BorderRadius.circular(20)
),
child: Center(
child: Text(
topic,
style: TextStyle(
fontSize: 20,
color:Colors.white
),
),
),
),
);
}
}