如何使用事件通道获取当前时间?



我需要使用事件通道获得当前时间。点击接收按钮。我不明白如何在kotlin文件中编写代码。如何使用事件通道获取当前时间?只需要通过事件通道接收日期。我在下面附上了Flutter代码和kotlin文件。

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
static const EventChannel _eventPlatform =
EventChannel('samples.flutter.dev/eventChannel_profile');
static Stream<int> get getCurrentTime {
return _eventPlatform.receiveBroadcastStream().cast();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body:  Container(
padding: const EdgeInsets.all(20),
child: Center(
child: Column(
children: [
StreamBuilder<int>(
stream: getCurrentTime,
builder:
(BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasData) {
return Text("Current Time: ${snapshot.data}");
} else {
return const Text("Waiting for get data...");
}
},
),
const SizedBox(height: 30),
ElevatedButton(
child: const Text('Get Update Profile'),
onPressed: _getUpdateProfile,
),
],
);
}
},
),
);
}
}

我芬兰湾的科特林:

class MainActivity : FlutterActivity() {
private val EVENT_CHANNEL = "samples.flutter.dev/profile"
private lateinit var channel: EventChannel
var eventSink: EventChannel.EventSink? = null

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)

channel = EventChannel(flutterEngine.dartExecutor.binaryMessenger, EVENT_CHANNEL)
channel.setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
}
}
override fun onCancel(arguments: Any?) {
Log.w("Android", "EventChannel onCancel called")
}
}
)
}
}

不太清楚您在这里想要完成什么。如果您确实需要当前时间,那么使用纯Dart有更好的方法:

DateTime current = DateTime.now();
Stream timer = Stream.periodic( Duration(seconds: 1), (i){
current = current.add(Duration(seconds: 1));
return current;
});
timer.listen((data)=> print(data));

但是,如果这只是一个与本机平台通信的学习练习,那么Flutter文档有一个非常详细的指南,包括Kotlin中的代码示例。

另一个很好的资源(专门讨论事件通道)是A deep Dive into Streaming on Flutter跨平台通道。

最新更新