未来的构建器给出失败的断言错误

时间:2019-06-14 09:50:09

标签: flutter

我正在通过API调用填充我的列表,并将数据发送给将来的构建器。它正在正确地从API调用中检索数据并返回该数据,但应用在构建Future Builder时崩溃并给出了错误:

我的代码:

  createNewTaskView(BuildContext context, List<String> societies){
      return Container(         
                DropdownButtonHideUnderline(
                  child: DropdownButton<String>(
                    value: _selectedSociety,
                    onChanged: (String newValue) {
                      setState(() {
                        _selectedSociety = newValue;
                      });
                    },
                    items: societies.map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child:  Padding(
                          padding: const EdgeInsets.only(left: 0.0, right: 0.0),
                          child: Text(value),
                        ),
                      );
                    })
                        .toList(),
                  ),),                            
            ),
          ));

    }


    return Scaffold(

      body: FutureBuilder(
          future: getAllData,
          initialData: [],
          builder: (context, snapshot) {
            if (!snapshot.hasData || snapshot.data.isEmpty) return Center(child: CircularProgressIndicator(valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),));
            else {
              return createNewTaskView(context, snapshot.data);
            }
          }),
    );

错误:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (10866): The following assertion was thrown building FutureBuilder<List<dynamic>>(dirty, state:
I/flutter (10866): _FutureBuilderState<List<dynamic>>#29af2):
I/flutter (10866): 'package:flutter/src/material/dropdown.dart': Failed assertion: line 560 pos 15: 'items == null ||
I/flutter (10866): items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value ==
I/flutter (10866): value).length == 1': is not true.

1 个答案:

答案 0 :(得分:0)

我认为问题在于这种情况:

    if (!snapshot.hasData || snapshot.data.isEmpty) return Center(child: CircularProgressIndicator(valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),));
    else {
      return createNewTaskView(context, snapshot.data);
    }

如果将来没有数据(snapshot.hasData = false),则使用!运算符,将使用空列表调用createNewTaskView,这是您得到的错误。

您可以尝试替换为:

if (!snapshot.hasError && snapshot.hasData) {
    return createNewTaskView(context, snapshot.data);
} else {
  return Center(child: CircularProgressIndicator(valueColor: new AlwaysStoppedAnimation<Color>(Colors.red),));
}