Reputation: 39
I'm very new to Dart. I was learning basic stuff for Flutter. And I've got some questions while working on BottomNavigationBar:
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
I have no idea why there's index as a parameter in the function. Where is it coming from? Also, in the setState function, why is there a function and what does it mean? I'm sorry these questions are very elementary but I couldn't find clear answers!
Thank you in advance!
Upvotes: 1
Views: 1328
Reputation: 143
Firstly onTap is a callback function and depending on widget it can have zero o more parameters. For example in InkWell widget the onTap callback has no parameters and in BottomNavigationBar the onTap callback take index as parameter to recognize the index of items in that widget.
Secondly, as you know setState function is used for updating UI and called inside State class.
When you use StatefulWidget, every StatfulWidget has a state object like code below:
class MyWidget extends StatefulWidget { // immutable Widget
@override
_MyWidgetState createState() => _MyWidgetState();
// creating State Object of MyWidget
}
class _MyWidgetState extends State<MyWidget> { // State Object
@override
Widget build(BuildContext context) {
return Container();
}
}
Since StatefulWidget itself is immutable (cannot be modified), we use State Object to modify the UI.
We tell this State Object to update our screen's UI using a function called setState().
void setState(VoidCallback fn) {
...
}
This setState() takes a function as it's parameter.
The function called inside setState does not need have any parameter as well.
finally, you can hold ctrl key and click on which function you want and see the implementation of the function.
Upvotes: 0
Reputation: 999
onTap: (index) {} : Index use for Keep track of the index of the selected BottomNavigationBarItem.
setState() : Whenever you change the state of a State object, make the change in a function that you pass to setState.
For more info :
onTap : https://api.flutter.dev/flutter/material/BottomNavigationBar/onTap.html
setState : https://api.flutter.dev/flutter/widgets/State/setState.html
Upvotes: 1