使用Flutter和StreamBuilder弹出刷新最后一个屏幕

时间:2018-08-07 13:40:42

标签: dart flutter pop navigator setstate

我想在Navigator.pop时重新加载我的列表,但我不能这样做。

我的代码:

class ConfigCNPJPage extends StatefulWidget {
  bool voltarTela;
  ConfigCNPJPage({Key key, this.voltarTela}) : super(key: key);

  @override
  ConfigCNPJPageState createState() => new ConfigCNPJPageState();
}

class ConfigCNPJPageState extends State<ConfigCNPJPage>
    with SingleTickerProviderStateMixin {
    ResultConfig BD;
    List<Map> list;
    List<Widget> listArray = [];

    Stream myStream;


  Future setupList() async {
    ConfigDatabase db = ConfigDatabase();
    var banco = await db.initDB();
    list = await banco.rawQuery('SELECT * FROM Empresa');
    return list;
  }



    @override
    void initState() {
      super.initState();
      myStream = setupList()?.asStream();
    }



  @override
  Widget build(BuildContext context) {
    return new StreamBuilder(
      stream: myStream,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        return snapshot.hasData?  new Scaffold(
          resizeToAvoidBottomPadding: false,
            appBar: new AppBar(
              title: new Text('Configurar Empresa'),
              actions: <Widget>[
                new IconButton(icon: const Icon(Icons.add), onPressed: () {
                  Navigator.pushNamed(context, "NovoCNPJ").then((value) {
                      setState(() {
                        myStream = setupList()?.asStream();
                      });
                  });
                })
              ],
            ),
            body: new Column(
              children: <Widget>[
                  criarLista()
              ],
            ),
        ):new Center(child: new RefreshProgressIndicator());
      },);
  }
}

我想在弹出后使用setState重新加载此Stream,但是不起作用。有人可以帮忙吗?

我需要重建该StreamBuilder吗?或仅重新加载列表?

使用StreamBuilder,我需要执行setState,如果我重新构建了streamBuilder,它将起作用吗?

1 个答案:

答案 0 :(得分:0)

我想您在该示例中必须使用StreamController而不是Stream

在您的示例中,看到_streamController次出现。

class ConfigCNPJPage extends StatefulWidget {
  bool voltarTela;
  ConfigCNPJPage({Key key, this.voltarTela}) : super(key: key);

  @override
  ConfigCNPJPageState createState() => new ConfigCNPJPageState();
}

class ConfigCNPJPageState extends State<ConfigCNPJPage>
    with SingleTickerProviderStateMixin {
    ResultConfig BD;
    List<Map> list;
    List<Widget> listArray = [];

    StreamController _streamController;


  Future setupList() async {
    ConfigDatabase db = ConfigDatabase();
    var banco = await db.initDB();
    list = await banco.rawQuery('SELECT * FROM Empresa');
    return list;
  }



    @override
    void initState() {
      super.initState();
      _streamController = new StreamController();
      setupList()?.then((o) => _streamController.add(o));
    }



  @override
  Widget build(BuildContext context) {
    return new StreamBuilder(
      stream: _streamController.stream,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        return snapshot.hasData?  new Scaffold(
          resizeToAvoidBottomPadding: false,
            appBar: new AppBar(
              title: new Text('Configurar Empresa'),
              actions: <Widget>[
                new IconButton(icon: const Icon(Icons.add), onPressed: () {
                  Navigator.pushNamed(context, "NovoCNPJ").then((value) {
                      setState(() {
                        _streamController.add(value);
                      });
                  });
                })
              ],
            ),
            body: new Column(
              children: <Widget>[
                  criarLista()
              ],
            ),
        ):new Center(child: new RefreshProgressIndicator());
      },);
  }
}

但是在您的用例中,您只有一个Empresa /公司,还是会有很多?

如果只有一个,而不是一个Stream,那么只管理一个_empresa / _company对象就容易得多。

如果您希望有一个对象列表,那么我也不会使用StreamBuilder。我也会管理一个List<Empresa> _empresas

class ConfigCNPJPage extends StatefulWidget {
  bool voltarTela;
  ConfigCNPJPage({Key key, this.voltarTela}) : super(key: key);

  @override
  ConfigCNPJPageState createState() => new ConfigCNPJPageState();
}

class ConfigCNPJPageState extends State<ConfigCNPJPage>
    with SingleTickerProviderStateMixin {
    ResultConfig BD;
    List<Map> list;
    List<Widget> listArray = [];

    List<Empresa> _empresas;


  Future setupList() async {
    ConfigDatabase db = ConfigDatabase();
    var banco = await db.initDB();
    list = await banco.rawQuery('SELECT * FROM Empresa');
    return list;
  }

  @override
  void initState() {
    super.initState();

    setupList()?.then((o) {
      if (_empresas == null) _empresas = new List();

      // if o is a list, perform a forEach on it

      _empresas.add(new Empresa(o))
    });
  }

  @override
  Widget build(BuildContext context) {
    // o melhor seria usar outra variavel pra controlar o loading,
    //   mas deve funcionar assim
    return _empresas == null
      ? new Center(child: new RefreshProgressIndicator())
      : new Scaffold(
          resizeToAvoidBottomPadding: false,
            appBar: new AppBar(
              title: new Text('Configurar Empresa'),
              actions: <Widget>[
                new IconButton(icon: const Icon(Icons.add), onPressed: () {
                  Navigator.pushNamed(context, "NovoCNPJ").then((value) {
                      setState(() {
                        _empresas.add(new Empresa(value));
                      });
                  });
                })
              ],
            ),
            body: new Column(
              children: <Widget>[
                  criarLista()
              ],
            ),
        );
  }
}

祝你好运!