首页 > 解决方案 > Flutter:加速了 2 个位置参数

问题描述

我的代码有问题,我尝试尽可能简短地解释它,实际上:我想用 initalroute 命令重定向,只是在代码中它给了我在标题中写的问题。我只是想确保当我打开 Web 应用程序时,只要我登录并转到显示 / 登录 / 仪表板的 url 上的主页。

//第一部分代码

  initialRoute: '/',
  // Redirect a /login
  //Capire come fare redirect a /dashboard
  routes: {
    '/login': (context) => LoginPage(),
    '/dashboard': (context) => HomePage(), //here is the error 2 positional argument(s)
  },

//第二部分(主页)

factory HomePage.fromBase64(String jwt) => HomePage(
  jwt,
  json.decode(
      ascii.decode(base64.decode(base64.normalize(jwt.split(".")[1])))));

 final String jwt;
 final Map<String, dynamic> payload;

 @override
 Widget build(BuildContext context) {
 return Scaffold(
    appBar: AppBar(
  backgroundColor: Colors.grey,
  elevation: 0.3,
  centerTitle: false,
  title: Row(
    children: [
      Text(
        'wow',
        style: Theme.of(context)
            .textTheme
            .headline6!
            .copyWith(color: Colors.orange, fontWeight: FontWeight.bold),
      )
    ],
  ),
));

} } 希望有人能给我一个解决方案,谢谢:)

标签: flutter

解决方案


你得到的错误是因为HomePage需要两个参数,但你没有传递任何参数,这是因为它们是位置参数,这意味着它们必须被传递,你可以通过将它们包装{ }HomePage构造函数中来使它们成为可选

它会是这样的:

class HomePage extends StatelessWidget {
  // add {} here to make it optional
  const HomePage({
    Key key,
    this.jwt,
    this.payload,
  })  : super(key: key);

  final String jwt;
  final Map<String, dynamic> payload;
}

这肯定会解决问题,但可能无法满足您的要求,因为您希望在创建 HomePage 时同时传递 jwt 和有效负载,但这将使HomePage创建时不会抱怨缺少参数,因此另一种解决方案是在 HomePage 构造函数中实际传递参数,如下所示:

routes: {
    '/login': (context) => LoginPage(),
    '/dashboard': (context) => HomePage(/** pass the arguments here*/), 
  },

推荐阅读