颤振 | Navigator.pushNamed 我收到一个错误,运算符“[]”没有为类型 'Object' 定义。尝试定义运算符 '[]'

Flutter | Navigator.pushNamed I got an error, The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'

我正在尝试使用 navigator.pushNamed 传输数据,但出现错误,我不知道如何解决。

我的代码;

首屏传输数据

Navigator.pushNamed(context, '/resultscreen',
          arguments: <dynamic, dynamic>{
            "totalCorrectGuess": totalCorrectGuess,
            "imageName": imageName,
          });

`副屏使用数据

class _ResultScreenState extends State<ResultScreen> {
  @override
  Widget build(BuildContext context) {
    Object? gameScreenData = ModalRoute.of(context)?.settings.arguments;

    return Scaffold(
      appBar: AppBar(
        title: const Text(AppTextContants.appBarTitleResultScreen),
        centerTitle: true,
      ),
      body: Center(
        child: Container(
          margin: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              **Text('totalCorrectAnswer: \n${gameScreenData!['totalCorrectGuess']}'),**
              **Image.asset('assets/images/${gameScreenData!['imageName']}.png'),**
              ElevatedButton(
                onPressed: () {},
                child: const Text('data'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

代码行错误

Text('totalCorrectAnswer: \n${gameScreenData!['totalCorrectGuess']}'),
Image.asset('assets/images/${gameScreenData!['imageName']}.png'),

您必须将 gameScreenData 转换为 Map

final gameScreenData = (ModalRoute.of(context)?.settings.arguments) as Map;

更新

如果您不想总是通过 arguments,请改用此方法:

final gameScreenData = (ModalRoute.of(context)?.settings.arguments ?? {}) as Map;

这里你先用??检查它是否不为空。如果它为空,它将使用 {} 作为默认值。但是随后您需要检查代码的其他部分 gameScreenData 是否有必要的数据。

Text('totalCorrectAnswer: \n${gameScreenData['totalCorrectGuess'] ?? '0'}'),
Image.asset('assets/images/${gameScreenData['imageName'] ?? 'default'}.png'),

这里发生了和以前一样的事情。您检查 totalCorrectGuessimageName 字段是否为空,以及是否为它们分配了默认值。

如果您总是需要数据,请确保每次路由时都传递它,否则使用它。

您正在传递 Map,因此您可以对其进行类型转换

Map? gameScreenData = ModalRoute.of(context)?.settings.arguments as Map;

并使用喜欢

if (gameScreenData != null) ...[
  Text(
      'totalCorrectAnswer: \n${gameScreenData['totalCorrectGuess'] ?? "default value"}'),
  if (gameScreenData['imageName'] != null)
    Text('assets/images/${gameScreenData['imageName']}.png'),
],