因为函数有 bool 语句,我在这里使用了 Function(bool?)
Widget buildSwitchtile(String title, String desc, bool currentvalue,
Function(bool?) updatevalue) {
return SwitchListTile(
title: Text(title),
value: currentvalue,
subtitle: Text(desc),
onChanged: updatevalue,
);
}
出现以下错误如何解决? 'bool?' 类型的值不能分配给“bool”类型的变量。 请帮我解决这个问题。------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --
import 'package:dishes_app/widgets/main_drawer.dart';
import 'package:flutter/material.dart';
class FilterScreen extends StatefulWidget {
static const routeName = '/filters';
@override
_FilterScreenState createState() => _FilterScreenState();
}
class _FilterScreenState extends State<FilterScreen> {
bool _glutenFree = false;
bool _vegetarian = false;
bool _vegan = false;
bool _lactoseFree = false;
Widget buildSwitchtile(String title, String desc, bool currentvalue,
Function(bool?) updatevalue) {
return SwitchListTile(
title: Text(title),
value: currentvalue,
subtitle: Text(desc),
onChanged: updatevalue,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Settings'),
),
drawer: MainDrawer(),
body: Column(
children: [
Container(
padding: EdgeInsets.all(20.0),
child: Text(
'Adjust Your meal selection',
style: Theme.of(context).textTheme.title,
),
),
Expanded(
child: ListView(
children: [
buildSwitchtile('Gluten-Free', 'Only include gluten-free meals',
_glutenFree, (newvalue) {
setState(() {
_glutenFree = newvalue;
});
}),
buildSwitchtile(
'Lactose-Free', 'Only include Lactose Free', _lactoseFree,
(newvalue) {
setState(() {
_lactoseFree = newvalue;
});
}),
buildSwitchtile('Vegetarian ', 'Only include Vegetarian food ',
_vegetarian, (newvalue) {
setState(() {
_vegetarian = newvalue;
});
}),
buildSwitchtile('Vegan', 'Only include Vegan', _vegan,
(newvalue) {
setState(() {
_vegan = newvalue;
});
})
],
),
),
],
),
);
}
}
答案 0 :(得分:0)
输入“!”最后在使用那个 bool 时。 It(bool?myBool) 有一个可以为 null 的值,所以在使用它时,你必须做 myBool!
答案 1 :(得分:0)
onChanged
方法只能发出 bool
。所以这样做。传递一个采用 bool
的方法。那么你不应该有你遇到的问题。
Widget buildSwitchtile(String title, String desc, bool currentvalue,
Function(bool) updatevalue) {
return SwitchListTile(
title: Text(title),
value: currentvalue,
subtitle: Text(desc),
onChanged: updatevalue,
);
}