简体   繁体   English

"<i>Flutter error: A value of type &#39;Object?&#39;<\/i>颤振错误:“对象?”类型的值<\/b><i>can&#39;t be assigned to a variable of type &#39;String&#39;<\/i>不能分配给“字符串”类型的变量<\/b>"

[英]Flutter error: A value of type 'Object?' can't be assigned to a variable of type 'String'

I am using a dropdownbuttonfield and getting this error:我正在使用下拉按钮字段并收到此错误:

A value of type 'Object?' can't be assigned to a variable of type 'String'.
Try changing the type of the variable, or casting the right-hand type to 'String'.dart(invalid_assignment)

Code :代码 :

    class SettingsForm extends StatefulWidget {
  @override
  _SettingsFormState createState() => _SettingsFormState();
}

class _SettingsFormState extends State<SettingsForm> {
  final _formKey = GlobalKey<FormState>();
  final List<String> sugars = ['0', '1', '2', '3', '4'];
  final List<int> strengths = [100, 200, 300, 400, 500, 600, 700, 800, 900];

  // form values
   String? _currentName;
   String? _currentSugars;
   int? _currentStrength;

  @override
  Widget build(BuildContext context) {
    MyUser user = Provider.of<MyUser>(context);

    return StreamBuilder<UserData>(
        stream: DatabaseService(uid: user.uid).userData,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            UserData? userData = snapshot.data;
            return Form(
              key: _formKey,
              child: Column(
                children: <Widget>[
                  Text(
                    'Update your brew settings.',
                    style: TextStyle(fontSize: 18.0),
                  ),
                  SizedBox(height: 20.0),
                  TextFormField(
                    initialValue: userData!.name,
                    decoration: textInputDecoration,
                    validator: (val) =>
                        val!.isEmpty ? 'Please enter a name' : null,
                    onChanged: (val) => setState(() => _currentName = val),
                  ),
                  SizedBox(height: 10.0),
                  DropdownButtonFormField(
                    value: _currentSugars ?? userData.sugars,
                    decoration: textInputDecoration,
                    items: sugars.map((sugar) {
                      return DropdownMenuItem(
                        value: sugar,
                        child: Text('$sugar sugars'),
                      );
                    }).toList(),
                    onChanged: (val) => setState(() => _currentSugars = val), <--Error here **val** right one
                  ),
                  SizedBox(height: 10.0),
                  Slider(
                    value: (_currentStrength ?? userData.strength).toDouble(),
                    activeColor:
                        Colors.brown[_currentStrength ?? userData.strength],
                    inactiveColor:
                        Colors.brown[_currentStrength ?? userData.strength],
                    min: 100.0,
                    max: 900.0,
                    divisions: 8,
                    onChanged: (val) =>
                        setState(() => _currentStrength = val.round()),
                  ),
                  ElevatedButton(
                      style:
                          ElevatedButton.styleFrom(primary: Colors.pink[400]),
                      child: Text(
                        'Update',
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () async {
                        if (_formKey.currentState!.validate()) {
                          await DatabaseService(uid: user.uid).updateUserData(
                              _currentSugars ?? snapshot.data!.sugars,
                              _currentName ?? snapshot.data!.name,
                              _currentStrength ?? snapshot.data!.strength);
                          Navigator.pop(context);
                        }
                      }),
                ],
              ),
            );
          } else {
            return Loading();
          }
        });
  }
}

Update Update 2 A value of type 'String?'更新更新 2 'String?' 类型的值can't be assigned to a variable of type 'String'.不能分配给“字符串”类型的变量。 Try changing the type of the variable, or casting the right-hand type to 'String'.尝试更改变量的类型,或将右侧类型转换为“字符串”。

尝试将val作为字符串或您想成为的任何类型:

onChanged: (val) => setState(() => _currentSugars = val as String),

Assign the generic type String to the DropdownButtonFormField:将通用类型String分配给 DropdownButtonFormField:

DropdownButtonFormField<String>(
                    value: _currentSugars,
                    decoration: textInputDecoration,
                    items: sugars.map((sugar) {
                      return DropdownMenuItem(
                        value: sugar,
                        child: Text('$sugar sugars'),
                      );
                    }).toList(),
                    onChanged: (val) => setState(() => _currentSugars = val), 
                  ),

Unless you specify the type String dart makes the assumption with the one of the most generic types it has Object?除非您指定String类型,否则 dart 使用它拥有的最通用的类​​型之一进行假设Object? as the generic type of the DropdownButtonFormField作为DropdownButtonFormField的通用类型

Complete demo (Updated to use null safety)完整演示(更新为使用空安全)

class Demo extends StatefulWidget {
  Demo({Key? key}) : super(key: key);

  @override
  _DemoState createState() => _DemoState();
}

class _DemoState extends State<Demo> {
  final sugars = ['candy', 'chocolate', 'snicker'];
  String? _currentSugars = 'candy';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: DropdownButtonFormField<String>(
          value: _currentSugars,
          items: sugars.map((sugar) {
            return DropdownMenuItem(
              value: sugar,
              child: Text('$sugar sugars'),
            );
          }).toList(),
          onChanged: (val) => setState(() => _currentSugars = val),
        ),
      ),
    );
  }
}

To fix add type parameters<\/strong> or cast<\/strong> from dynamic explicitly修复添加类型参数<\/strong>或从动态显式转换<\/strong>

You can avoid this error by adding type parameters:您可以通过添加类型参数来避免此错误:

void filterValues<T>(bool Function(T) filter) {}
filterValues<String>((x) => x.contains('Hello'));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 颤振错误:“对象?”类型的值不能分配给“字符串”类型的变量 - Flutter Error : A value of type 'Object?' can't be assigned to a variable of type 'String' 'Map 类型的值<string, object> ' 不能分配给 'HashMap 类型的变量<string, dynamic> ' flutter</string,></string,> - A value of type 'Map<String, Object>' can't be assigned to a variable of type 'HashMap<String, dynamic>' flutter “对象?”类型的值不能分配给“地图”类型的变量<string, dynamic> '。 flutter 相关问题</string,> - A value of type 'Object?' can't be assigned to a variable of type 'Map<String, dynamic>'. flutter related issue Flutter - 'List 类型的值<map<string, object> &gt;' 不能分配给“列表”类型的变量<classes> ' </classes></map<string,> - Flutter - A value of type 'List<Map<String, Object>>' can't be assigned to a variable of type 'List<Classes>' 错误:“字符串”类型的值? 不能分配给“字符串”类型的变量 - Error: A value of type 'String?' can't be assigned to a variable of type 'String' “对象”类型的值? 不能分配给“字符串”类型的变量 - A value of type 'Object?' can't be assigned to a variable of type 'String' 颤振错误“对象?”类型的值不能分配给“int”类型的变量 - Flutter error A value of type 'Object?' can't be assigned to a variable of type 'int' Flutter DocumentSnapshot - 错误:“对象?”类型的值不能分配给“DocumentSnapshot”类型的变量 - Flutter DocumentSnapshot - Error: A value of type 'Object?' can't be assigned to a variable of type 'DocumentSnapshot' Flutter 错误字符串函数()不能分配给“字符串”类型的变量 - Flutter Error String Function() can't be assigned to a variable of type 'String' Flutter/Firestore - 错误:“列表”类型的值<string> Function(QuerySnapshot)' 不能分配给 'List' 类型的变量<dynamic> '</dynamic></string> - Flutter/Firestore - Error: A value of type 'List<String> Function(QuerySnapshot)' can't be assigned to a variable of type 'List<dynamic>'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM