How do I access my inherited widget in a dart file that doesn't build a widget in the tree?

87 Views Asked by At

I'm following this example to add my very first InheritedWidget into my app. I've created my _state_container.dart file and now want to use it.

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). 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. This file doesn't have a widget build function, so how would I use the container here?

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:

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...//
1

There are 1 best solutions below

3
Sayyid J On

its a class, Dart classes are the blueprint of the object, or it can be called object constructors. its just not initialize yet. just like that StateContainer it self;

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();