I am trying to transfer data with navigator.pushNamed but I am getting error and I don't know how to solve it.
My Code;
First screen transfer data
Navigator.pushNamed(context, '/resultscreen',
arguments: <dynamic, dynamic>{
"totalCorrectGuess": totalCorrectGuess,
"imageName": imageName,
});
`Second screen use data
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'),
)
],
),
),
),
);
}
}
Line of code error
Text('totalCorrectAnswer: \n${gameScreenData!['totalCorrectGuess']}'),
Image.asset('assets/images/${gameScreenData!['imageName']}.png'),
You have to cast the gameScreenData
to Map
final gameScreenData = (ModalRoute.of(context)?.settings.arguments) as Map;
Update
In case you don't want to always pass arguments
use this instead:
final gameScreenData = (ModalRoute.of(context)?.settings.arguments ?? {}) as Map;
Here you first check if it's not null with ??
. If it is null it will use {}
as default. But then you need to check in other parts of your code whether gameScreenData
has necessary data or not.
Text('totalCorrectAnswer: \n${gameScreenData['totalCorrectGuess'] ?? '0'}'),
Image.asset('assets/images/${gameScreenData['imageName'] ?? 'default'}.png'),
Here the same thing as before happens. You check whether or not totalCorrectGuess
and imageName
fields are null and if they are assign default values to them.
If you always need the data make sure to pass it every time you route, otherwise use this.