progress on home page

This commit is contained in:
2025-06-26 14:43:25 +02:00
parent d50623d24e
commit a866d97b70
13 changed files with 802 additions and 139 deletions

30
lib/http/http.dart Normal file
View File

@@ -0,0 +1,30 @@
import 'package:dio/dio.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:logger/logger.dart';
var logger = Logger(printer: PrettyPrinter());
class Http {
final Dio dio = Dio();
final String baseUrl = dotenv.env['BASE_URL'] ?? '';
Http() {
dio.options.baseUrl = baseUrl;
dio.options.connectTimeout = const Duration(seconds: 60);
dio.options.receiveTimeout = const Duration(seconds: 60);
dio.interceptors.add(LogInterceptor(
request: true,
responseBody: true,
requestBody: true,
error: true,
));
}
Future<dynamic> get(String url) async {
Response response;
response = await dio.get(baseUrl + url);
logger.i(response.data.toString());
return response.data;
}
}

View File

@@ -2,13 +2,18 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:go_router/go_router.dart';
import 'providers/transaction_provider.dart';
import 'screens/home_screen.dart';
import 'screens/home/home_screen.dart';
import 'screens/make_payment_screen.dart';
import 'screens/history_screen.dart';
import 'screens/profile_screen.dart';
import 'theme/app_theme.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
void main() {
const String testEnv = "assets/.env";
const String liveEnv = "assets/.env";
void main() async {
await dotenv.load(fileName: testEnv);
runApp(const MyApp());
}
@@ -17,49 +22,43 @@ class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => TransactionProvider(),
child: MaterialApp.router(
title: 'QPay',
theme: AppTheme.lightTheme,
routerConfig: GoRouter(
initialLocation: '/',
routes: [
ShellRoute(
builder: (context, state, child) {
return ScaffoldWithNavBar(child: child);
},
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/make-payment',
builder: (context, state) => const MakePaymentScreen(),
),
GoRoute(
path: '/history',
builder: (context, state) => const HistoryScreen(),
),
GoRoute(
path: '/profile',
builder: (context, state) => const ProfileScreen(),
),
],
),
],
),
return MaterialApp.router(
title: 'QPay',
theme: AppTheme.lightTheme,
routerConfig: GoRouter(
initialLocation: '/',
routes: [
ShellRoute(
builder: (context, state, child) {
return ScaffoldWithNavBar(child: child);
},
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
),
GoRoute(
path: '/make-payment',
builder: (context, state) => const MakePaymentScreen(),
),
GoRoute(
path: '/history',
builder: (context, state) => const HistoryScreen(),
),
GoRoute(
path: '/profile',
builder: (context, state) => const ProfileScreen(),
),
],
),
],
),
);
}
}
class ScaffoldWithNavBar extends StatelessWidget {
const ScaffoldWithNavBar({
super.key,
required this.child,
});
const ScaffoldWithNavBar({super.key, required this.child});
final Widget child;

View File

@@ -0,0 +1,75 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:qpay/http/http.dart';
part 'home_controller.freezed.dart';
part 'home_controller.g.dart';
class HomeScreenModel {
List<dynamic> transactions = [];
List<Category> categories = [];
dynamic account = {};
dynamic profile = {};
bool isLoading = false;
bool isLoggedIn = false;
String? errorMessage;
}
@freezed
abstract class Category with _$Category {
const factory Category({
required String name,
required String description,
required String? image,
required String label,
}) = _Category;
factory Category.fromJson(Map<String, dynamic> json) =>
_$CategoryFromJson(json);
}
var logger = Logger(printer: PrettyPrinter());
class HomeController extends ChangeNotifier {
final HomeScreenModel model = HomeScreenModel();
final Http http = Http();
Future<void> getCategories() async {
// activate skeletonizer
model.categories = getFakeCategoryData();
// Simulate fetching categories
try {
model.isLoading = true;
List<dynamic> response = await http.get('/categories');
model.categories = response.map((e) => Category.fromJson(e)).toList();
} on DioException catch (e) {
logger.e(e);
model.errorMessage = e.type.name;
model.categories = [];
}
model.isLoading = false;
notifyListeners();
}
// required by skeletonizer
List<Category> getFakeCategoryData() {
return [
Category(
name: 'Electricity',
description: 'Pay your electricity bills easily',
image: 'assets/images/electricity.png',
label: 'Electricity',
),
Category(
name: 'Internet',
description: 'Pay your internet bills easily',
image: 'assets/images/internet.png',
label: 'Internet',
),
];
}
}

View File

@@ -0,0 +1,157 @@
// dart format width=80
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'home_controller.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$Category {
String get name; String get description; String? get image; String get label;
/// Create a copy of Category
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$CategoryCopyWith<Category> get copyWith => _$CategoryCopyWithImpl<Category>(this as Category, _$identity);
/// Serializes this Category to a JSON map.
Map<String, dynamic> toJson();
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is Category&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&(identical(other.image, image) || other.image == image)&&(identical(other.label, label) || other.label == label));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,name,description,image,label);
@override
String toString() {
return 'Category(name: $name, description: $description, image: $image, label: $label)';
}
}
/// @nodoc
abstract mixin class $CategoryCopyWith<$Res> {
factory $CategoryCopyWith(Category value, $Res Function(Category) _then) = _$CategoryCopyWithImpl;
@useResult
$Res call({
String name, String description, String? image, String label
});
}
/// @nodoc
class _$CategoryCopyWithImpl<$Res>
implements $CategoryCopyWith<$Res> {
_$CategoryCopyWithImpl(this._self, this._then);
final Category _self;
final $Res Function(Category) _then;
/// Create a copy of Category
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? name = null,Object? description = null,Object? image = freezed,Object? label = null,}) {
return _then(_self.copyWith(
name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,description: null == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String,image: freezed == image ? _self.image : image // ignore: cast_nullable_to_non_nullable
as String?,label: null == label ? _self.label : label // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
/// @nodoc
@JsonSerializable()
class _Category implements Category {
const _Category({required this.name, required this.description, required this.image, required this.label});
factory _Category.fromJson(Map<String, dynamic> json) => _$CategoryFromJson(json);
@override final String name;
@override final String description;
@override final String? image;
@override final String label;
/// Create a copy of Category
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$CategoryCopyWith<_Category> get copyWith => __$CategoryCopyWithImpl<_Category>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$CategoryToJson(this, );
}
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _Category&&(identical(other.name, name) || other.name == name)&&(identical(other.description, description) || other.description == description)&&(identical(other.image, image) || other.image == image)&&(identical(other.label, label) || other.label == label));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,name,description,image,label);
@override
String toString() {
return 'Category(name: $name, description: $description, image: $image, label: $label)';
}
}
/// @nodoc
abstract mixin class _$CategoryCopyWith<$Res> implements $CategoryCopyWith<$Res> {
factory _$CategoryCopyWith(_Category value, $Res Function(_Category) _then) = __$CategoryCopyWithImpl;
@override @useResult
$Res call({
String name, String description, String? image, String label
});
}
/// @nodoc
class __$CategoryCopyWithImpl<$Res>
implements _$CategoryCopyWith<$Res> {
__$CategoryCopyWithImpl(this._self, this._then);
final _Category _self;
final $Res Function(_Category) _then;
/// Create a copy of Category
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? name = null,Object? description = null,Object? image = freezed,Object? label = null,}) {
return _then(_Category(
name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,description: null == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
as String,image: freezed == image ? _self.image : image // ignore: cast_nullable_to_non_nullable
as String?,label: null == label ? _self.label : label // ignore: cast_nullable_to_non_nullable
as String,
));
}
}
// dart format on

