mchess-client/lib/pages/prepare_chess_game.dart

94 lines
2.5 KiB
Dart
Raw Normal View History

import 'dart:developer';
2023-06-08 15:10:48 +00:00
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
2023-06-08 15:10:48 +00:00
import 'package:go_router/go_router.dart';
import 'package:http/http.dart';
2023-06-02 21:28:40 +00:00
import 'package:mchess/api/register.dart';
import 'package:mchess/pages/chess_game.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
2023-06-08 15:10:48 +00:00
class PrepareChessGameWidget extends StatefulWidget {
const PrepareChessGameWidget({super.key});
2023-06-08 15:10:48 +00:00
@override
State<PrepareChessGameWidget> createState() => _PrepareChessGameWidgetState();
}
class _PrepareChessGameWidgetState extends State<PrepareChessGameWidget> {
late Future randomGameResponse;
@override
void initState() {
randomGameResponse = registerForRandomGame();
super.initState();
}
@override
Widget build(BuildContext context) {
2023-06-08 15:10:48 +00:00
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(),
),
);
2023-06-08 15:10:48 +00:00
},
),
);
}
2023-06-08 15:10:48 +00:00
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));
}
2023-06-08 15:10:48 +00:00
return null;
}
}