feat(UI): add screens for choosing stations and vehicles (WIP)

This commit is contained in:
fbachus
2026-07-21 03:13:35 +02:00
parent 3850cea0e8
commit d7aa2a1b46
2 changed files with 264 additions and 73 deletions
+214 -52
View File
@@ -3,9 +3,12 @@ import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'api_handler.dart'; import 'api_handler.dart';
import 'transport_helper.dart'; import 'transport_helper.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart'; //for testing on desktop
void main() async { void main() async {
await dotenv.load(); await dotenv.load();
const String dbName = "oeffimasterTransportDb"; const String dbName = "oeffimasterTransportDb";
databaseFactory = databaseFactoryFfi; // for debugging and desktop test
DbHelper.initDb(dbName); DbHelper.initDb(dbName);
runApp(const MyApp()); runApp(const MyApp());
} }
@@ -17,42 +20,21 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(
title: 'Flutter Demo', title: 'Oeffimaster',
theme: ThemeData( theme: ThemeData(
// This is the theme of your application. colorScheme: .fromSeed(seedColor: Colors.yellow),
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: .fromSeed(seedColor: Colors.deepPurple),
), ),
home: const MyHomePage(title: 'Flutter Demo Home Page'), home: const MyHomePage(title: 'Oeffimaster'), //this is what matters
// routes: {
// //'/': (context) => const MyHomePage(title: 'Oeffimaster'),
// '/stations': (context) => const ChooseStationPage(),
// },
); );
} }
} }
class MyHomePage extends StatefulWidget { class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title}); const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title; final String title;
@override @override
@@ -64,6 +46,7 @@ class _MyHomePageState extends State<MyHomePage> {
//String API_KEY = ApiHandler.accessID; //String API_KEY = ApiHandler.accessID;
String API_KEY = "no telly"; String API_KEY = "no telly";
//Future<Map<String, dynamic>> ?id; //Future<Map<String, dynamic>> ?id;
List<Station> stationList = [];
String id = ''; String id = '';
void _incrementCounter() { void _incrementCounter() {
@@ -78,9 +61,9 @@ class _MyHomePageState extends State<MyHomePage> {
} }
// TODO :find a better way to show the list // TODO :find a better way to show the list
void show_result(Future<List<String>> future_id) async { void showResult(Future<List<Station>> future_id) async {
var tmp = await future_id; stationList = await future_id;
id = tmp[0]; id = stationList[0].id;
setState(() {}); setState(() {});
} }
@@ -94,31 +77,14 @@ class _MyHomePageState extends State<MyHomePage> {
// than having to individually change instances of widgets. // than having to individually change instances of widgets.
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to //backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar //backgroundColor: Colors.amber,
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by // Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title. // the App.build method, and use it to set our appbar title.
title: Text(widget.title), title: Text(widget.title),
), ),
body: Center( body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column( child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: .center, mainAxisAlignment: .center,
children: [ children: [
const Text('You have pushed the button this many times:'), const Text('You have pushed the button this many times:'),
@@ -129,12 +95,20 @@ class _MyHomePageState extends State<MyHomePage> {
Text('API key from ENV is $API_KEY'), Text('API key from ENV is $API_KEY'),
MaterialButton( MaterialButton(
onPressed: () { onPressed: () {
show_result(ApiHandler.findStations('S Biesdorf')); showResult(ApiHandler.findStations('S Biesdorf'));
setState(() {});
}, },
child: Text('Search for \'S Biesdorf\''), child: Text('Search for \'S Biesdorf\''),
), ),
Text(id), Text(id),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ChooseStationPage()),
);
},
child: const Text('Start a route'),
),
], ],
), ),
), ),
@@ -146,3 +120,191 @@ class _MyHomePageState extends State<MyHomePage> {
); );
} }
} }
class ChooseStationPage extends StatefulWidget {
const ChooseStationPage({super.key});
@override
State<ChooseStationPage> createState() => _ChooseStationPageState();
}
class _ChooseStationPageState extends State<ChooseStationPage> {
Station? _selectedStation;
List<Station> stationList = [];
void findNearbyStations() async {
stationList = await ApiHandler.nearbyStations(
// TODO: replace with location
"52.55",
"13.55",
maxStations: 20,
);
}
/* TODO: function to get stations along a vehicles route past current station,
* and run the correct function on switching to the screen
*/
void findStationsByName(
String name, {
int? resultnum,
}) async {
stationList = await ApiHandler.findStations(name);
}
void showResult(Future<List<Station>> future_id) async {
stationList = await future_id;
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('RoutePicker')),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () {
showResult(ApiHandler.findStations('S Biesdorf'));
},
child: Text('Search for \'S Biesdorf\''),
),
Expanded(
child: SizedBox(
height: 200,
child: StationList(
stationList: stationList,
onTapped: _handleStationTapped,
),
),
),
],
),
),
);
}
void _handleStationTapped(Station station) {
// setState(() {
// _selectedStation = station;
// });
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChooseDeparturePage(startStation: station),
),
);
}
}
class StationList extends StatelessWidget {
final List<Station> stationList;
final ValueChanged<Station> onTapped;
StationList({
required this.stationList,
required this.onTapped,
});
@override
Widget build(BuildContext context) {
return ListView(
children: [
for (Station station in stationList)
ListTile(
title: Text(station.name),
onTap: () => onTapped(station),
),
],
);
}
}
class ChooseDeparturePage extends StatefulWidget {
final Station startStation;
const ChooseDeparturePage({super.key, required this.startStation});
@override
State<ChooseDeparturePage> createState() => _ChooseDeparturePageState();
}
class _ChooseDeparturePageState extends State<ChooseDeparturePage> {
List<Departure> departureList = [];
Departure? _selectedDeparture;
void loadDepartures(Station startStation) async {
departureList = await ApiHandler.departures(startStation.id);
setState(() {});
}
@override
initState() {
loadDepartures(widget.startStation);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('RoutePicker for ${widget.startStation.name}'),
),
body: Center(
child: Column(
children: [
Expanded(
child: SizedBox(
height: 400,
child: DepartureList(
departureList: departureList,
onTapped: _handleDepartureTapped,
),
),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ChooseStationPage()),
);
},
child: const Text('Vehicle picked!'),
),
],
),
),
);
}
void _handleDepartureTapped(Departure departure) {
// setState(() {
// _selectedDeparture = departure;
// });
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ChooseStationPage()),
);
}
}
class DepartureList extends StatelessWidget {
final List<Departure> departureList;
final ValueChanged<Departure> onTapped;
DepartureList({
required this.departureList,
required this.onTapped,
});
@override
Widget build(BuildContext context) {
return ListView(
children: [
for (Departure departure in departureList)
ListTile(
title: Text(departure.vehicleName),
subtitle: Text(departure.departureTime.toString()),
onTap: () => onTapped(departure),
),
],
);
}
}
+50 -21
View File
@@ -438,7 +438,7 @@ class Station {
}); });
Map<String, Object?> _toMap() { Map<String, Object?> _toMap() {
return {"id": id, "name": name}; return {"stationid": id, "name": name};
} }
List<Map<String, Object?>> _toMapLines() { List<Map<String, Object?>> _toMapLines() {
@@ -455,20 +455,26 @@ class Station {
List<Line>? stationLines, List<Line>? stationLines,
}) { }) {
return Station( return Station(
id: map["id"] as String, id: map["stationid"] as String,
name: map["name"] as String, name: map["name"] as String,
transportLines: stationLines ?? List.empty(), transportLines: stationLines ?? List.empty(),
); );
} }
factory Station.fromJson(Map<String, dynamic> json) => Station( factory Station.fromJson(Map<String, dynamic> json) => Station(
id: json["id"] ?? json["extId"] as String, id: json["id"] as String,
name: json["name"], name: json["name"] as String,
transportLines: json.containsKey("productAtStop") transportLines:
? json["productAtStop"].map( json.containsKey("productAtStop") && json["productAtStop"] != Null
(jsonLine) => Line.fromJson(jsonLine as Map<String, dynamic>), ? json["productAtStop"]
) .map(
: const [], (jsonLine) => //jsonLine != Null
/*?*/ Line.fromJson(jsonLine! as Map<String, dynamic>),
//: Null,
)
.toList()
.cast<Line>()
: [],
); );
static void initStationTable() async { static void initStationTable() async {
@@ -563,16 +569,19 @@ class Vehicle {
static const String tableName = "vehicle"; static const String tableName = "vehicle";
String id; String id;
String name;
String vehicleLineId; String vehicleLineId;
Vehicle({ Vehicle({
required this.id, required this.id,
required this.name,
required this.vehicleLineId, required this.vehicleLineId,
}); });
Map<String, Object?> _toMap() { Map<String, Object?> _toMap() {
return { return {
"id": id, "id": id,
"name": name,
"line": vehicleLineId, "line": vehicleLineId,
}; };
} }
@@ -582,6 +591,7 @@ class Vehicle {
) { ) {
return Vehicle( return Vehicle(
id: map["id"] as String, id: map["id"] as String,
name: map["name"] as String,
vehicleLineId: map["line"] as String, vehicleLineId: map["line"] as String,
); );
} }
@@ -589,7 +599,8 @@ class Vehicle {
// we can use the "product" class from within any JSON response // we can use the "product" class from within any JSON response
// (within hafas API, on the appropriate level) // (within hafas API, on the appropriate level)
factory Vehicle.fromJson(Map<String, dynamic> json) => Vehicle( factory Vehicle.fromJson(Map<String, dynamic> json) => Vehicle(
id: json["matchId"], id: json["num"],
name: json["name"],
vehicleLineId: Line.fromJson(json).lineId, vehicleLineId: Line.fromJson(json).lineId,
); );
@@ -597,7 +608,8 @@ class Vehicle {
Database database = DbHelper.db; Database database = DbHelper.db;
String line = Line.tableName; String line = Line.tableName;
database.execute("""CREATE TABLE IF NOT EXISTS $tableName( database.execute("""CREATE TABLE IF NOT EXISTS $tableName(
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
name TEXT,
line TEXT, line TEXT,
FOREIGN KEY(line) REFERENCES $line(lineid) FOREIGN KEY(line) REFERENCES $line(lineid)
); );
@@ -684,14 +696,14 @@ class Line {
]; ];
factory Line.fromJson(Map<String, dynamic> json) => Line( factory Line.fromJson(Map<String, dynamic> json) => Line(
lineId: json["lineId"], lineId: json["lineId"] as String,
name: json["name"], name: json["name"] as String,
mode: _vehicleTypeAsCatCode[int.parse(json["catCode"])], mode: _vehicleTypeAsCatCode[int.parse(json["catCode"] as String)],
fgColor: fgColor:
Color.fromJson(json["foregroundColor"]) as Color? ?? Color.fromJson(json["icon"]["foregroundColor"]) as Color? ??
Color(r: 255, g: 255, b: 255), // fallback Color(r: 255, g: 255, b: 255), // fallback
bgColor: bgColor:
Color.fromJson(json["backgroundColor"]) as Color? ?? Color.fromJson(json["icon"]["backgroundColor"]) as Color? ??
Color(r: 50, g: 50, b: 50), // fallback Color(r: 50, g: 50, b: 50), // fallback
); );
static void initLineTable() async { static void initLineTable() async {
@@ -744,12 +756,14 @@ class Departure {
int? id; int? id;
String vehicleId; String vehicleId;
String vehicleName;
String stationId; String stationId;
DateTime departureTime; DateTime departureTime;
Departure({ Departure({
this.id, this.id,
required this.vehicleId, required this.vehicleId,
required this.vehicleName,
required this.stationId, required this.stationId,
required this.departureTime, required this.departureTime,
}); });
@@ -758,6 +772,7 @@ class Departure {
return { return {
"id": id, "id": id,
"vehicle": vehicleId, "vehicle": vehicleId,
"vehiclename": vehicleName,
"station": stationId, "station": stationId,
"departuretime": departureTime, "departuretime": departureTime,
}; };
@@ -767,19 +782,33 @@ class Departure {
return Departure( return Departure(
id: map["id"] as int, id: map["id"] as int,
vehicleId: map["vehicle"] as String, vehicleId: map["vehicle"] as String,
vehicleName: map["vehiclename"] as String,
stationId: map["station"] as String, stationId: map["station"] as String,
departureTime: map["departuretime"] as DateTime, departureTime: map["departuretime"] as DateTime,
); );
} }
factory Departure.fromJson(Map<String, dynamic> json) { factory Departure.fromJson(Map<String, dynamic> json) {
Vehicle vehicle = Vehicle.fromJson(json["Product"]); Vehicle vehicle = Vehicle.fromJson(json["Product"][0]);
vehicle.dbInsert(); // try {
Station station = Station.fromJson(json["stop"]); // vehicle.dbInsert();
station.dbInsert(); // } catch (e) {
// vehicle.dbUpdate();
// }
Station station = Station(
id: json["stopid"],
name: json["stop"],
transportLines: [],
);
// try {
// station.dbInsert();
// } catch (e) {
// station.dbUpdate();
// }
return Departure( return Departure(
vehicleId: vehicle.id, vehicleId: vehicle.id,
vehicleName: vehicle.name,
stationId: station.id, stationId: station.id,
departureTime: json["time"], departureTime: DateTime.parse('${json["date"]}T${json["time"]}'),
); );
} }