在main.dart上我有StatelessWidget和StatefulWidget。
在StatefulWidget中,变量myUsername设置来自sharedPreferences的用户名。
如何将用户名从StatefulWidget传递给StatelessWidget
class MyHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/home',
routes: {
'/home': (context) => MyHomePage(title: 'Home'),
'/myUser':(context) => MyUser(paramUser: "set here username from StatefulWidget" )
},
title: 'app',
);
}
}或者有更好的解决方案吗?
发布于 2022-05-02 13:57:39
导航只执行一页到另一页的操作。因此,如果您想将数据从一个传递到另一个,那么为任何特定页面创建构造函数,然后将数据传递给它们。
class UserPage extends StatefulWidget {
final bool isMyPost;
final String postId;
const UserPage({Key? key, required this.postId, this.isMyPost = false}) : super(key: key);
@override
_ UserPage State createState() => _ UserPage State();
}
class _ UserPage State extends State< UserPage > {
//Rest of Code
}然后像这样导航:
Navigator.push(context,
MaterialPageRoute(
builder: (_) => Preview(
postId:provider.searchPost[index].postId,
)));https://stackoverflow.com/questions/72087254
复制相似问题