flutter - NoSuchMethodError:在 null 上调用了 getter 'dlongitude'
问题描述
我是新来的。我试图创建一个通用类并从其他类访问它的变量。我的应用程序中有这个类:
class Target {
double dlatitude;
double dlongitude;
Target({this.dlatitude, this.dlongitude});
}
我在其他有状态的小部件中使用这个类来设置它的变量的值:
class _EditLocationState extends State<EditLocation> {
final TextEditingController _search = TextEditingController();
Target target = Target();
@override
void dispose() {
_search.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Positioned(
left: 20,
top: 50,
right: 20,
child: TextField(
controller: _search,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[400],
hintText: "${widget.location}",
),
),
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
var array = _search.text.split(",");
Target(
dlongitude: double.parse(array[0]),
dlatitude: double.parse(array[1]));
}
print(target.dlatitude); // null value is printed here.
},
child: const Icon(Icons.done),
backgroundColor: Colors.green,
),
);
}
}
每当我尝试访问其他小部件中的目标变量值时,我都会收到此错误:NoSuchMethodError: The getter 'dlongitude' was called on null。
class _SearchRideState extends State<SearchRide> {
final TextEditingController _search = TextEditingController();
Target target=Target();
@override
void dispose() {
_search.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Positioned(
left: 20,
top: 50,
right: 20,
child: TextField(
controller: _search,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[400],
hintText: "${target.dlatitude},${target.dlongitude}"
),
),
),
],
),
);
}
}
我该怎么办?
解决方案
现在提出您的问题,如果您正在使用该类并想要分配值,它将像这样完成:
Target target = Target(dlatitude: 1.1, dlongitude: 2.0);
你刚刚做Target target = Target();
了这就是为什么创建空对象以及你在那里得到一个空值的原因。下面的代码意义不大。
onPressed: () {
var array = _search.text.split(",");
Target(
dlongitude: double.parse(array[0]),
dlatitude: double.parse(array[1]),
);
print(target.dlatitude);
}
1.这就是为什么您的代码的解决方案如下:删除Target target = Target();
onPressed: () {
var array = _search.text.split(",");
Target target = Target(
dlongitude: double.parse(array[0]),
dlatitude: double.parse(array[1]),
);
print(target.dlatitude);
}
2.或者你可以在类中提供一个默认值:
class Target {
double dlatitude;
double dlongitude;
Target({this.dlatitude=0.0, this.dlongitude=0.0});
}
然后在你的逻辑中,它会像:
Target target = Target();
代码保持原样。和
onPressed: () {
var array = _search.text.split(",");
target.dlongitud = double.parse(array[0]);
target.dlongitude = double.parse(array[1]);
print(target.dlatitude);
}
推荐阅读
- latex - pandoc beamer 文本溢出
- iframe - Vaadin iFrame 不显示外部内容
- java - Cannot get a very basic program to produce any output whatsoever
- python - MCP9600:热电偶读数()在很长一段时间内给出相同的值
- solana - NFT 代币如何与资产相关联(例如图像、视频)
- html - 一个按钮是白色的,直到光标在它上面。所有其他按钮均为蓝色
- python - 如何映射和连接值两个数据框python
- python - 如何从谷歌驱动器检索图像链接并使用 GridFS 将其上传到 MongoDB?
- javascript - 样式化 rc-slider 轨道以在其内部包含句柄
- java - Flutter Downloder 失败,错误是找不到具有权限的提供者的元数据