【发布时间】:2021-01-17 21:32:58
【问题描述】:
想要使用流从服务器的实时数据创建列表视图, 所以创建假数据流,然后将其快照保存在列表中以测试结果,当在 ListTile 中使用该列表并运行应用程序时会出现以下错误:
在构建 ListTile(dirty) 时抛出了以下断言: 未找到 Material 小部件。
ListTile 小部件需要 Material 小部件祖先。
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Center(
child: StreamBuilderPage(),
),
),
);
}
}
class StreamBuilderPage extends StatefulWidget {
@override
_StreamBuilderPageState createState() => _StreamBuilderPageState();
}
class _StreamBuilderPageState extends State<StreamBuilderPage> {
List<int> items = [];
@override
Widget build(BuildContext context) {
return StreamBuilder(
//Error number 2
stream: NumberCreator().stream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.connectionState == ConnectionState.done) {
return Text('done');
} else if (snapshot.hasError) {
return Text('Error!');
} else {
items.add(snapshot.data);
print(items); //print every second: [0] then [0,1] then [0,1,2] ...
return ListView.builder(
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index].toString()),
);
},
itemCount: items.length,
);
}
},
);
}
}
class NumberCreator {
NumberCreator() {
Timer.periodic(Duration(seconds: 1), (timer) {
//add count to stream
_controller.sink.add(_count);
_count++;
});
}
var _count = 1;
final _controller = StreamController<int>();
Stream<int> get stream => _controller.stream;
dispose() {
_controller.close();
}
}
究竟是什么导致了这个错误? 感谢社区。p>
【问题讨论】:
-
好吧,错误解释了自己,你没有材料小部件。用 Material 小部件或 Scaffold 包裹你的树。
-
MyApp中有MaterialApp,还不够吗?
-
把它包在脚手架里,错误就消失了,谢谢