Flutter显示SnackBar并在StreamBuilder中返回空容器会引发错误

时间:2018-12-26 05:56:43

标签: android ios flutter scaffold snackbar

您好,如果网络响应返回错误,我现在想显示Snackbar。我的构建函数如下所示:

  @override
  Widget build(BuildContext context) {
    NewsBloc bloc = NewsBloc();
    return Scaffold(
      key: scaffoldKey,
      body: Container(
        color: Colors.white,
        child: StreamBuilder<List<BaseModel>>(
          stream: bloc.newsStream,
          builder: (BuildContext context, AsyncSnapshot<List<BaseModel>> snap) {
            if (snap.hasError) {
              scaffoldKey.currentState.showSnackBar(SnackBar(
                content: Container(
                  height: 100,
                ),
              ));
              return Center(child: Text(snap.error));
            } else if (!snap.hasData) {
              return Center(child: CircularProgressIndicator());
            } else {
              return _newsList(snap.data);
            }
          },
        ),
      ),
    );
  }

它显示了Snackbar,但还会引发错误:

This Scaffold widget cannot be marked as needing to build
because the framework is already in the procces

3 个答案:

答案 0 :(得分:1)

这是因为在Snackbar是重建过程中,您不应该显示Widget,因此可以使用的解决方法是:

          _displaySnackBar(BuildContext context) async {
            await Future.delayed(Duration(milliseconds: 400));
            scaffoldKey.currentState.showSnackBar(SnackBar(
              content: Container(
                height: 100,
              ),
            ));
          }

   if (snap.hasError) {
          _displaySnackBar(context);
          return Center(child: Text(snap.error));
        }

答案 1 :(得分:0)

这是一个工作日,但为我工作

Future<void> _snackBar(String text, context) async {
    Scaffold.of(context).showSnackBar(Helper.snackBarInfo(text));
}

答案 2 :(得分:0)

StreamBuilder(
    stream: bloc.stream,
    builder: (BuildContext context,
        AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        SchedulerBinding.instance
              .addPostFrameCallback((_) {
            Scaffold.of(context).showSnackBar(
              SnackBar(
                content: Text(
                        snapshot.data.error,
                        style: TextStyle(fontSize: 16)),
                duration: Duration(seconds: 3),
              ),
            );
          }); 
      }
      return Container();
    }),