首页 > 解决方案 > 应该恰好有一项具有 [DropdownButton] 的值:0。检测到 0 个或 2 个或多个具有相同值的 [DropdownMenuItem]

问题描述

请有人帮助我!我在 StatefullWidget 上使用地图键和值创建了 DropdownButton。我有以下代码在运行时产生错误

Settings_Form.Dart:

final user = Provider.of<User>(context);

return StreamBuilder<UserData>(
  stream: DatabaseServices(uid: user.uid).userData,
  builder: (context, snapshot) {
    if(snapshot.hasData){
      UserData? userData = snapshot.data;
      return Form(
        key: _formKey,
        child: Column(
          children: [
            Text(
              'Update your brew settings.',
              style: TextStyle(fontSize: 18.0),
            ),
            SizedBox(height: 20),
            TextFormField(
              initialValue: userData!.name,
              decoration: textInputDecoration,
              validator: (val) => val!.isEmpty ? 'Please enter a name' : null,
              onChanged: (val) => setState(() => _currentName = val),
            ),
            SizedBox(height: 10),
            

这就是我认为问题所在。DropdownField 将我所有的麻烦都嵌套在那里。我真的很紧张。

    DropdownButtonFormField(
                  value: userData.sugars,
                  decoration: textInputDecoration,
                  items: sugars.map((sugar) {
                    return DropdownMenuItem(
                      value: sugars,
                      child: Text('$sugar sugars'),
                    );
                  }).toList(),
                  onChanged: (val) => setState(() => _currentSugars = 'val' ),
                ),
                SizedBox(height: 10),
                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()),
                ),
                // slider
                RaisedButton(
                    color: Colors.brown[400],
                    child: Text(
                      'Update',
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () async {
                      if(_formKey.currentState!.validate()){
                        await DatabaseServices(uid: user.uid).updateUserData(
                          userData.sugars,
                          userData.name,
                          userData.strength
                        );
                      }
                    }
                ),
              ],
            ),
          );
        }else{
          return Loading();
        }
      }
    );
  }
}

数据库类:

class DatabaseServices {
  final String? uid;
  DatabaseServices({ this.uid });

  //collection reference
  final CollectionReference brewCollection = Firestore.instance.collection('brews');

  Future updateUserData (String sugars, String name, int strength) async {
    return await brewCollection.document(uid).setData({
      'sugars' : sugars,
      'name' : name,
      'strength': strength,
    });
  }

  //get brew list from snapshot
  List<Brew> _brewListFromSnapshot (QuerySnapshot snapshot) {
    return snapshot.documents.map((doc){
      return Brew(
          name: doc['name'] ?? '',
          sugars: doc['sugars'] ?? 0,
          strength: doc['strength'] ?? '0',
      );
    }).toList();
  }

  //user data from snapshot
  UserData _userDataFromSnapshot(DocumentSnapshot snapshot){
    return UserData(
        uid: 'uid',
        name: snapshot.data['name'],
        sugars: snapshot.data['sugars'],
        strength: snapshot.data['strength']
    );
  }

  //get brews Stream
  Stream <List<Brew>> get brews{
    return brewCollection.snapshots()
        .map(_brewListFromSnapshot);
  }

  //get user doc stream
  Stream<UserData > get userData {
    return brewCollection.document(uid).snapshots()
        .map(_userDataFromSnapshot);
  }
}

错误信息:

Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 1506 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

标签: androidflutter

解决方案


推荐阅读