使用onPressed切换到另一个屏幕不能正常工作



我正在尝试切换到不同的屏幕在Flutter项目使用onPressed,但它不产生任何结果不确定是什么原因。

主界面:

onPressed: () {
const User_Profile();
print("Hello");
},

下面是用户配置文件:

class User_Profile extends StatefulWidget {
const User_Profile({Key? key}) : super(key: key);

@override
State<User_Profile> createState() => _user_profileState();
}

class _user_profileState extends State<User_Profile> {
@override
Widget build(BuildContext context) {
return const Text("User Profile");
}
}

问题:如何使用Onpressed切换屏幕?我做错了什么,注意到每次都打印用于调试的单词Hello。

尝试下面的代码并使用Navigator.push导航

ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => User_Profile(),
),
);
},
child: const Text('User Profile'),
),

你必须像这样使用一个函数来代替你的类:

Navigator.push(context, MaterialPageRoute(builder: (context)=>User_profile()));

称之为:

onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=>User_profile()));
},

而不是:

onPressed: () {
const User_Profile();
print("Hello");
},

,因为您知道您不能通过调用类中的构造函数方法来访问特定的页面。你有两种方法:

  1. 使用Navigator.push如下:

    Navigator.push(
    context,
    MaterialPageRoute(
    builder: (context) => User_Profile(),
    ),
    );
    

,你可以发送参数到下一页的构造函数参数,如:User_Profile(name: 'yourName').2),你可以使用Navigator.pushNamed。你可以在项目的主类中定义routeName,像这样:

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(
MyApp(),
);
}
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
canvasColor: Colors.transparent,
),
initialRoute: '/',
routes: {
'/': (context) => Splash(),
'/user_profile': (context) => User_Profile(),
},
);
}
}

如你所见,你定义了一个routeName'/user_profile',你可以使用Navigator.pushNamed,如果你想传递参数到下一页,你必须使用arguments,像这样:

Navigator.pushNamed(
context,
'/user_profile',
arguments: {"name" : "yourName"},);

这段代码是用来获取你在User_Profile中传递的参数:

var arguments = ModalRoute.of(context)!.settings.arguments as Map;
var name = arguments['name'] as String;

我建议您使用第二种方法来了解项目的所有路由。

好运;)

最新更新