gpt4 book ai didi

flutter - 如何传递参数 runApp(MyApp());

转载 作者:行者123 更新时间:2023-12-01 23:40:44 28 4
gpt4 key购买 nike

我有如下代码,没问题。

void main() async {
Widget _defaultHome = new LoginPage();

runApp(new MaterialApp(
title: 'App',
debugShowCheckedModeBanner: false,
home: _defaultHome,
routes: <String, WidgetBuilder>{
// Set routes for using the Navigator.
'/tabs': (BuildContext context) => new TabsPage(),
'/login': (BuildContext context) => new LoginPage()
},
));
}

我想把它改成下面的代码,如何将_defaultHome传递给MyApp类?

void main() async {
Widget _defaultHome = new LoginPage();
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
// final textTheme = Theme.of(context).textTheme;
return MaterialApp(
title: 'Gaia',
debugShowCheckedModeBanner: false,
home: _defaultHome,
routes: <String, WidgetBuilder>{
// Set routes for using the Navigator.
'/tabs': (BuildContext context) => new TabsPage(),
'/login': (BuildContext context) => new LoginPage()
},
);
}
}

最佳答案

使用下面的代码,任何参数都可以通过构造函数传递。

  void main() async {
Widget _defaultHome = new LoginPage();
runApp(MyApp(defaultHome: _defaultHome,));
}

class MyApp extends StatelessWidget {
final Widget defaultHome;

const MyApp({
@required this.defaultHome,
Key key,
}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
// final textTheme = Theme.of(context).textTheme;
return MaterialApp(
title: 'Gaia',
debugShowCheckedModeBanner: false,
home: defaultHome,
routes: <String, WidgetBuilder>{
// Set routes for using the Navigator.
'/tabs': (BuildContext context) => new TabsPage(),
'/login': (BuildContext context) => new LoginPage()
},
);
}
}

关于flutter - 如何传递参数 runApp(MyApp());,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65002172/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com