[英]How do I access my inherited widget in a dart file that doesn't build a widget in the tree?
I'm following this example to add my very first InheritedWidget
into my app.我正在按照这个示例将我的第一个InheritedWidget
添加到我的应用程序中。 I've created my _state_container.dart
file and now want to use it.我已经创建了我的_state_container.dart
文件,现在想使用它。
To start, I'd like to use it in the widget where I display the chats in a group chat.首先,我想在群聊中显示聊天的小部件中使用它。 This widget is in the file receivedChats.dart
(chat header).此小部件位于文件receivedChats.dart
(聊天标题)中。 I see in the example that all I would need to do is instantiate the container
in the target's widget build function, but the problem is that this widget is calling another file called message_dao.dart
to handle all data from Firebase.我在示例中看到,我需要做的就是在目标的小部件构建 function 中实例化container
,但问题是这个小部件正在调用另一个名为message_dao.dart
的文件来处理来自 Z0354489FF8D0324EF544A 的所有数据This file doesn't have a widget build function, so how would I use the container here?该文件没有小部件构建 function,那么我将如何在这里使用容器?
File Structure:文件结构:
main.dart
|
wrapper.dart
|
home.dart //or authenticate.dart if user is not logged in
|
chatScreen.dart
| |
msgInput.dart receivedChats.dart - message_dao.dart
This is what I've already tried, but it gives 2 errors:这是我已经尝试过的,但它给出了2个错误:
class MessageDao {
final container = StateContainer.of(context); //ERROR: Undefined name 'context'.
final chatState = container.chatState; //ERROR: The instance member 'container' can't be accessed in an initializer.
//...rest of code...//
its a class, Dart classes are the blueprint of the object, or it can be called object constructors.它的一个 class、Dart 类是 object 的蓝图,也可以称为 ZA8CFDE6331B49EB2AC96B8 构造函数。 its just not initialize yet.它只是还没有初始化。 just like that StateContainer
it self;就像那个StateContainer
一样;
class MessageDao {
//here :
final StateContainerState container;
MessageDao(this.container);
chatstate(){
return container.chatState;
}
}
you need to initialize it somewhere in your code when there is an actual build context that can be passed to:当存在可以传递给的实际构建上下文时,您需要在代码中的某处对其进行初始化:
final messageDaoState = MessageDao(StateContainer.of(context));
final chatstate = messageDaoState.chatstate();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.