Application propre sans erreurs. Bonne base sur laquelle repartir de zero en cas de soucis majeurs.

This commit is contained in:
DahoudG
2024-08-26 22:45:58 +00:00
parent bcf714ab73
commit eb8368b1ee
24 changed files with 397 additions and 201 deletions

View File

@@ -0,0 +1,22 @@
import 'package:get_it/get_it.dart';
import 'package:http/http.dart' as http;
import '../../data/datasources/user_remote_data_source.dart';
import '../../data/datasources/user_repository_impl.dart';
import '../../domain/usecases/get_user.dart';
final sl = GetIt.instance;
void init() {
// Register Http Client
sl.registerLazySingleton(() => http.Client());
// Register Data Sources
sl.registerLazySingleton(() => UserRemoteDataSource(sl()));
// Register Repositories
sl.registerLazySingleton(() => UserRepositoryImpl(remoteDataSource: sl()));
// Register Use Cases
sl.registerLazySingleton(() => GetUser(sl()));
}

18
lib/config/router.dart Normal file
View File

@@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
import 'package:afterwork/presentation/screens/home/home_screen.dart';
class AppRouter {
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (_) => const HomeScreen());
// Ajoute d'autres routes ici
default:
return MaterialPageRoute(
builder: (_) => const Scaffold(
body: Center(child: Text('Page not found')),
),
);
}
}
}

View File

@@ -0,0 +1,6 @@
class Urls {
static const String baseUrl = 'http://localhost:8085';
// static const String login = baseUrl + 'auth/login';
// static const String events = baseUrl + 'events';
// Ajoute d'autres URLs ici
}

View File

@@ -0,0 +1,3 @@
class ServerException implements Exception {}
class CacheException implements Exception {}

View File

@@ -0,0 +1,9 @@
import 'package:equatable/equatable.dart';
abstract class Failure extends Equatable {
@override
List<Object> get props => [];
}
class ServerFailure extends Failure {}
class CacheFailure extends Failure {}

View File

@@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
class AppTheme {
static final ThemeData lightTheme = ThemeData(
primaryColor: Colors.blue,
colorScheme: const ColorScheme.light(
secondary: Colors.orange,
),
brightness: Brightness.light,
buttonTheme: const ButtonThemeData(buttonColor: Colors.blue),
);
static final ThemeData darkTheme = ThemeData(
primaryColor: Colors.black,
colorScheme: const ColorScheme.dark(
secondary: Colors.red,
),
brightness: Brightness.dark,
);
}

View File

@@ -0,0 +1,16 @@
import 'package:dartz/dartz.dart';
import 'package:afterwork/core/errors/failures.dart';
class InputConverter {
Either<Failure, int> stringToUnsignedInteger(String str) {
try {
final integer = int.parse(str);
if (integer < 0) throw const FormatException();
return Right(integer);
} catch (e) {
return Left(InvalidInputFailure());
}
}
}
class InvalidInputFailure extends Failure {}

View File

@@ -0,0 +1,22 @@
import 'dart:convert';
import 'package:afterwork/data/models/user_model.dart';
import 'package:afterwork/core/constants/urls.dart';
import 'package:http/http.dart' as http;
import '../../core/errors/exceptions.dart';
class UserRemoteDataSource {
final http.Client client;
UserRemoteDataSource(this.client);
Future<UserModel> getUser(String id) async {
final response = await client.get(Uri.parse('${Urls.baseUrl}/user/$id'));
if (response.statusCode == 200) {
return UserModel.fromJson(json.decode(response.body));
} else {
throw ServerException();
}
}
}

View File

@@ -0,0 +1,14 @@
import 'package:afterwork/domain/entities/user.dart';
import 'package:afterwork/domain/repositories/user_repository.dart';
import 'package:afterwork/data/datasources/user_remote_data_source.dart';
class UserRepositoryImpl implements UserRepository {
final UserRemoteDataSource remoteDataSource;
UserRepositoryImpl({required this.remoteDataSource});
@override
Future<User> getUser(String id) async {
return await remoteDataSource.getUser(id);
}
}

View File

@@ -0,0 +1,26 @@
import '../../domain/entities/user.dart';
class UserModel extends User {
const UserModel({
required super.id,
required super.name,
required super.email,
});
factory UserModel.fromJson(Map<String, dynamic> json) {
return UserModel(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'email': email,
};
}
}

View File

@@ -0,0 +1,12 @@
import 'package:equatable/equatable.dart';
class User extends Equatable {
final String id;
final String name;
final String email;
const User({required this.id, required this.name, required this.email});
@override
List<Object?> get props => [id, name, email];
}

View File

@@ -0,0 +1,5 @@
import 'package:afterwork/domain/entities/user.dart';
abstract class UserRepository {
Future<User> getUser(String id);
}

View File

@@ -0,0 +1,19 @@
import 'package:dartz/dartz.dart';
import 'package:afterwork/domain/entities/user.dart';
import 'package:afterwork/domain/repositories/user_repository.dart';
import 'package:afterwork/core/errors/failures.dart';
class GetUser {
final UserRepository repository;
GetUser(this.repository);
Future<Either<Failure, User>> call(String id) async {
try {
final user = await repository.getUser(id);
return Right(user);
} catch (e) {
return Left(ServerFailure());
}
}
}

View File

@@ -1,125 +1,21 @@
import 'package:flutter/material.dart';
import 'config/router.dart';
import 'core/theme/app_theme.dart';
void main() {
runApp(const MyApp());
runApp(const AfterWorkApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
class AfterWorkApp extends StatelessWidget {
const AfterWorkApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// 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: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
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;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// 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
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
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: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
title: 'AfterWork',
theme: AppTheme.lightTheme,
onGenerateRoute: AppRouter.generateRoute,
initialRoute: '/',
);
}
}

View File

@@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
class EventScreen extends StatelessWidget {
const EventScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Événements'),
),
body: const Center(
child: Text('Liste des événements'),
),
);
}
}

View File

@@ -0,0 +1,17 @@
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AfterWork'),
),
body: const Center(
child: Text('Bienvenue sur AfterWork!'),
),
);
}
}

View File

@@ -0,0 +1,43 @@
import 'package:afterwork/domain/entities/user.dart';
import 'package:afterwork/domain/usecases/get_user.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class UserBloc extends Bloc<UserEvent, UserState> {
final GetUser getUser;
UserBloc({required this.getUser}) : super(UserInitial());
Stream<UserState> mapEventToState(UserEvent event) async* {
if (event is GetUserById) {
yield UserLoading();
final either = await getUser(event.id);
yield either.fold(
(failure) => UserError(),
(user) => UserLoaded(user: user),
);
}
}
}
abstract class UserEvent {}
class GetUserById extends UserEvent {
final String id;
GetUserById(this.id);
}
abstract class UserState {}
class UserInitial extends UserState {}
class UserLoading extends UserState {}
class UserLoaded extends UserState {
final User user;
UserLoaded({required this.user});
}
class UserError extends UserState {}

View File

@@ -0,0 +1,17 @@
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
final String text;
final VoidCallback onPressed;
const CustomButton({super.key, required this.text, required this.onPressed});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(text),
);
}
}