I'm trying to create a widget that is a container and takes two arguments, the path to the image and the title of the Image. The widget code so far is:
class CharacterBox extends StatelessWidget {
final String imagePath;
final String characterName;
CharacterBox(this.imagePath, this.characterName);
@override
Widget build(BuildContext context) {
final CharacterBox args = ModalRoute.of(context).settings.arguments;
return Container(
margin: EdgeInsets.all(20.0),
height: 200,
width: 100,
child: Column(
children: [
Expanded(
child: Image(
image: AssetImage(args.imagePath),
alignment: Alignment.center,
fit: BoxFit.contain,
),
),
Container(
margin: EdgeInsets.all(5.0),
child: Text(
args.characterName,
style: TextStyle(color: Colors.white),
),
)
],
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
color: Color.fromARGB(255, 252, 70, 82)),
);
}
}
And I'm using the following to pass the arguments:
body: SafeArea(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
CharacterBox("assets/artwork.png", "Character"),
],
),
),
However I get the error saying:
The getter 'imagePath' was called on null.
Receiver: null
Tried calling: imagePath
I guess it is related to the ModalRoute declaration since I was doing it with this Documentation. However, I still didn't quiet get it.
You're using args.imagePath
should only be imagePath
Remove final CharacterBox args = ModalRoute.of(context).settings.arguments;
since you're already passing arguments via the constructor.
To improve the code readability and also perfomance I'd advice to following:
You can append const
on the constructor.
I'd change to this and use name parameters for clarity:
class CharacterBox extends StatelessWidget {
final String imagePath;
final String characterName;
const CharacterBox({
Key key,
this.imagePath,
this.characterName
}) : super(key: key);