我创建了以下2个流。
流1-定期流,它在特定时间调用异步函数。
流2-侦听流1然后创建流2的功能
我想添加逻辑,以便如果流1的长度大于0,则仅创建流2。但是我得到的流1的长度始终为0。
我的代码如下。 (在热重载后运行)
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int _counter = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyPage(),
);
}
}
class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
StreamController<List<String>> _myStreamController =
StreamController<List<String>>();
int _counter = 0;
Stream<List<String>> _stream() {
Duration interval = Duration(milliseconds: 100);
Stream<List<String>> stream =
Stream<List<String>>.periodic(interval, temp2);
return stream;
}
Future temp() async {
List<String> a = [];
_counter++;
a.add(_counter.toString());
return a;
}
List<String> temp2(int value) {
List<String> _localMsg = List();
temp().then((a) {
print(a);
_localMsg = a;
});
return _localMsg;
}
@override
void initState() {
super.initState();
_stream().listen((ondata) {
print(ondata);
if (ondata.length > 0) _myStreamController.sink.add(ondata);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: StreamBuilder(
stream: _myStreamController.stream,
builder: (context, snapshot) {
if (snapshot.data != null) {
return Text(snapshot.data.toString());
} else {
return Text("waiting...");
}
},
),
),
),
);
}
}