我有需要拉动刷新功能的该应用程序,因此我将StreamBuilder窗口小部件放置在RefreshIndicator窗口小部件内,但是我不知道在触发onRefreshed事件时如何手动刷新StreamBuilder。

最佳答案

stream作为state variable并在拉动刷新时重置将解决此问题。

在下面的代码中,我将在按下按钮时重置流。希望对您有帮助。

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  var stream; // state variable

  @override
  void initState() {
    super.initState();
    stream = newStream(); // initial stream
  }

  Stream<String> newStream() =>
      Stream.periodic(Duration(seconds: 1), (i) => "$i");

  @override
  Widget build(BuildContext context) {
    var streamBuilder = StreamBuilder(
        initialData: "0",
        stream: stream,
        builder: (context, snapshot) {
          return new Text(snapshot.data);
        });
    return MaterialApp(
        title: 'Trial',
        home: Scaffold(
            appBar: AppBar(title: Text('Stream builder')),
            body: Column(
              children: <Widget>[
                streamBuilder,
                FlatButton(
                    onPressed: () {
                      setState(() {
                        stream = newStream(); //refresh/reset the stream
                      });
                    },
                    child: Text("Reset"))
              ],
            )));
  }
}

关于flutter - 如何手动刷新或重新加载Flutter Firestore StreamBuilder?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52132896/

10-10 17:21