dth-pingpong-mobileapp/lib/pages/views/creatematch.dart

117 lines
3.3 KiB
Dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../../globals.dart';
class CreateMatchPage extends StatefulWidget {
@override
_CreateMatchPageState createState() => _CreateMatchPageState();
}
class _CreateMatchPageState extends State<CreateMatchPage> {
String? _matchId;
bool _isLoading = false;
final String _createMatchApiUrl = '$apiurl/creatematch';
Future<void> _createMatch() async {
setState(() {
_isLoading = true;
});
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
if (token == null) {
_showToast('No token found. Please login again.');
setState(() {
_isLoading = false;
});
return;
}
try {
final response = await http.post(
Uri.parse(_createMatchApiUrl),
headers: {'Content-Type': 'application/json'},
body: json.encode({'token': token}),
);
if (response.statusCode == 200) {
final data = json.decode(response.body);
setState(() {
_matchId = data['match_id'].toString();
});
_showToast('Match created successfully!');
} else {
_showToast('Failed to create match.');
}
} catch (e) {
_showToast('Error: $e');
} finally {
setState(() {
_isLoading = false;
});
}
}
// Show a Toast message (SnackBar in Flutter)
void _showToast(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message)),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Create Match'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(
Icons.sports_tennis,
size: 80,
color: Colors.blue,
),
SizedBox(height: 16),
Text(
'Create a Match',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
SizedBox(height: 16),
Text(
'Due to current limitations in how we handle matchmaking, only the joining player can control the match. This is only a temporary solution to a problem we are actively fixing.',
style: TextStyle(fontSize: 14),
textAlign: TextAlign.center,
),
SizedBox(height: 16),
_isLoading
? CircularProgressIndicator() // Show loading spinner
: ElevatedButton(
onPressed: _createMatch,
child: Text('Create Match'),
),
SizedBox(height: 16),
if (_matchId != null)
Text(
'Your Match ID: $_matchId',
style: TextStyle(fontSize: 18, color: Colors.green),
textAlign: TextAlign.center,
),
],
),
),
),
);
}
}