Flutter Dropdown:无法将 'Object?' 类型的值分配给 'String' 类型的变量。 - 'Object' 来自 'dart:core'

Flutter Dropdown: A value of type 'Object?' can't be assigned to a variable of type 'String'. - 'Object' is from 'dart:core'

我不断收到以下错误: lib/main.dart:45:37: 错误:'Object?' 类型的值无法分配给 'String'.

类型的变量

这完全有道理,但我已尝试将值更改为字符串,但这并不能解决问题。我试过“$value”,也试过 _startMeasure = value as String。但是,none 有效。

代码:

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

              ),