mchess-client/lib/pages/prepare_chess_game.dart

97 lines
2.6 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 PrepareChessGameWidget extends StatefulWidget {
const PrepareChessGameWidget({super.key});
@override
State<PrepareChessGameWidget> createState() => _PrepareChessGameWidgetState();
}
class _PrepareChessGameWidgetState extends State<PrepareChessGameWidget> {
late Future randomGameResponse;
@override
void initState() {
ChessBloc.getInstance().add(InitBoard());
randomGameResponse = registerForRandomGame();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: randomGameResponse,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
log('Response from registering to random game ${snapshot.data}');
if (snapshot.data != null) {
return ChessGame(
playerID: snapshot.data!.playerID,
lobbyID: snapshot.data!.lobbyID,
);
}
}
return const Center(
child: SizedBox(
height: 100,
width: 100,
child: CircularProgressIndicator(),
),
);
},
),
);
}
Future<ResponseFromRegisteringGame?> registerForRandomGame() async {
String addr;
if (kDebugMode) {
addr = 'http://localhost:8080/api/random';
} else {
addr = 'https://chess.sw-gross.de:9999/api/random';
}
Response response;
try {
response = await http
.get(Uri.parse(addr), headers: {"Accept": "application/json"});
} catch (e) {
const snackBar = SnackBar(
backgroundColor: Colors.amberAccent,
content:
Text("mChess server is not responding. Try again or give up"));
if (!context.mounted) return null;
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(snackBar);
Future.delayed(const Duration(seconds: 2), () {
context.goNamed('lobbySelector');
});
return null;
}
if (response.statusCode == 200) {
log(response.body);
return ResponseFromRegisteringGame.fromJson(jsonDecode(response.body));
}
return null;
}
}