【问题标题】:Flutter BLoC implementation with streamBuilder使用 streamBuilder 实现 Flutter BLoC
【发布时间】:2020-07-21 04:39:19
【问题描述】:

我的 BLoC 实现有问题,我在 synchronize.dart 中有这段代码:

...
class _SynchronizeState extends State<Synchronize> {
  UserBloc userBloc;
  //final dbRef = FirebaseDatabase.instance.reference();

  @override
  Widget build(BuildContext context) {
    userBloc = BlocProvider.of(context);

    return Scaffold(
      resizeToAvoidBottomPadding: false,
      body: Container(
        ...
        ),
        child: StreamBuilder(
          stream: dbRef.child('info_tekax').limitToLast(10).onValue,
          builder: (context, snapshot) {
            if(snapshot.hasData && !snapshot.hasError){
              Map data = snapshot.data.snapshot.value;
              List keys = [];
              data.forEach( (index, data) => keys.add(index) );
              return ListView.builder(
                itemCount: data.length,
                itemBuilder: (context, index) => SynchronizeItem(title: keys[index], bottom: 10, onPressed: (){ print(keys[index]); })
              );
            }else{
              return Container(
                child: Center(
                  child: Text('Loading...'),
                ),
              );
            }

          }
        ),

      ),
    );
  }
}

previos 代码,工作正常,但我想实现 bloc 模式,我有 userBloc 然后我想把这个 userBloc.getDevicesForSinchronized() 代替 dbRef.child('info_tekax').limitToLast(10).onValue,

我的问题是这样的:

void getDevicesForSynchronized() {
  return dbRef.child(DEVICES).limitToLast(10).onValue;
}

我收到此错误**无法从方法“getDevicesForSynchronized”返回“Stream”类型的值,因为它的返回类型为“void”

错误很清楚,但是不知道需要返回什么类型,试试:

Furure<void> getDevicesForSynchronized() async {
  return await dbRef.child(DEVICES).limitToLast(10).onValue;    
}

Furure<void> getDevicesForSynchronized() async {
  dynamic result = await dbRef.child(DEVICES).limitToLast(10).onValue;    
}

还有另一种解决方案,但我不知道如何正确返回值以在 StreamBuilder 中使用

【问题讨论】:

    标签: flutter firebase-realtime-database bloc


    【解决方案1】:

    从报错信息可以看出返回类型是Stream。更改您的方法,例如:

    Future<Stream> getDevicesForSynchronized() async {
      return dbRef.child(DEVICES).limitToLast(10).onValue;    
    }
    

    【讨论】:

    • 我得到,等待应用于'Stream',这不是未来的T_T
    • @UzielTrujillo:你在哪一行得到了那个错误?
    • @Mihum MP,在我的声明方法中
    猜你喜欢
    • 2021-06-16
    • 2019-12-26
    • 2021-05-20
    • 2019-09-04
    • 2021-08-15
    • 2020-04-26
    • 2020-07-30
    • 2020-10-19
    • 1970-01-01
    相关资源
    最近更新 更多