Flutter中GoRouter传递布尔参数报错,咨询原因与解决方法
GoRouter传递bool类型参数报错问题
我尝试通过GoRouter传递bool类型参数时,收到以下错误提示:
参数类型String无法分配给参数类型"bool"
不确定错误来源,想确认:queryParams是否仅允许String类型?
代码片段
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, }); } }
问题原因与解决方法
queryParams仅支持String类型:URL查询参数本质都是字符串,GoRouter的
queryParams要求所有值必须为String,直接传bool会触发类型错误,接收端直接赋值给bool变量也会报错。修复步骤:
- 传递时转字符串:在
loading.dart中将bool转为String:context.goNamed('home', queryParams: { 'location': instance.location, 'time': instance.time, 'flag': instance.flag, 'isDaytime': instance.isDaytime.toString(), }); - 接收时转bool:在
main.dart中将字符串转回bool,可通过判断是否等于'true'实现: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'] == 'true', ) ) ), ]); - 修正home.dart类型错误:
isDaytime的类型误写为State,需改成bool:class Home extends StatefulWidget { String location; String time; String flag; bool 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(); }
- 传递时转字符串:在
内容的提问来源于stack exchange,提问作者Duddy67
相关产品推荐
相关产品推荐

