我不断收到以下错误: lib/main.dart:45:37:错误:“对象”类型的值?不能分配给“字符串”类型的变量。
- “对象”来自“dart:core”。 _startMeasure = 值;
这完全有道理,但我尝试将值更改为字符串,但这并不能解决问题。我试过“$value”和 _startMeasure = value as String。但是,这些都不起作用。
代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyAppState createState() => MyAppState();
}//class
class MyAppState extends State<MyApp> {
double _numberFrom = 0;
String _startMeasure = "";
final List<String> _measures = [
'meters',
'kilometers',
'grams',
'kilograms',
'feet',
'miles',
'pounds (lbs)',
'ounces',
];
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Center(child: Text("Convert Units")),
backgroundColor: Colors.deepOrange[300],
),
body: Center(
child: Column(
children: [
DropdownButton(
items: _measures.map((String value) {
return DropdownMenuItem<String>(value: value, child: Text(value),);
}).toList(),
onChanged: (value) {
setState(() {
_startMeasure = value;
});
},
),
TextField(
onChanged: (text) {
var rv = double.tryParse(text);
if (rv != null) {
setState(() {
_numberFrom = rv;
});
}
else {
setState(() {
_numberFrom = 0;
});
}
},
),
//Text((_numberFrom == null) ? '' : _numberFrom.toString()),
Text("Number entered: $_numberFrom"),
],
),//Column
),
),
);
}//widget
}
最佳答案
您的下拉按钮没有类型,所以它认为 onChanged 中的值是 Object? 相反,它应该是这样的:
DropdownButton<String>(
items: _measures.map((String value) {
return DropdownMenuItem<String>(value: value, child: Text(value),);
}).toList(),
onChanged: (String? value) {
setState(() {
// You can't assign String? to String that's why the ! tells dart it cant be null
_startMeasure = value!;
});
},
),
关于Flutter Dropdown : A value of type 'Object?' can't be assigned to a variable of type 'String' . - 'Object' 来自 'dart:core',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67908375/