Home > other >  How to pass an object as a parameter to a screen in flutter?
How to pass an object as a parameter to a screen in flutter?

Time:11-26

I have an object in a class (chatPage.dart):

class _ChatState extends State<Chat> {
    
      List<ChatModel> chats = [
        ChatModel('fa', 'Fred', 'person.svg', '13:12', 'Some parts of message...'),
        ChatModel('da', 'David', 'person.svg', '11:52', 'Some parts of message...'),
        ChatModel('ax', 'Alex', 'person.svg', '16:39', 'Some parts of message...'),
        ChatModel('Ama', 'Amanda', 'person.svg', '19:16', 'Some parts of message...')
      ];
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: chats.length,
        itemBuilder: (context, index) => ChatScreen(
          chatModel: chats[index],
        ),
      )
    );
  }
}

I want this object to be passed into the following class (chatScreen.dart):

class ChatScreen extends StatefulWidget {
  const ChatScreen({super.key, required this.chatModel});
  final ChatModel chatModel;

  @override
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  bool showEmoji = false;
  FocusNode focusNode = FocusNode();
  TextEditingController textEditController = TextEditingController();
  late String myUsername;
  var targetUsername = chatModel.username;//chatModel cannot be used here. I need its value.
.
.
.
.
}

The problem is that I can only access the passed object inside Widget build(BuildContext context) {. . .} while I need that object outside of widget. How is it possible? I studied the similar question here.

CodePudding user response:

You need to use late:

late var targetUsername = widget.chatModel.username;
  • Related