【问题标题】:Flutter error: A value of type 'Object?' can't be assigned to a variable of type 'String'颤振错误:“对象?”类型的值不能使用下拉按钮字段分配给“字符串”类型的变量
【发布时间】:2021-09-27 15:29:53
【问题描述】:

我正在使用下拉按钮字段并收到此错误:

“对象?”类型的值不能分配给“字符串”类型的变量。 尝试更改变量的类型,或将右侧类型转换为 'String'.dart(invalid_assignment) 目的?值

'val'下面的红线

代码:

    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();
          }
        });
  }
}

UpdateUpdate 2 “字符串?”类型的值不能分配给“字符串”类型的变量。 尝试更改变量的类型,或将右侧类型转换为“字符串”。

【问题讨论】:

  • 请务必提及_currentSugarssugars 的类型。
  • @TheAlphamerc 他们都是'字符串'
  • @MikeOsborn 设置_currentSugars = val!
  • 您需要将DropdownButtonFormField 更改为DropdownButtonFormField&lt;String&gt; 然后使用我上面提到的评论
  • @MikeOsborn 是的,因为你声明它可以为空,所以你不再需要使用 !.

标签: android flutter mobile


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    将泛型类型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), 
                      ),
    

    除非您指定 String 类型,否则 dart 会假设它拥有的最通用类型之一 Object? 作为 DropdownButtonFormField 的通用类型

    完整演示(更新为使用空安全)

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

    【讨论】:

    • 它对我有用,我添加了一个演示,我在其中声明了 _currentSugarssugars,这是您发布的代码中唯一对我来说未知的
    • 更新了它。我忘记了零安全性?
    • 你能分辨出来,看看是什么导致了错误
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 2021-03-28
    • 2021-12-10
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多