在我的项目中,我想在时间线上显示实时巴士跟踪,一个代表巴士的图标和 当公交车现场位置改变时移动,我尝试了很多方法来实现这种情况,但没有任何效果
我想要该小部件的 ui 代码以及将图标移动到真实公交车位置的方法
您可以使用堆栈布局来完成此操作。这是示例代码:
import 'package:flutter/material.dart';
import 'dart:async';
class LiveBusTracking extends StatefulWidget {
@override
_LiveBusTrackingState createState() => _LiveBusTrackingState();
}
class _LiveBusTrackingState extends State<LiveBusTracking> {
double busPosition = 0.0; // Initial bus position (0 represents the start of the timeline)
@override
void initState() {
super.initState();
_updateBusPosition();
}
// Simulates fetching live bus location updates
void _updateBusPosition() {
Timer.periodic(Duration(seconds: 2), (timer) {
// Here you would fetch the new location of the bus, e.g., from a real-time API.
// For this example, we just incrementally increase the bus position for demonstration.
setState(() {
busPosition = (busPosition + 0.1) % 1.0; // Move the bus position in the range [0, 1]
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Live Bus Tracking')),
body: Stack(
children: [
Center(
child: Column(
children: [
Text(
'Live Bus Tracking Timeline',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
SizedBox(height: 20),
Expanded(
child: Container(
width: 10,
color: Colors.grey.shade300,
),
),
],
),
),
AnimatedPositioned(
duration: Duration(milliseconds: 500),
top: MediaQuery.of(context).size.height * busPosition,
left: MediaQuery.of(context).size.width * 0.5 - 20,
child: Icon(
Icons.directions_bus,
size: 40,
color: Colors.blue,
),
),
],
),
);
}
}