Home > database >  How to pass data in flutter on Stateless Widget?
How to pass data in flutter on Stateless Widget?

Time:02-10

I'm trying to do my school 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;
}




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.

CodePudding user response:

You have to pass data using Constructor. I hope you will get an idea from this link.

CodePudding user response:

You can pass arguments to widgets just like you pass to Flutter's widgets:

///Creating Page2 instances
Page2(text: 'text');
Page2.otherConstructor('text');

///This is how you pass values to widgets
class Page2 extends StatelessWidget {
  //Pass `this.field` to the constructor so that you are asking for the field you created.
  const Page2({Key? key, required this.text}) : super(key: key);
  const Page2.otherConstructor(this.text);

  final String text;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text(text),
    );
  }
}

And in case it's a StatefulWidget in the State you can access the values with widget.field.

  • Related