如何在Flutter中使用Bloc正确设置DropdownButton的值?

时间:2018-12-19 14:11:28

标签: dart flutter bloc

我是Bloc编程模式的新手,在将其与Dropdown一起使用时遇到问题 那是在我的bloc类中:

final _dropDown = BehaviorSubject<String>();
Stream<String> get dropDownStream => _dropDown.stream;
Sink<String> get dropDownSink => _dropDown.sink;
final _dropdownValues = BehaviorSubject<List<String>>(seedValue: [
    'One',
    'Two',
    'Three',
    'Four',
  ].toList());
  Stream<List<String>> get dropdownValuesStream => _dropdownValues.stream;

在我的窗口小部件页面中,我添加了以下下拉窗口小部件,以便所有内容均由Bloc类处理:

StreamBuilder<List<String>>(
                      stream: _exampleBloc.dropdownValuesStream,
                      builder: (BuildContext contextValues, AsyncSnapshot snapshotValues) {
                        return StreamBuilder<String>(
                            stream: _exampleBloc.dropDownStream,
                            builder: (BuildContext context, AsyncSnapshot snapshot) {
                              return InputDecorator(
                                decoration: InputDecoration(
                                  icon: const Icon(Icons.color_lens),
                                  labelText: 'DropDown',
                                ),
                                child: DropdownButtonHideUnderline(
                                  child: DropdownButton<String>(
                                    value: snapshot.data,
                                    onChanged: (String newValue) => _exampleBloc.dropDownSink.add(newValue),
                                    items: snapshotValues.data != null ? snapshotValues.data.map<DropdownMenuItem<String>>((String value) {
                                      return DropdownMenuItem<String>(
                                        value: value,
                                        child: Text(value),
                                      );
                                    }).toList() : <String>[''].map<DropdownMenuItem<String>>((String value) {
                                      return DropdownMenuItem<String>(
                                        value: value,
                                        child: Text(value),
                                      );
                                    }).toList(),
                                  ),
                                ),
                              );
                            },
                          );
                      },
                    ),

但是这样做,在设置DropdownButton的值(值:snapshot.data)时出现此错误:

I/flutter ( 5565): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5565): The following assertion was thrown building StreamBuilder<String>(dirty, state:
I/flutter ( 5565): _StreamBuilderBaseState<String, AsyncSnapshot<String>>#70482):
I/flutter ( 5565): 'package:flutter/src/material/dropdown.dart': Failed assertion: line 514 pos 15: 'items == null ||
I/flutter ( 5565): value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not
I/flutter ( 5565): true.
I/flutter ( 5565):
I/flutter ( 5565): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 5565): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 5565): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 5565):   https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 5565):
I/flutter ( 5565): When the exception was thrown, this was the stack:
I/flutter ( 5565): #2      new DropdownButton (package:flutter/src/material/dropdown.dart:514:15)
I/flutter ( 5565): #3      _ExamplePageState.build.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:financeiro_mobile/src/ui/exemple/example_page.dart:129:42)
I/flutter ( 5565): #4      StreamBuilder.build (package:flutter/src/widgets/async.dart:423:74)
I/flutter ( 5565): #5      _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 5565): #6      StatefulElement.build (package:flutter/src/widgets/framework.dart:3809:27)
I/flutter ( 5565): #7      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3721:15)
I/flutter ( 5565): #8      Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 5565): #9      StatefulElement.update (package:flutter/src/widgets/framework.dart:3878:5)
I/flutter ( 5565): #10     Element.updateChild (package:flutter/src/widgets/framework.dart:2742:15)
I/flutter ( 5565): #11     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3732:16)
I/flutter ( 5565): #12     Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 5565): #13     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2286:33)
I/flutter ( 5565): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:676:20)
I/flutter ( 5565): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:219:5)
I/flutter ( 5565): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)
I/flutter ( 5565): #17     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)
I/flutter ( 5565): #18     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:842:5)
I/flutter ( 5565): #19     _invoke (dart:ui/hooks.dart:154:13)
I/flutter ( 5565): #20     _drawFrame (dart:ui/hooks.dart:143:3)
I/flutter ( 5565): (elided 2 frames from class _AssertionError)

我尝试了很多想法,例如在设置时检查snapshotValues.data是否不为null。我知道值必须是列表中的某个值或为null。但是,我没有提出任何逻辑可以使此错误消失。 如果将值设置为null,则可以使用,但是所选的值不会显示。 我做错了吗?有没有更好的方法可行?我该如何解决这个问题? 谢谢!

2 个答案:

答案 0 :(得分:0)

那是因为您使用的是StreamBuilder,所以在第一次快照为空时,您必须进行验证:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int create_random(int num);


int main() 
{ 
  int i=0,num=0;
  printf("How many random number ? ");//Request from user..
  scanf("%d",&num);
  for(i=0 ; i<num ; ++i)
{
    printf("%d\n",create_random(i));    
}

return 0; 
}

int create_random(int a)
{

  a=0;
  srand(time(NULL));
  a=rand()%100;

return a;
} 

显示一个空的小部件it('Should add', () => { const fb = new FormBuilder(); const myObject = fb.group('myArray': fb.array()); component.new(myObject); const packagesLength = component.myFormGroup.get('data')['controls'][0] ['controls']['items']['controls'].length; expect(packagesLength).toEqual(2); }); return snapshot.hasData ? InputDecorator( decoration: InputDecoration( icon: const Icon(Icons.color_lens), labelText: 'DropDown', ), child: DropdownButtonHideUnderline( child: DropdownButton<String>( value: snapshot.data, onChanged: (String newValue) => _exampleBloc.dropDownSink.add(newValue), items: snapshotValues.data != null ? snapshotValues.data.map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList() : SizedBox(height: 0.0) ), ) : SizedBox(height: 0.0);

答案 1 :(得分:0)

我在集团中使用两个流来解决它,一个用于elemtns列表,另一个用于值。因此,在构建中,您需要两个链式StreamBuilder,并且当您同时获得两个快照和数据时,就可以加载构建。像这样:

Widget _holdingDropDown() {
return StreamBuilder(
    stream: bloc.holding,
    builder: (BuildContext context, AsyncSnapshot<Holding> snapshot) {
      return Container(
        child: Center(
          child: snapshot.hasData
              ? StreamBuilder(
                  stream: bloc.obsHoldingList,
                  builder: (BuildContext context,
                      AsyncSnapshot<List<Holding>> holdingListSnapshot) {
                    return holdingListSnapshot.hasData ?
                    DropdownButton<Holding>(
                      value: snapshot.data,
                      items: _listDropDownHoldings,
                      onChanged: (Holding h) {
                        _changeDropDownItemHolding(h);
                      },
                    ): CircularProgressIndicator();
                  },
                )
              : CircularProgressIndicator(),
        ),
      );
    });
}

如果我没有包含数据的快照,则使用循环进度指示器返回。 希望我能对您有所帮助。