View File

@@ -0,0 +1,21 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'home_controller.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_Category _$CategoryFromJson(Map<String, dynamic> json) => _Category(
name: json['name'] as String,
description: json['description'] as String,
image: json['image'] as String?,
label: json['label'] as String,
);
Map<String, dynamic> _$CategoryToJson(_Category instance) => <String, dynamic>{
'name': instance.name,
'description': instance.description,
'image': instance.image,
'label': instance.label,
};

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:qpay/screens/home/home_controller.dart';
import 'package:skeletonizer/skeletonizer.dart';
import 'dart:async';
@@ -17,13 +18,19 @@ class _HomeScreenState extends State<HomeScreen>
final List<Animation<Offset>> _animations = [];
final List<Animation<Offset>> _alignListAnimations = [];
late bool _enabled = true;
late final bool _enabled = true;
late bool _loading = true;
Timer? _loadingTimer;
bool get _isLoggedIn => true;
final HomeController homeController = HomeController();
@override
void initState() {
super.initState();
homeController.getCategories();
_controller = AnimationController(
duration: const Duration(milliseconds: 600),
vsync: this,
@@ -68,6 +75,23 @@ class _HomeScreenState extends State<HomeScreen>
});
}
void _showErrorSnackBar(String? message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message.toString()),
behavior: SnackBarBehavior.floating,
),
);
}
int _getCategoryIndex(String name) {
return homeController.model.categories.indexWhere((e) => e.name == name);
}
bool _isCategoryOdd(String name) {
return _getCategoryIndex(name) % 2 != 0;
}
@override
void dispose() {
_loadingTimer?.cancel();
@@ -84,7 +108,7 @@ class _HomeScreenState extends State<HomeScreen>
slivers: [
SliverAppBar(
floating: true,
title: const Text('QPay'),
title: Image(image: AssetImage('assets/icon.png'), width: 85),
actions: [
IconButton(
icon: const Icon(Icons.notifications_outlined),
@@ -98,110 +122,100 @@ class _HomeScreenState extends State<HomeScreen>
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AlignTransition(
alignment: _alignAnimation,
child: Skeletonizer(
enabled: _loading,
child: Text(
"USD 4.02",
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
if (_isLoggedIn)
AlignTransition(
alignment: _alignAnimation,
child: Skeletonizer(
enabled: _loading,
child: Column(
children: [
Text(
"Vusumuzi Khoza",
style: TextStyle(fontSize: 15),
),
Text(
"USD 4.02",
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 20),
],
),
),
),
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SlideTransition(
position: _animations[0],
child: FilledButton(
style: ButtonStyle(
backgroundColor: WidgetStateProperty.all(
Theme.of(
context,
).colorScheme.primary.withValues(alpha: 0.9),
),
padding: WidgetStateProperty.all(
const EdgeInsets.symmetric(
vertical: 17.5,
horizontal: 30,
),
),
),
onPressed: onPressed,
child: Row(
ListenableBuilder(
listenable: homeController,
builder: (context, child) {
if (homeController.model.errorMessage != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_showErrorSnackBar(
homeController.model.errorMessage,
);
});
}
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Icon(Icons.electric_bolt, color: Colors.white),
const SizedBox(width: 8),
const Text(
'Electricity',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
...homeController.model.categories.map(
(e) => Skeletonizer(
enabled: homeController.model.isLoading,
child: SlideTransition(
position: _animations[0],
child: FilledButton(
style: ButtonStyle(
backgroundColor:
WidgetStateProperty.all(
_isCategoryOdd(e.name)
? Theme.of(context)
.colorScheme
.secondary
.withValues(alpha: 0.9)
: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: 0.9),
),
padding: WidgetStateProperty.all(
const EdgeInsets.symmetric(
vertical: 17.5,
horizontal: 30,
),
),
),
onPressed: onPressed,
child: Row(
children: [
Icon(
Icons.electric_bolt,
color: Colors.white,
),
const SizedBox(width: 8),
Text(
e.name,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
),
),
],
),
),
),
SlideTransition(
position: _animations[1],
child: OutlinedButton(
style: ButtonStyle(
side: WidgetStateProperty.all(
BorderSide(
color: Theme.of(context).colorScheme.primary,
),
),
foregroundColor: WidgetStateProperty.all(
Theme.of(context).colorScheme.primary,
),
padding: WidgetStateProperty.all(
const EdgeInsets.symmetric(
vertical: 17.5,
horizontal: 30,
),
),
),
onPressed: onPressed,
child: Row(
children: [
Icon(Icons.phone_android),
const SizedBox(width: 8),
const Text(
'Airtime',
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
),
),
SlideTransition(
position: _animations[2],
child: OutlinedButton(
style: ButtonStyle(
side: WidgetStateProperty.all(
BorderSide(
color: Theme.of(context).colorScheme.primary,
),
),
padding: WidgetStateProperty.all(
const EdgeInsets.symmetric(
vertical: 17.5,
horizontal: 30,
),
),
),
onPressed: onPressed,
child: Icon(Icons.add),
),
),
],
homeController.model.categories.isNotEmpty
? const SizedBox(height: 30)
: SizedBox(),
],
);
},
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [