我正在努力完成学校作业,在将数据传递到无状态小部件时遇到了困难。我有以下课程:
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;
}
上面有我的消息Data,我需要通过。
基本上,我希望能够导航到Page2,但我在Navigator.push()
上一直遇到错误。错误详细信息:Type' can't be assigned to the parameter type 'MessageData'.
当Page2((上没有参数时,错误消息:The named parameter 'messageData' is required, but there's no corresponding argument.
必须使用构造函数传递数据。我希望你能从这个链接中得到一个想法。
您可以将参数传递给小部件,就像传递给Flutter
的小部件一样:
///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),
);
}
}
如果是State
中的StatefulWidget
,则可以使用widget.field
访问值。