如何在Dart / Flutter的另一个文件的类中调用Widget中的函数?

huangapple go评论69阅读模式
英文:

How to call function in Widget from class of another file in Dart / Flutter?

问题

我想通过从另一个文件中检索来自数据库的更新数据并在该小部件中调用setState()来更新小部件中的数据(请注意,显示的代码已大幅简化以仅显示我的问题)。
对此,我认为最简单的方法是调用一个内部包含setState()的函数,然而可能有其他我不知道的方法,我很乐意听到。
我的问题是,我不知道如何调用那个函数:我想从另一个文件中的一个名为'testClass'的类中调用状态小部件'testWidget'内部的函数'foo'。
以下是第一个文件的代码:

```dart
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() 应该从这个类中调用:

import 'first_file.dart';

class testClass {
  int x = 6;
  void callFunctionInWidget(){
    // 类似于:testWidget().foo(x);
  }
}

我如何实现这一点?
小部件一直显示,我只想从另一个文件中更新它的数据。

我查看了这里的许多类似的问题(例如从父小部件调用小部件的函数),但我没有找到解决方案可行。


<details>
<summary>英文:</summary>

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&#39;t know of and would be happy to hear.
My problem is, that I don&#39;t know how to call that function: I want to call the function &#39;foo&#39; inside of the stateful Widget &#39;testWidget&#39; from a class &#39;testClass&#39; 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.

</details>


# 答案1
**得分**: 1

我猜你的方法不正确。如果你想访问数据库,那么你应该为此创建一个特定的Dart文件。与该数据相关的任何函数都应该在该文件中。你可以通过使用它的对象在该文件中调用任何方法。

例如,我有一个用于连接到我的数据库的方法connect()。

```dart
class Database {

  Future<void> connect() async {
  }
}

这个方法在我的database.dart文件中。我可以通过导入以下方式从任何其他文件中访问它:

import 'package:project_name/database.dart';

Database db = Database();
await db.connect();
英文:

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.

class Database{

    Future&lt;&gt;connect()async{
    }
}

This method is in my database.dart file. I can access this from any other file by just importing

import &#39;package:project_name/database.dart&#39;;

and making an object of the class Database

Database db = Database();
await db.connect();

答案2

得分: 0

  1. 如何在有状态小部件的状态类中调用方法:

要通过从另一个文件调用setState()来更新小部件中的数据,您可以使用GlobalKey来访问小部件的状态类。根据您的用例,您可以定义不同类型的键。
例如,您可以将全局键定义为全局变量,您可以随处访问它:

GlobalKey<testWidget> testWidgetKey = GlobalKey();

将该键传递给您的TestWidget的构造函数。
TestWidget(key: testWidgetKey)
最后,您可以调用foo()函数:

testWidgetKey.currentState?.foo();
  1. Flutter中的状态管理:

如果您正在寻找Flutter中的状态管理解决方案,您可以在Flutter官方网站上的此处找到更多关于不同方法的数据,或者查看社区中的许多其他博客。

英文:

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 :

GlobalKey&lt;testWidget&gt; testWidgetKey = GlobalKey();

Pass that key to your TestWidget's constructor.
TestWidget(key:testWidgetKey)
Finally, you can call the foo() function:

textWidgetKey.currentState?.foo();

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.

huangapple
  • 本文由 发表于 2023年6月26日 00:11:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定