简体   繁体   中英

Flutter: How to return a widget in streamSubscription.listen onData, which is void

I'm trying to return a widget in the streamSubscription.listen's onData callback. However, the Text widget in the example below never renders. I think this is because the onData method is of void type.

How do I return a widget in response to stream data?

@override 
Widget build(BuildContext context) {
    Stream<List<DocumentSnapshot>> stream = geo
        .collection(collectionRef: ref)
        .within(center: center, radius: radius, field: field);
    stream.listen((List<DocumentSnapshot> documentList) {
      return Text('this text never renders');
    });
    return Text("loading");
  }

You cannot return a Widget there.
You can use setState() instead, with a bool value.

For example:

  1. Declare bool isLoading variable.
  2. Change its value inside the stream listener like setState(() => isLoading = true);
  3. Using the isLoading 's value, render your widget like:
Container(
  child: isLoading ? Text("loading") : Text('Not Loading, some Data here');
)

Alternatively, you can use a ValueListenableBuilder or better, a StreamBuilder .

Try this

@override 
Widget build(BuildContext context) {
  Stream<List<DocumentSnapshot>> stream = geo
      .collection(collectionRef: ref)
      .within(center: center, radius: radius, field: field);
  return StreamBuilder(
    stream: stream,
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return Text("Loading...");
      }
      return Text('this text never renders');
    }
  );
}

You can use StreamBuilder , It will return Widget as you expect

 StreamBuilder<List<DocumentSnapshot>>(
      stream:
          geo.collection(collectionRef: ref).within(center: center, radius: radius, field: field),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Text("loading");
        } else {
          return Text('this text never renders');
        }
      },
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM