I want data in a widget to be updated by calling setState() in the widget from another file which retrieves the updated data from a database (Please note that the displayed code is heavily reduced to only display my problem).
For this I think the easiest thing is to call a function with setState() inside of it, however there could be other ways to do this that I don’t know of and would be happy to hear.
My problem is, that I don’t know how to call that function: I want to call the function ‘foo’ inside of the stateful Widget ‘testWidget’ from a class ‘testClass’ in another file.
Here is the code of the first file:
class testWidget extends StatefulWidget {
const testWidget({super.key});
@override
State<testWidget> createState() => _testWidgetState();
}
class _testWidgetState extends State<testWidget> {
int value = 0;
@override
Widget build(BuildContext context) {
return Container();
}
void foo(int x){
setState(() {
value = x;
});
}
}
foo() should be called from this class:
import 'first_file.dart';
class testClass {
int x = 6;
void callFunctionInWidget(){
// Something like: testWidget.foo(x);
}
}
How can I achieve this?
The widget is displayed the whole time, i just want to update its data from another file.
I looked at many other questions on here, which are similar (e.g. call function of widget from parent widget), but I got no solution to work.
2
Answers
1. How to call a method in the state class of a stateful widget:
To update the data in a widget by calling setState() from another file, you can access the state class of the widget using a GlobalKey.
Depending on your use case, you can define different types of keys.
For example, You can Define a global key as a global variable, which you can have access everywhere :
Pass that key to your TestWidget’s constructor.
TestWidget(key:testWidgetKey)
Finally, you can call the foo() function:
2. State Management in Flutter
you’re looking for a state management solution in flutter.
You can find more data about different approaches here on Flutter’s official website, or many other blogs from the community.
I guess your approach is not right. If you want to access a database then you should make a specific dart file for that. Any function related to that data should be inside that file. You can call any method inside that file by using its object.
For example I have a method connect() to connect to my dataase.
This method is in my database.dart file. I can access this from any other file by just importing
and making an object of the class Database