Flutter Stateful Constructor Const Problem - flutter

I'm following tutorial on udemy and i found this weird error and i already read some doccumentation and i still didnt find the right answer to have constructor with initail value.
her is my code
class MapScreen extends StatefulWidget {
final PlaceLocation initialLocation;
final bool isSelecting;
const MapScreen({Key? key, this.initialLocation = PlaceLocation( //here there is an error "The default value of an optional parameter must be constant. (Documentation)"
latittude: 37.422,
longitude: -122.084,
address: "Example stree no 1",
), this.isSelecting = false}) : super(key: key);
#override
_MapScreenState createState() => _MapScreenState();
}
however if i delete those const new error come out
class MapScreen extends StatefulWidget {
final PlaceLocation initialLocation;
final bool isSelecting;
MapScreen({Key? key, this.initialLocation = PlaceLocation( //The default value of an optional parameter must be constant. (Documentation)
latittude: 37.422,
longitude: -122.084,
address: "Jl. Imambonjol",
), this.isSelecting = false}) : super(key: key);
#override
_MapScreenState createState() => _MapScreenState();
}
i also tried to follow the instruction and modify my code like this:
class MapScreen extends StatefulWidget {
final PlaceLocation initialLocation;
final bool isSelecting;
MapScreen({
this.initialLocation =
const PlaceLocation(latitude: 37.422, longitude: -122.084),
this.isSelecting = false,
});
#override
_MapScreenState createState() => _MapScreenState();
}
but the error still came out

I was able to fix your mistake, below I will attach the solution code and a screenshot of the console:
// Fake model:
class PlaceLocation {
final double latittude;
final double longitude;
final String address;
// Make this constructor const to solve your problem:
const PlaceLocation(
{required this.latittude,
required this.longitude,
required this.address});
}
class MapScreen extends StatefulWidget {
final PlaceLocation initialLocation;
final bool isSelecting;
// Also don't forget to put const before PlaceLocation() in this constructor:
const MapScreen(
{Key? key,
this.initialLocation = const PlaceLocation(
latittude: 37.422,
longitude: -122.084,
address: "Example stree no 1",
),
this.isSelecting = false})
: super(key: key);
#override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
#override
Widget build(BuildContext context) {
// Console test to check default values:
print("lattitude: " +
MapScreen().initialLocation.latittude.toString() +
"\nlongitude: " +
MapScreen().initialLocation.longitude.toString() +
"\naddress: " +
MapScreen().initialLocation.address.toString());
return Scaffold(body: Container());
}
}
All you have to do is make your model (PlaceLocation) constructor const.

Related

Flutter: Cannot pass a boolean type parameter through GoRouter

I want to pass a bool type parameter through GoRouter but I get this message error:
The argument type String cannot be assigned to the parameter type "bool"
But I can't really figure out where this error comes from.
Is String the only allowed type in queryParams ?
Here's my code:
main.dart
final GoRouter _router = GoRouter(routes: [
GoRoute(name: 'home', path: '/home', builder: ((context, state) => Home(
location: state.queryParams['location']!,
time: state.queryParams['time']!,
flag: state.queryParams['flag']!,
isDaytime: state.queryParams['isDaytime']!,
)
)
),
]);
world_time.dart
class WorldTime {
String _url = 'https://api-urlxxxxxxx';
String location;
String flag;
String time = '';
bool isDaytime = true;
WorldTime({ required this.location, required this.flag });
...
}
home.dart
class Home extends StatefulWidget {
String location;
String time;
String flag;
State isDaytime;
Home({
Key? key,
required this.location,
required this.time,
required this.flag,
required this.isDaytime,
}) : super(key: key);
#override
// ignore: library_private_types_in_public_api
_HomeState createState() => _HomeState();
}
loading.dart
class Loading extends StatefulWidget {
const Loading({Key? key}) : super(key: key);
#override
_LoadingState createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
void setupWorldTime() async {
WorldTime instance = WorldTime(location: 'London', flag: 'england.png');
await instance.getTime();
...
context.goNamed('home', queryParams: {
'location': instance.location,
'time': instance.time,
'flag': instance.flag,
'isDaytime': instance.isDaytime,
});
}
}

How to pass function to class attribute in flutter?

I am trying to assign a function to an class attribute. HOw can i assign that value to that class' attribue.
return MyCartListItem(
cartName: cartList[index]['english_name'],
cartQuantity: 2,
cartImage: path + img,
cartPrice: cartList[index]['mrp'].toString(),
cartIndex: cartList[index],
onItemRemoved: ?? ,
//trying to assing function here
);
const MyCartListItem(
{Key? key,
...
required this.onItemRemoved,
required this.onItemRemoved(index)})
: super(key: key);
final String cartName;
final int cartQuantity;
final String cartImage;
final String cartPrice;
final int cartIndex;
final Function onItemRemoved;
// func here
#override
State<MyCartListItem> createState() => _MyCartListItemState();
}
onItemRemoved(){
}
return MyCartListItem(
cartName: cartList[index]['english_name'],
cartQuantity: 2,
cartImage: path + img,
cartPrice: cartList[index]['mrp'].toString(),
cartIndex: cartList[index],
onItemRemoved: onItemRemoved ,
//trying to assing function here
);
so you have a function like this:
onTap({required String message}){
print(message);
}
in your class pass function argument like this:
class ClassTest extends StatelessWidget {
final Function({required String message}) onTap;
const ClassTest({Key? key, required this.onTap}) : super(key: key);
#override
Widget build(BuildContext context) {
return InkWell(
onTap: ()=>onTap(message: 'your mesage'),
child: Container(),
);
}
}

