flutter 使用ModalRoute检索参数时出错

rn0zuynd  于 2023-03-19  发布在  Flutter
关注(0)|答案(3)|浏览(657)

每次调用modalroute从一个命名路由中检索参数时,我都会得到null。
下面是代码片段:

Navigator.pushNamed(
           context, 
           VerifyCode.routeName, 
           arguments: {'code': randValue,},
           );

这是我重新获得论证的地方:

Widget build(BuildContext context) 
{
   //Get the dialog provider to display information
   alertViewModel = Provider.of<AlertViewModel>(context);

   //Retrieve the route argument
   final routeArgs =
           ModalRoute.of(context).settings.arguments as Map<String, int>;

    final securityCode = routeArgs['code']; <-- Error happens here

    print('Code =' + securityCode.toString());
   return Container()

}
我应该从Map中获取一个整数,但却得到了错误:

════════ Exception Caught By widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building VerifyCode(dirty, dependencies: [InheritedProvider<AlertViewModel>, _ModalScopeStatus], state: _VerifyCodeState#98992):
The method '[]' was called on null.
Receiver: null
Tried calling: []("code")
When the exception was thrown, this was the stack
#0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:50:5)
#1      _VerifyCodeState.build package:accidentapp/screens/verifycode.dart:42
#2      StatefulElement.build 
package:flutter/…/widgets/framework.dart:4012
#3      ComponentElement.performRebuild package:flutter/…/widgets/framework.dart:3924
#4      Element.rebuild
package:flutter/…/widgets/framework.dart:3721 ═══════════════════════════════════════════════════════════════════

routeArgs始终为空。我尝试使用一个类来传递值而不是Map,但我得到了相同的错误。不确定我做错了什么。

t40tm48m

t40tm48m1#

将设置传递到材料页面路由

Route<dynamic> generateRoute(RouteSettings settings) {
return MaterialPageRoute(
  builder: (BuildContext context) {
    //some custom code
    return Page();
  },
  settings: settings
);

}

ldxq2e6h

ldxq2e6h2#

试试这样

String rawJson = '{"code":randValue}';
 Map<String, dynamic> map = jsonDecode(rawJson);

 Navigator.pushNamed(context, VerifyCode.routeName, arguments: map);

接收数据使用:-

final Map<String, dynamic> map = ModalRoute.of(context).settings.arguments;

您可以使用获取数据

map["code"]
1bqhqjot

1bqhqjot3#

只需移除Map占位符
final routeArgs = ModalRoute.of(context).settings.arguments as Map;

相关问题