i a new with this Flutter and now i am wondering how i can use a simple parameter inside my widget.
Here is first the code:
class Viewer extends StatefulWidget {
const Viewer({
super.key,
this.width,
this.height,
required this.srcURL,
});
final double? width;
final double? height;
final String srcURL;
@override
State<Viewer> createState() => _ViewerState();
}
class _ViewerState extends State<Viewer> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Header')),
body: const ModelViewer(
backgroundColor: Color.fromARGB(0xFF, 0xEE, 0xEE, 0xEE),
src: widget.srcURL,
alt: 'Homer Cool',
ar: true,
autoRotate: true,
iosSrc: 'SOMEURLHERE',
disableZoom: true,
),
),
);
}
}
Now i want to use the parameter "srcURL" iin my widget in "src:"
I dont know, but i tried now many things and thats my last status. So far nothing worked for me.
And the current code gives me the error "Invalid constant value."
How to do it in flutter properly, so i can use the paramater as a "variabe" in the widget.
Many thanks
I was using google and many people used "widget.srcURL" or "$srcURL". Tried also other possibilities but i cant get the parameter as a variable in my widget running.
2
Answers
The fix for this problem is as simple as removing the
const
keyword from where you are calling theModelViewer
widget.In dart, if a variable is declared as
const
, it becomes a compile time constant. However, in your code, thewidget.srcURL
property would be generated a runtime, hence the error.The official Dart docs explain this very well.
Issue is due to the use of the
const
keyword in your widget tree. Theconst
keyword is used to define compile-time constants, which means that all values inside aconst
widget must be known at compile time. Sincewidget.srcURL
is a runtime variable, it cannot be used inside aconst
widget.So, you need to remove the
const
keyword from the ModelViewer widget.