Flutter: Cannot pass a boolean type parameter through GoRouter - flutter

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,
});
}
}

Related

How to access values from another dart file?

I am new to flutter .Here I stored a value to a variable doc_id ,I want to use this value in another file called comments.dart . So I did something like below but it gives null value in comment.dart .
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));
Comment.dart
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
#override
Widget build(BuildContext context) {
return
Text(widget.postid);
}
}
Just create a global variable and assign from there
String postid = "";
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
#override
Widget build(BuildContext context) {
return
Text(postid);
}
}
void setPostID(String s) { // get value
postid = s;
}
Finally assign the value
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
setPostID(value.id); // set value
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));
You can use: https://pub.dev/packages/shared_preferences
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
await prefs.setString('doc_id', postid); // set value
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));
Finally use it in your class
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
#override
void initState() {
super.initState();
widget.postid = prefs.getString('doc_id'); // get the value
setState(() {});
}
#override
Widget build(BuildContext context) {
return
Text(postid);
}
}

"'key' is required, but there's no corresponding argument" flutter error

How to solve this error?
The named parameter 'key' is required, but there's no corresponding argument. (Documentation) Try adding the required argument.
error
Future<void> onJoin() async {
// update input validation
setState(() {
_channelController.text.isEmpty
? _validateError = true
: _validateError = false;
});
if (_channelController.text.isNotEmpty) {
await _handleCameraAndMic(Permission.camera);
await _handleCameraAndMic(Permission.microphone);
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoCall(
channelName: _channelController.text,
role: _role,
),
),
);
}
}
class VideoCall
class VideoCall extends StatefulWidget {
final String channelName;
final ClientRole role;
const VideoCall({Key key, required this.channelName, required this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}
class _VideoCallState extends State<VideoCall> {
final _users = <int>[];
final _infoStrings = <String>[];
bool muted = false;
late RtcEngine _engine;
#override
void dispose() {
// clear users
_users.clear();
// destroy sdk
_engine.leaveChannel();
_engine.destroy();
super.dispose();
}
#override
void initState() {
super.initState();
// initialize agora sdk
initialize();
}
this is the videoCall class in there no any error shows.
when add "key" show this
When remove required property from key in video call class
show this error
In VideoCall class, key property set as a required, change it to optional:
class VideoCall extends StatefulWidget {
final String? channelName;
final ClientRole? role;
const VideoCall({Key? key, this.channelName, this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}

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(),
);
}
}

Flutter Stateful Constructor Const Problem

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.

Store the filters selected in a variable

I have a code that is responsible for filtering data: the user choose the criteria that are important to him and clicks "Apply". And sees a list based on the selected filters.
But the applied filters are not saved for subsequent filtrations. And the next time user click on the "filters" button, the user cannot continue working with them from the last moment. He has to choose all the filters again.
How to make the filters to be saved and the user to continue working with the filters based on the previous selection?
filter_dialog.dart
class FilterDialog extends StatefulWidget {
final void Function(Map<String, List<String>?>) onApplyFilters;
const FilterDialog({Key? key, required this.onApplyFilters}) : super(key: key);
#override
State<FilterDialog> createState() => _FilterDialogState();
}
class _FilterDialogState extends State<FilterDialog> {
Map<String, List<String>?> filters = {};
void _handleCheckFilter(bool checked, String key, String value) {
final currentFilters = filters[key] ?? [];
if(checked) {
currentFilters.add(value);
} else {
currentFilters.remove(value);
}
filters[key] = currentFilters;
}
#override
.......
main_page.dart
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
#override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
List<Phone> filteredPhones = phoneList;
void _filter(Map<String, List<String>?> filters) {
setState(() {
filteredPhones = phoneList;
filters.forEach((key, value) {
if((value ?? []).isNotEmpty) {
filteredPhones = filteredPhones.where((phone) {
switch(key) {
case 'brand':
return value!.contains(phone.brand);
case 'version_OS':
return value!.contains(phone.version_OS);
case 'operation_system':
return value!.contains(phone.operation_system);
default:
return false;
}
}).toList();
}
});
});
}
#override
....
}
class Filter {
String name;
bool Function(Phone) filterFn;
Filter({required this.name, required this.filterFn});
}
custom_checkbox_tile.dart
class CustomCheckboxTile extends StatefulWidget {
final String label;
final void Function(bool)? onChange;
const CustomCheckboxTile({Key? key, required this.label, this.onChange}) : super(key: key);
#override
State<CustomCheckboxTile> createState() => _CustomCheckboxTileState();
}
class _CustomCheckboxTileState extends State<CustomCheckboxTile> {
bool checked = false;
#override
Widget build(BuildContext context) {
return Row(
children: [
Checkbox(
visualDensity: VisualDensity.compact,
value: checked,
onChanged: (_) {
setState(() {
checked = !checked;
if(widget.onChange != null) {
widget.onChange!(checked);
}
});
},
),
Text(widget.label),
],
);
}
}
its not simple to answer your qustion.
More changes should made.
I'm done it all.
Please Check Github