【发布时间】:2022-02-10 09:27:46
【问题描述】:
我正在尝试完成我的学校作业,但在将数据传递到无状态小部件时遇到了困难。我有以下课程:
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;
}
上面有我的messageData需要传递。
基本上,我希望能够导航到第 2 页,但在 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 navigation