DEV Community

GiftMogale
GiftMogale

Posted on

How to pass data in flutter on Stateless Widget?

I'm trying to do an assignment, and have run into difficulty with passing data into Stateless Widgets. I have the following classes:

 class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Page1(),
    );
  }
}




class Page1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: ElevatedButton(
        onPressed: () {
          Navigator.push(
              context, MaterialPageRoute(builder: (context) => Page2(messageData: messageData)));
        },
        child: Text('Request Chat'),
      )),
    );
  }
}




class Page2 extends StatelessWidget {
  //Navigation
  static Route route(MessageData data) => MaterialPageRoute(
        builder: (context) => Page2(
          messageData: data,
        ),
      );

  const Page2({Key? key, required this.messageData}) : super(key: key);

  final MessageData messageData;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: Theme.of(context).iconTheme,
        centerTitle: false,
),
),
},


@immutable
class MessageData {
  const MessageData(
      {required this.senderName,
      required this.message,
      required this.messageDate,
      required this.dateMessage,
      required this.profilePicture});

  final String senderName;
  final String message;
  final DateTime messageDate;
  final String dateMessage;
  final String profilePicture;
}

Enter fullscreen mode Exit fullscreen mode

There is my messageData above that I need to pass.

Basically, I want to be able to Navigate to Page2() but I keep getting an error at Navigator.push() . Error details: Type' can't be assigned to the parameter type 'MessageData'.

And when there are no arguments on Page2() the error message: The named parameter 'messageData' is required, but there's no corresponding argument.

Top comments (0)