Search code examples
flutterdartdropdown

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


I keep getting the following error: lib/main.dart:45:37: Error: A value of type 'Object?' can't be assigned to a variable of type 'String'.

  • 'Object' is from 'dart:core'. _startMeasure = value;

Which makes complete sense but I have tried changing value into string but that doesnt fix the problem. I have tried "$value" and also _startMeasure = value as String. But, none of this works.

Code:

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
}

Solution

  • Your dropdown button has no type so it thinks the value in the onChanged is Object? instead it should look like this:

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