gpt4 book ai didi

flutter - 如何在 Flutter 中显示流中的 Snackbar?

转载 作者:IT王子 更新时间:2023-10-29 06:58:00 24 4
gpt4 key购买 nike

一旦 StringStream 发送一个新的 String,我想显示一个 SnackBar

我试图在 StatefulWidget 中放置一个 StreamBuilder,以便能够调用 Scaffold.of()(因为它是另一个上下文 现在)。但后来我得到这个错误:

The following assertion was thrown building StreamBuilder(dirty, state: _StreamBuilderBaseState>#7f258): setState() or markNeedsBuild() called during build. This Scaffold widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase. The widget on which setState() or markNeedsBuild() was called was: Scaffold(dependencies: [_LocalizationsScope-[GlobalKey#0e1f6], Directionality, _InheritedTheme, MediaQuery], state: ScaffoldState#3f2aa(tickers: tracking 2 tickers)) The widget which was currently being built when the offending call was made was: StreamBuilder(dirty, state: _StreamBuilderBaseState>#7f258)

我该如何解决这个问题?

这是一个显示问题的简单代码片段:

import 'dart:async';

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: TestHome(),
);
}
}

class TestHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamSnackbar(),
);
}
}

class StreamSnackbar extends StatefulWidget {
@override
_StreamSnackbarState createState() => _StreamSnackbarState();
}

class _StreamSnackbarState extends State<StreamSnackbar> {
final status = StreamController<String>();

@override
Widget build(BuildContext context) {
return Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
status.add('Test');
},
child: Text('Press me to trigger the Snackbar!'),
),
StreamBuilder<String>(
stream: status.stream,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text(snapshot.data)));
}
return Container(
height: 0,
width: 0,
); // just because we need to return a Widget
},
),
],
),
),
);
}
}

最佳答案

不需要使用StreamBuilder。显示 SnackBar 必须在同步 build() 执行之外完成。

@override
void initState() {
super.initState();
status.stream.forEach((e) =>
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text(e))));
}

@override
void dispose() {
status.close();
super.dispose();
}

关于flutter - 如何在 Flutter 中显示流中的 Snackbar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55018488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com