98 lines
2.5 KiB
Dart
98 lines
2.5 KiB
Dart
|
import 'dart:developer';
|
||
|
|
||
|
import 'package:flutter/foundation.dart';
|
||
|
import 'package:flutter/material.dart';
|
||
|
import 'package:go_router/go_router.dart';
|
||
|
import 'package:http/http.dart';
|
||
|
import 'package:mchess/api/register.dart';
|
||
|
import 'package:mchess/chess_bloc/chess_bloc.dart';
|
||
|
import 'package:mchess/chess_bloc/chess_events.dart';
|
||
|
import 'package:mchess/pages/chess_game.dart';
|
||
|
import 'package:http/http.dart' as http;
|
||
|
import 'dart:convert';
|
||
|
|
||
|
class PrepareRandomGameWidget extends StatefulWidget {
|
||
|
const PrepareRandomGameWidget({super.key});
|
||
|
|
||
|
@override
|
||
|
State<PrepareRandomGameWidget> createState() =>
|
||
|
_PrepareRandomGameWidgetState();
|
||
|
}
|
||
|
|
||
|
class _PrepareRandomGameWidgetState extends State<PrepareRandomGameWidget> {
|
||
|
late Future randomGameResponse;
|
||
|
|
||
|
@override
|
||
|
void initState() {
|
||
|
ChessBloc.getInstance().add(InitBoard());
|
||
|
|
||
|
randomGameResponse = registerForRandomGame();
|
||
|
|
||
|
goToGameWhenResponseIsHere(randomGameResponse as Future<PlayerInfo?>);
|
||
|
|
||
|
super.initState();
|
||
|
}
|
||
|
|
||
|
void goToGameWhenResponseIsHere(Future<PlayerInfo?> resp) {
|
||
|
resp.then((value) {
|
||
|
if (value == null) return;
|
||
|
context.push(
|
||
|
'/game',
|
||
|
extra: ChessGameArguments(
|
||
|
lobbyID: value.lobbyID!,
|
||
|
playerID: value.playerID!,
|
||
|
passphrase: value.passphrase),
|
||
|
);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
@override
|
||
|
Widget build(BuildContext context) {
|
||
|
return const Scaffold(
|
||
|
body: Center(
|
||
|
child: SizedBox(
|
||
|
height: 100,
|
||
|
width: 100,
|
||
|
child: CircularProgressIndicator(),
|
||
|
),
|
||
|
),
|
||
|
);
|
||
|
}
|
||
|
|
||
|
Future<PlayerInfo?> registerForRandomGame() async {
|
||
|
String addr;
|
||
|
Response response;
|
||
|
|
||
|
if (kDebugMode) {
|
||
|
addr = 'http://localhost:8080/api/random';
|
||
|
} else {
|
||
|
addr = 'https://chess.sw-gross.de:9999/api/random';
|
||
|
}
|
||
|
|
||
|
try {
|
||
|
response = await http
|
||
|
.get(Uri.parse(addr), headers: {"Accept": "application/json"});
|
||
|
} catch (e) {
|
||
|
if (!context.mounted) return null;
|
||
|
|
||
|
const snackBar = SnackBar(
|
||
|
backgroundColor: Colors.amberAccent,
|
||
|
content: Text("mChess server is not responding. Try again or give up"),
|
||
|
);
|
||
|
Future.delayed(const Duration(seconds: 2), () {
|
||
|
ScaffoldMessenger.of(context).clearSnackBars();
|
||
|
ScaffoldMessenger.of(context).showSnackBar(snackBar);
|
||
|
context.pop();
|
||
|
});
|
||
|
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
if (response.statusCode == 200) {
|
||
|
log(response.body);
|
||
|
return PlayerInfo.fromJson(jsonDecode(response.body));
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
}
|