Accessing route parameters in Dart and flutter

I am sending 2 parameters restaurantDetails.rest_latitude and restaurantDetails.rest_longitude to a class to get the map details
BarMapWidget(restaurantDetails.rest_latitude, restaurantDetails.rest_longitude),
In the class I have a stateful widget
class BarMapWidget extends StatefulWidget {
String restLatitude;
String restLongitude;
BarMapWidget(this.restLatitude, this.restLongitude, {Key? key}) : super(key: key);
#override
_BarMapWidgetState createState() => _BarMapWidgetState();
}
I am passing a string so I know I have to make it a double
Here is the extended class,
class _BarMapWidgetState extends State<BarMapWidget> {
// Destination Longitude
final double _destLatitude = restLatitude;
final double _destLongitude = restLongitude;
void initState() {
// Add destination marker
_addMarker(
LatLng(_destLatitude, _destLongitude),
"destination",
// BitmapDescriptor.defaultMarkerWithHue(90),
BitmapDescriptor.defaultMarker
);
super.initState();
}
Which give me a Undefined name 'restLatitude'. and Undefined name 'restLongitude'.
How can I access the variable in BarMapWidget?
Your restLatitude and restLongitude on widget level, try using widget.variableName. Also, those aren't matching datatype.
If you need double convert BarMapWidget variable to double.
To initialize on state level you can trick with using late or use initState;
class BarMapWidget extends StatefulWidget {
final double restLatitude;
final double restLongitude;
const BarMapWidget(this.restLatitude, this.restLongitude, {Key? key})
: super(key: key);
#override
_BarMapWidgetState createState() => _BarMapWidgetState();
}
class _BarMapWidgetState extends State<BarMapWidget> {
// Destination Longitude
late final double _destLatitude = widget.restLatitude;
late final double _destLongitude = widget.restLongitude;
Just add in
widget.restLatitude

Null value in Flutter widget inside initState method

It's the first time a use Flutter (2.8.1) and I'having problems trying to undestrand what's going wrong.
I have a Stateful widget like this:
class SimpleWidget extends StatefulWidget {
const SimpleWidget({Key key, #required this.aValue}) : super(key: key);
final Type2 aValue;
#override
_SimpleWidgetState createState() => _SimpleWidgetState();
}
class _SimpleWidgetState extends State<SimpleWidget> {
Type1 from;
Type1 to;
#override
void initState() {
print('mounted: $mounted'); // true
print('widget.aValue: ${widget.aValue}'); // null <-- WHY IS THIS NULL?
super.initState();
from = ...;
to = ...;
}
...
}
that I call in this way:
List<Type1> breakTimes = await showDialog(
context: context,
builder: (context) {
print('currentElement.aValue: ${currentElement.aValue}'); // not null
return SimpleWidget(aValue: currentElement.aValue);
},
);
Why is widget.aValue == null in initInstance()? How can I solve it?
There is wrong in your code :
Chane this to this:
class SimpleWidget extends StatefulWidget {
final Type2 aValue; // initialize 1st
const SimpleWidget({Key key, #required this.aValue}) : super(key: key);
#override
_SimpleWidgetState createState() => _SimpleWidgetState();
}

How to access the variable from one class to other in flutter

I want to access the variable UniversityId in the class of _HomePageState
class showDetailOfUniversity extends StatelessWidget {
final String UniversityId;
showDetailOfUniversity({Key key, #required this.UniversityId}) : super(key:
key);
#override
Widget build(BuildContext context)
{
return (
HomePage()
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//
var temp2 = showDetailOfUniversity();
var temp = temp2.getUniversityId;
/// here i want to access the code but failed
}
The problem here is that you created another instance of showDetailOfUniversity that will have another values for its members. You did not initialize String UniversityId so its value is null untill you set it.
So when you called showDetailOfUniversity() in temp, the value of String UniversityId in this instance is null since there was no value given in this particular instance.
You can pass the String UniversityId in the constructor of the StatefulWidget like this:
class ShowDetailOfUniversity extends StatelessWidget {
final String universityId;
ShowDetailOfUniversity({Key key, #required this.universityId})
: super(key: key);
#override
Widget build(BuildContext context) {
return HomePage(universityId: universityId);
}
}
class HomePage extends StatefulWidget {
final String universityId;
const HomePage({Key key, this.universityId}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var universityId;
#override
void initState() {
super.initState();
universityId = widget.universityId;
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Text(universityId);
}
}
Solution for your code:
var temp2 = showDetailOfUniversity(UniversityId: university_id);
var temp = temp2.UniversityId; //this will return university_id