repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/BooklyApp/lib/features/search/presentation/cubits | mirrored_repositories/BooklyApp/lib/features/search/presentation/cubits/searched_books_cubit/searched_books_cubit.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:bookly/core/entities/book_entity.dart';
import 'package:bookly/features/search/domain/use_cases/fetch_searched_books_use_case.dart';
part 'searched_books_state.dart';
class SearchedBooksCubit extends Cubit<SearchedBooksState> {
SearchedBooksCubit(this._useCase) : super(SearchedBooksInitial());
final FetchSearchedBooksUseCase _useCase;
TextEditingController searchController = TextEditingController();
Future<void> fetchSearchedBooks({required String query, required int page})async {
emit(SearchedBooksLoading());
var result = await _useCase.call(query: query, page: page);
result.fold((failure) {
emit(SearchedBooksFailure(failure.errMessage));
}, (books){
emit(SearchedBooksSuccess(books));
});
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/features/search/domain | mirrored_repositories/BooklyApp/lib/features/search/domain/use_cases/fetch_searched_books_use_case.dart | import 'package:bookly/core/use_cases/no_param_use_case.dart';
import 'package:dartz/dartz.dart';
import 'package:bookly/core/errors/failure.dart';
import 'package:bookly/core/entities/book_entity.dart';
import 'package:bookly/features/search/domain/repos/search_repo.dart';
class FetchSearchedBooksUseCase extends UseCase<List<BookEntity>> {
final SearchRepo _searchRepo;
FetchSearchedBooksUseCase(this._searchRepo);
@override
Future<Either<Failure, List<BookEntity>>> call({
String query = '',
int page = 0,
}) async {
return await _searchRepo.fetchSearchedBooks(query: query, page: page);
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/features/search/domain | mirrored_repositories/BooklyApp/lib/features/search/domain/repos/search_repo.dart | import 'package:dartz/dartz.dart';
import 'package:bookly/core/errors/failure.dart';
import 'package:bookly/core/entities/book_entity.dart';
abstract class SearchRepo {
Future<Either<Failure, List<BookEntity>>> fetchSearchedBooks({
required String query,
required int page,
});
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/widgets/custom_button.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:bookly/core/utils/styles.dart';
class CustomButton extends StatelessWidget {
const CustomButton({
Key? key,
required this.backGroundColor,
required this.textColor,
this.borderRadius,
required this.text,
this.fontSize,
this.onPressed,
}) : super(key: key);
final String text;
final Color backGroundColor;
final Color textColor;
final double? fontSize;
final BorderRadius? borderRadius;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 50,
child: Platform.isAndroid
? ElevatedButton(
onPressed: onPressed,
style: TextButton.styleFrom(
backgroundColor: backGroundColor,
shape: RoundedRectangleBorder(
borderRadius: borderRadius ?? BorderRadius.circular(16),
),
),
child: Text(
text,
style: Styles.textStyle18.copyWith(
fontSize: fontSize,
color: textColor,
fontWeight: FontWeight.w900,
),
),
)
: CupertinoButton(
onPressed: onPressed,
color: backGroundColor,
borderRadius: borderRadius ?? BorderRadius.circular(16),
child: Text(
text,
style: Styles.textStyle18.copyWith(
fontSize: fontSize,
color: textColor,
fontWeight: FontWeight.w900,
),
),
),
);
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/widgets/custom_error.dart | import 'package:bookly/core/utils/styles.dart';
import 'package:flutter/material.dart';
class CustomError extends StatelessWidget {
const CustomError({Key? key, required this.errMessage}) : super(key: key);
final String errMessage;
@override
Widget build(BuildContext context) {
return Center(
child: Text(
errMessage,
style: Styles.textStyle18,
textAlign: TextAlign.center,
),
);
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/widgets/custom_loading_indicator.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
class CustomLoadingIndicator extends StatelessWidget {
const CustomLoadingIndicator({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Platform.isAndroid
? const CircularProgressIndicator()
: const CupertinoActivityIndicator(),
);
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/widgets/custom_fading_widget.dart | import 'package:flutter/material.dart';
class CustomFadingWidget extends StatefulWidget {
const CustomFadingWidget({super.key, required this.child});
final Widget child;
@override
State<CustomFadingWidget> createState() => _CustomFadingWidgetState();
}
class _CustomFadingWidgetState extends State<CustomFadingWidget>
with SingleTickerProviderStateMixin {
late Animation _animation;
late AnimationController _animationController;
@override
void initState() {
_animationController = AnimationController(vsync: this, duration: const Duration(seconds: 1));
_animation = Tween<double>(begin: 0.2, end: 0.5).animate(_animationController);
_animationController.addListener(() {
setState(() {});
});
_animationController.repeat(reverse: true);
super.initState();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Opacity(
opacity: _animation.value,
child: widget.child,
);
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models | mirrored_repositories/BooklyApp/lib/core/models/book_model/volume_info.dart | import 'package:equatable/equatable.dart';
import 'volume_info_model/image_links.dart';
import 'volume_info_model/reading_modes.dart';
import 'volume_info_model/industry_identifier.dart';
import 'volume_info_model/panelization_summary.dart';
class VolumeInfo extends Equatable {
final String? title;
final List<String>? authors;
final String? publisher;
final String? publishedDate;
final String? description;
final List<IndustryIdentifier>? industryIdentifiers;
final ReadingModes? readingModes;
final int? pageCount;
final String? printType;
final List<String>? categories;
final num? averageRating;
final int? ratingsCount;
final String? maturityRating;
final bool? allowAnonLogging;
final String? contentVersion;
final PanelizationSummary? panelizationSummary;
final ImageLinks? imageLinks;
final String? language;
final String? previewLink;
final String? infoLink;
final String? canonicalVolumeLink;
const VolumeInfo({
this.title,
this.authors,
this.publisher,
this.publishedDate,
this.description,
this.industryIdentifiers,
this.readingModes,
this.pageCount,
this.printType,
this.categories,
this.averageRating,
this.ratingsCount,
this.maturityRating,
this.allowAnonLogging,
this.contentVersion,
this.panelizationSummary,
this.imageLinks,
this.language,
this.previewLink,
this.infoLink,
this.canonicalVolumeLink,
});
factory VolumeInfo.fromJson(Map<String, dynamic> json) => VolumeInfo(
title: json['title'] as String?,
authors: (json['authors'] as List<dynamic>?)?.cast<String>(),
publisher: json['publisher'] as String?,
publishedDate: json['publishedDate'] as String?,
description: json['description'] as String?,
industryIdentifiers: (json['industryIdentifiers'] as List<dynamic>?)
?.map((e) => IndustryIdentifier.fromJson(e as Map<String, dynamic>))
.toList(),
readingModes: json['readingModes'] == null
? null
: ReadingModes.fromJson(
json['readingModes'] as Map<String, dynamic>),
pageCount: json['pageCount'] as int?,
printType: json['printType'] as String?,
categories: (json['categories'] as List<dynamic>?)?.cast<String>(),
averageRating: json['averageRating'] as num?,
ratingsCount: json['ratingsCount'] as int?,
maturityRating: json['maturityRating'] as String?,
allowAnonLogging: json['allowAnonLogging'] as bool?,
contentVersion: json['contentVersion'] as String?,
panelizationSummary: json['panelizationSummary'] == null
? null
: PanelizationSummary.fromJson(
json['panelizationSummary'] as Map<String, dynamic>),
imageLinks: json['imageLinks'] == null
? null
: ImageLinks.fromJson(json['imageLinks'] as Map<String, dynamic>),
language: json['language'] as String?,
previewLink: json['previewLink'] as String?,
infoLink: json['infoLink'] as String?,
canonicalVolumeLink: json['canonicalVolumeLink'] as String?,
);
Map<String, dynamic> toJson() => {
'title': title,
'authors': authors,
'publisher': publisher,
'publishedDate': publishedDate,
'description': description,
'industryIdentifiers':
industryIdentifiers?.map((e) => e.toJson()).toList(),
'readingModes': readingModes?.toJson(),
'pageCount': pageCount,
'printType': printType,
'categories': categories,
'averageRating': averageRating,
'ratingsCount': ratingsCount,
'maturityRating': maturityRating,
'allowAnonLogging': allowAnonLogging,
'contentVersion': contentVersion,
'panelizationSummary': panelizationSummary?.toJson(),
'imageLinks': imageLinks?.toJson(),
'language': language,
'previewLink': previewLink,
'infoLink': infoLink,
'canonicalVolumeLink': canonicalVolumeLink,
};
@override
List<Object?> get props {
return [
title,
authors,
publisher,
publishedDate,
description,
industryIdentifiers,
readingModes,
pageCount,
printType,
categories,
averageRating,
ratingsCount,
maturityRating,
allowAnonLogging,
contentVersion,
panelizationSummary,
imageLinks,
language,
previewLink,
infoLink,
canonicalVolumeLink,
];
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models | mirrored_repositories/BooklyApp/lib/core/models/book_model/book_model.dart | import 'sale_info.dart';
import 'access_info.dart';
import 'volume_info.dart';
import 'package:bookly/core/entities/book_entity.dart';
class BookModel extends BookEntity {
final String? kind;
final String? id;
final String? etag;
final String? selfLink;
final VolumeInfo? volumeInfo;
final SaleInfo? saleInfo;
final AccessInfo? accessInfo;
BookModel({
this.kind,
this.id,
this.etag,
this.selfLink,
this.volumeInfo,
this.saleInfo,
this.accessInfo,
}) : super(
bookId: id!,
imageUrl: volumeInfo!.imageLinks?.thumbnail ?? '',
title: volumeInfo.title!,
authorName: volumeInfo.authors?.first ?? 'Unknown',
price: 'Free',
rating: volumeInfo.averageRating ?? 0.0,
ratingsCount: volumeInfo.ratingsCount ?? 0,
previewLink: volumeInfo.previewLink,
);
factory BookModel.fromJson(Map<String, dynamic> json) => BookModel(
kind: json['kind'] as String?,
id: json['id'] as String?,
etag: json['etag'] as String?,
selfLink: json['selfLink'] as String?,
volumeInfo:
VolumeInfo.fromJson(json['volumeInfo'] as Map<String, dynamic>),
saleInfo: json['saleInfo'] == null
? null
: SaleInfo.fromJson(json['saleInfo'] as Map<String, dynamic>),
accessInfo: json['accessInfo'] == null
? null
: AccessInfo.fromJson(json['accessInfo'] as Map<String, dynamic>),
);
Map<String, dynamic> toJson() => {
'kind': kind,
'id': id,
'etag': etag,
'selfLink': selfLink,
'volumeInfo': volumeInfo?.toJson(),
'saleInfo': saleInfo?.toJson(),
'accessInfo': accessInfo?.toJson(),
};
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models | mirrored_repositories/BooklyApp/lib/core/models/book_model/sale_info.dart | import 'package:equatable/equatable.dart';
class SaleInfo extends Equatable {
final String? country;
final String? saleability;
final bool? isEbook;
const SaleInfo({this.country, this.saleability, this.isEbook});
factory SaleInfo.fromJson(Map<String, dynamic> json) => SaleInfo(
country: json['country'] as String?,
saleability: json['saleability'] as String?,
isEbook: json['isEbook'] as bool?,
);
Map<String, dynamic> toJson() => {
'country': country,
'saleability': saleability,
'isEbook': isEbook,
};
@override
List<Object?> get props => [country, saleability, isEbook];
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models | mirrored_repositories/BooklyApp/lib/core/models/book_model/access_info.dart | import 'access_info_model/pdf.dart';
import 'access_info_model/epub.dart';
import 'package:equatable/equatable.dart';
class AccessInfo extends Equatable {
final String? country;
final String? viewability;
final bool? embeddable;
final bool? publicDomain;
final String? textToSpeechPermission;
final Epub? epub;
final Pdf? pdf;
final String? webReaderLink;
final String? accessViewStatus;
final bool? quoteSharingAllowed;
const AccessInfo({
this.country,
this.viewability,
this.embeddable,
this.publicDomain,
this.textToSpeechPermission,
this.epub,
this.pdf,
this.webReaderLink,
this.accessViewStatus,
this.quoteSharingAllowed,
});
factory AccessInfo.fromJson(Map<String, dynamic> json) => AccessInfo(
country: json['country'] as String?,
viewability: json['viewability'] as String?,
embeddable: json['embeddable'] as bool?,
publicDomain: json['publicDomain'] as bool?,
textToSpeechPermission: json['textToSpeechPermission'] as String?,
epub: json['epub'] == null
? null
: Epub.fromJson(json['epub'] as Map<String, dynamic>),
pdf: json['pdf'] == null
? null
: Pdf.fromJson(json['pdf'] as Map<String, dynamic>),
webReaderLink: json['webReaderLink'] as String?,
accessViewStatus: json['accessViewStatus'] as String?,
quoteSharingAllowed: json['quoteSharingAllowed'] as bool?,
);
Map<String, dynamic> toJson() => {
'country': country,
'viewability': viewability,
'embeddable': embeddable,
'publicDomain': publicDomain,
'textToSpeechPermission': textToSpeechPermission,
'epub': epub?.toJson(),
'pdf': pdf?.toJson(),
'webReaderLink': webReaderLink,
'accessViewStatus': accessViewStatus,
'quoteSharingAllowed': quoteSharingAllowed,
};
@override
List<Object?> get props {
return [
country,
viewability,
embeddable,
publicDomain,
textToSpeechPermission,
epub,
pdf,
webReaderLink,
accessViewStatus,
quoteSharingAllowed,
];
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models/book_model | mirrored_repositories/BooklyApp/lib/core/models/book_model/volume_info_model/industry_identifier.dart | import 'package:equatable/equatable.dart';
class IndustryIdentifier extends Equatable {
final String? type;
final String? identifier;
const IndustryIdentifier({this.type, this.identifier});
factory IndustryIdentifier.fromJson(Map<String, dynamic> json) {
return IndustryIdentifier(
type: json['type'] as String?,
identifier: json['identifier'] as String?,
);
}
Map<String, dynamic> toJson() => {
'type': type,
'identifier': identifier,
};
@override
List<Object?> get props => [type, identifier];
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models/book_model | mirrored_repositories/BooklyApp/lib/core/models/book_model/volume_info_model/image_links.dart | import 'package:equatable/equatable.dart';
class ImageLinks extends Equatable {
final String? smallThumbnail;
final String? thumbnail;
const ImageLinks({this.smallThumbnail, this.thumbnail});
factory ImageLinks.fromJson(Map<String, dynamic> json) => ImageLinks(
smallThumbnail: json['smallThumbnail'] as String?,
thumbnail: json['thumbnail'] as String?,
);
Map<String, dynamic> toJson() => {
'smallThumbnail': smallThumbnail,
'thumbnail': thumbnail,
};
@override
List<Object?> get props => [smallThumbnail, thumbnail];
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models/book_model | mirrored_repositories/BooklyApp/lib/core/models/book_model/volume_info_model/reading_modes.dart | import 'package:equatable/equatable.dart';
class ReadingModes extends Equatable {
final bool? text;
final bool? image;
const ReadingModes({this.text, this.image});
factory ReadingModes.fromJson(Map<String, dynamic> json) => ReadingModes(
text: json['text'] as bool?,
image: json['image'] as bool?,
);
Map<String, dynamic> toJson() => {
'text': text,
'image': image,
};
@override
List<Object?> get props => [text, image];
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models/book_model | mirrored_repositories/BooklyApp/lib/core/models/book_model/volume_info_model/panelization_summary.dart | import 'package:equatable/equatable.dart';
class PanelizationSummary extends Equatable {
final bool? containsEpubBubbles;
final bool? containsImageBubbles;
const PanelizationSummary({
this.containsEpubBubbles,
this.containsImageBubbles,
});
factory PanelizationSummary.fromJson(Map<String, dynamic> json) {
return PanelizationSummary(
containsEpubBubbles: json['containsEpubBubbles'] as bool?,
containsImageBubbles: json['containsImageBubbles'] as bool?,
);
}
Map<String, dynamic> toJson() => {
'containsEpubBubbles': containsEpubBubbles,
'containsImageBubbles': containsImageBubbles,
};
@override
List<Object?> get props => [containsEpubBubbles, containsImageBubbles];
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models/book_model | mirrored_repositories/BooklyApp/lib/core/models/book_model/access_info_model/pdf.dart | import 'package:equatable/equatable.dart';
class Pdf extends Equatable {
final bool? isAvailable;
final String? acsTokenLink;
const Pdf({this.isAvailable, this.acsTokenLink});
factory Pdf.fromJson(Map<String, dynamic> json) => Pdf(
isAvailable: json['isAvailable'] as bool?,
acsTokenLink: json['acsTokenLink'] as String?,
);
Map<String, dynamic> toJson() => {
'isAvailable': isAvailable,
'acsTokenLink': acsTokenLink,
};
@override
List<Object?> get props => [isAvailable, acsTokenLink];
}
| 0 |
mirrored_repositories/BooklyApp/lib/core/models/book_model | mirrored_repositories/BooklyApp/lib/core/models/book_model/access_info_model/epub.dart | import 'package:equatable/equatable.dart';
class Epub extends Equatable {
final bool? isAvailable;
const Epub({this.isAvailable});
factory Epub.fromJson(Map<String, dynamic> json) => Epub(
isAvailable: json['isAvailable'] as bool?,
);
Map<String, dynamic> toJson() => {
'isAvailable': isAvailable,
};
@override
List<Object?> get props => [isAvailable];
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/use_cases/use_case.dart | import 'package:bookly/core/errors/failure.dart';
import 'package:dartz/dartz.dart';
abstract class UseCase<Type, Param> {
Future<Either<Failure, Type>> call(Param param);
} | 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/use_cases/no_param_use_case.dart | import 'package:bookly/core/errors/failure.dart';
import 'package:dartz/dartz.dart';
abstract class UseCase<Type> {
Future<Either<Failure, Type>> call();
} | 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/entities/book_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'book_entity.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class BookEntityAdapter extends TypeAdapter<BookEntity> {
@override
final int typeId = 0;
@override
BookEntity read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return BookEntity(
bookId: fields[0] as String,
imageUrl: fields[1] as String?,
title: fields[2] as String,
authorName: fields[3] as String?,
price: fields[4] as String?,
rating: fields[5] as num?,
ratingsCount: fields[6] as num?,
previewLink: fields[7] as String?,
);
}
@override
void write(BinaryWriter writer, BookEntity obj) {
writer
..writeByte(8)
..writeByte(0)
..write(obj.bookId)
..writeByte(1)
..write(obj.imageUrl)
..writeByte(2)
..write(obj.title)
..writeByte(3)
..write(obj.authorName)
..writeByte(4)
..write(obj.price)
..writeByte(5)
..write(obj.rating)
..writeByte(6)
..write(obj.ratingsCount)
..writeByte(7)
..write(obj.previewLink);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BookEntityAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/entities/book_entity.dart | import 'package:hive/hive.dart';
part 'book_entity.g.dart';
@HiveType(typeId: 0)
class BookEntity extends HiveObject {
@HiveField(0)
final String bookId;
@HiveField(1)
final String? imageUrl;
@HiveField(2)
final String title;
@HiveField(3)
final String? authorName;
@HiveField(4)
final String? price;
@HiveField(5)
final num? rating;
@HiveField(6)
final num? ratingsCount;
@HiveField(7)
final String? previewLink;
BookEntity({
required this.bookId,
required this.imageUrl,
required this.title,
required this.authorName,
required this.price,
required this.rating,
required this.ratingsCount,
required this.previewLink,
});
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/errors/server_failure.dart | import 'failure.dart';
import 'package:dio/dio.dart';
class ServerFailure extends Failure {
ServerFailure({required String errMessage}) : super(errMessage);
factory ServerFailure.fromDioError(DioException dioException) {
switch (dioException.type) {
case DioExceptionType.cancel:
return ServerFailure(errMessage: "Request to server was cancelled");
case DioExceptionType.connectionError:
return ServerFailure(errMessage: "Connection to server failed due to internet connection");
case DioExceptionType.connectionTimeout:
return ServerFailure(errMessage: "Connection timeout with server");
case DioExceptionType.receiveTimeout:
return ServerFailure(errMessage: "Receive timeout in connection with server");
case DioExceptionType.sendTimeout:
return ServerFailure(errMessage: "Send timeout in connection with server");
case DioExceptionType.badCertificate:
return ServerFailure(errMessage: "Bad certificate in connection with server");
case DioExceptionType.badResponse:
return ServerFailure._fromResponse(dioException.response!);
default:
return ServerFailure(errMessage: "Oops, an unexpected error occurred, please try again later");
}
}
factory ServerFailure._fromResponse(Response response) {
final statusCode = response.statusCode!;
final responseData = response.data!;
String errorMessage = 'Oops, an unexpected error occurred, please try again later';
if (responseData is Map<String, dynamic> && responseData.containsKey('error')) {
final errorData = responseData['error'];
if (errorData is Map<String, dynamic> && errorData.containsKey('message')) {
errorMessage = errorData['message'];
}
}
switch (statusCode) {
case 404:
errorMessage = 'Your request was not found, please try again later';
break;
case 500:
errorMessage = 'Internal server error, please try again later';
break;
case 400:
case 401:
case 402:
case 403:
errorMessage = errorMessage.isNotEmpty ? errorMessage : "An error occurred while processing your request";
break;
default:
break;
}
return ServerFailure(errMessage: errorMessage);
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/errors/failure.dart | abstract class Failure {
final String errMessage;
const Failure(this.errMessage);
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/utils/styles.dart | import 'package:bookly/constants.dart';
import 'package:flutter/material.dart';
abstract class Styles {
static const TextStyle textStyle14 = TextStyle(
fontSize: 14,
fontWeight: FontWeight.normal,
color: Color(0xff707070),
);
static const TextStyle textStyle16 = TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w500,
);
static const TextStyle textStyle18 = TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
);
static const TextStyle textStyle20 = TextStyle(
fontSize: 20,
fontWeight: FontWeight.normal,
);
static const TextStyle textStyle30 = TextStyle(
fontSize: 30,
fontWeight: FontWeight.w400,
fontFamily: kGtSectraFine,
);
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/utils/url_launcher.dart | import 'package:bookly/core/functions/show_custom_snack_bar.dart';
import 'package:url_launcher/url_launcher_string.dart';
Future<void> launchMyUrl(context, String? url) async {
if (url != null) {
if (await canLaunchUrlString(url)) {
await launchUrlString(url, mode: LaunchMode.externalApplication);
} else {
showCustomSnackBar(context, 'Can`t launch url');
}
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/utils/api_service.dart | import 'package:dio/dio.dart';
class ApiService {
final String _baseUrl = 'https://www.googleapis.com/books/v1/';
final Dio _dio;
ApiService(this._dio);
Future<Map<String, dynamic>> get({required String endpoint}) async {
var response = await _dio.get(_baseUrl + endpoint);
return response.data;
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/utils/service_locator.dart | import 'api_service.dart';
import 'package:dio/dio.dart';
import 'package:get_it/get_it.dart';
import 'package:bookly/features/home/data/repos/home_repo_impl.dart';
import 'package:bookly/features/search/data/repos/search_repo_impl.dart';
import 'package:bookly/features/home/domain/use_cases/fetch_newest_books_use_case.dart';
import 'package:bookly/features/home/domain/use_cases/fetch_similar_books_use_case.dart';
import 'package:bookly/features/home/domain/use_cases/fetch_featured_books_use_case.dart';
import 'package:bookly/features/search/domain/use_cases/fetch_searched_books_use_case.dart';
import 'package:bookly/features/home/data/data_sources/home_local_data_source/home_local_data_source_impl.dart';
import 'package:bookly/features/home/data/data_sources/home_remote_data_source/home_remote_data_source_impl.dart';
final GetIt getIt = GetIt.instance;
void setupServiceLocator() {
getIt.registerSingleton<ApiService>(ApiService(Dio()));
getIt.registerSingleton<HomeRemoteDataSourceImpl>(HomeRemoteDataSourceImpl(
getIt.get<ApiService>(),
));
getIt.registerSingleton<HomeRepoImpl>(HomeRepoImpl(
homeRemoteDataSource: getIt.get<HomeRemoteDataSourceImpl>(),
homeLocalDataSource: HomeLocalDataSourceImpl(),
));
getIt.registerSingleton<FetchFeaturedBooksUseCase>(FetchFeaturedBooksUseCase(
getIt.get<HomeRepoImpl>(),
));
getIt.registerSingleton<FetchNewestBooksUseCase>(FetchNewestBooksUseCase(
getIt.get<HomeRepoImpl>(),
));
getIt.registerSingleton<FetchSimilarBooksUseCase>(FetchSimilarBooksUseCase(
getIt.get<HomeRepoImpl>(),
));
getIt.registerSingleton<SearchRepoImpl>(
SearchRepoImpl(getIt.get<ApiService>()),
);
getIt.registerSingleton<FetchSearchedBooksUseCase>(
FetchSearchedBooksUseCase(getIt.get<SearchRepoImpl>()),
);
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/utils/app_router.dart | import 'package:bookly/constants.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:bookly/core/utils/service_locator.dart';
import 'package:bookly/core/entities/book_entity.dart';
import 'package:bookly/features/search/presentation/views/search_view.dart';
import 'package:bookly/features/splash/presentation/views/splash_view.dart';
import 'package:bookly/features/home/presentation/views/home_view/home_view.dart';
import 'package:bookly/features/home/domain/use_cases/fetch_similar_books_use_case.dart';
import 'package:bookly/features/search/domain/use_cases/fetch_searched_books_use_case.dart';
import 'package:bookly/features/home/presentation/views/book_details_view/book_details_view.dart';
import 'package:bookly/features/home/presentation/cubits/similar_books_cubit/similar_book_cubit.dart';
import 'package:bookly/features/search/presentation/cubits/searched_books_cubit/searched_books_cubit.dart';
abstract class AppRouter {
static final router = GoRouter(
routes: [
GoRoute(
path: kSplashView,
builder: (context, state) => const SplashView(),
),
GoRoute(
path: kHomeView,
builder: (context, state) => const HomeView(),
),
GoRoute(
path: kBookDetailsView,
builder: (context, state) => BlocProvider(
create: (context) => SimilarBooksCubit(getIt.get<FetchSimilarBooksUseCase>())..fetchSimilarBooks(),
child: BookDetailsView(
book: state.extra as BookEntity,
),
),
),
GoRoute(
path: kSearchView,
builder: (context, state) => BlocProvider(
create: (context) => SearchedBooksCubit(getIt.get<FetchSearchedBooksUseCase>()),
child: const SearchView()),
),
],
);
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/functions/show_custom_snack_bar.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:go_router/go_router.dart';
import 'package:bookly/core/utils/styles.dart';
void showCustomSnackBar(BuildContext context, String text) {
if (Platform.isAndroid) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.grey[800],
content: Text(
text,
style: Styles.textStyle16,
),
duration: const Duration(seconds: 2),
),
);
} else {
showCupertinoModalPopup(
barrierDismissible: true,
barrierColor: Colors.grey[800]!,
context: context,
builder: (context) => CupertinoActionSheet(
title: const Text(
'Error',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
message: Text(
text,
style: Styles.textStyle16,
),
cancelButton: CupertinoActionSheetAction(
onPressed: () => GoRouter.of(context).pop(),
child: const Text('OK'),
),
),
);
}
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/functions/setup_hive_db.dart | import 'package:bookly/constants.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:bookly/core/entities/book_entity.dart';
Future<void> setupHiveDB() async {
await Hive.initFlutter();
Hive.registerAdapter(BookEntityAdapter());
Future.wait([
Hive.openBox<BookEntity>(kFeaturedBox),
Hive.openBox<BookEntity>(kNewestBox),
Hive.openBox<BookEntity>(kSimilarBox),
]);
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/functions/cache_books_list.dart | import 'package:hive/hive.dart';
import 'package:bookly/core/entities/book_entity.dart';
void cacheBooksList(List<BookEntity> books, String boxName) {
var box = Hive.box<BookEntity>(boxName);
box.addAll(books);
} | 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/functions/get_books_list.dart | import 'package:bookly/core/models/book_model/book_model.dart';
import 'package:bookly/core/entities/book_entity.dart';
List<BookEntity> getBooksList(Map<String, dynamic> data) {
List<BookEntity> books = [];
if (data['items'] == null) {
return books;
}
for (var item in data['items']) {
books.add(BookModel.fromJson(item));
}
return books;
}
| 0 |
mirrored_repositories/BooklyApp/lib/core | mirrored_repositories/BooklyApp/lib/core/functions/set_system_ui_overlay_style.dart | import 'package:flutter/services.dart';
import 'package:bookly/constants.dart';
void setSystemUIOverlayStyle() {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: kPrimaryColor,
statusBarIconBrightness: Brightness.light,
),
);
} | 0 |
mirrored_repositories/BooklyApp | mirrored_repositories/BooklyApp/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:bookly/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const Bookly());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/chemfriend-mobile | mirrored_repositories/chemfriend-mobile/lib/custom_header.dart | import 'package:flutter/material.dart';
Widget customHeader() {
return DrawerHeader(
margin: EdgeInsets.zero,
padding: EdgeInsets.zero,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Colors.red,
Colors.orange,
Colors.yellow,
Colors.green,
]),
),
child: Stack(children: <Widget>[
Positioned(
bottom: 12.0,
left: 16.0,
child: Text("Chemfriend",
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w500))),
]));
}
| 0 |
mirrored_repositories/chemfriend-mobile | mirrored_repositories/chemfriend-mobile/lib/input.dart | import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:chemfriend/chemistry/chemistry.dart';
class Input extends StatefulWidget {
Input(
{Key key,
this.onPressed,
this.scrollController,
this.placeholder,
this.buttonSideLength})
: super(key: key);
/// This function is called every time the arrow button is pressed.
final Function onPressed;
/// This is the scroll controller for the page of the input.
final ScrollController scrollController;
/// This String is the placeholder of the text input.
final String placeholder;
/// This is the side length of the red button.
final int buttonSideLength;
@override
_InputState createState() => _InputState();
}
class _InputState extends State<Input> {
final _textController = TextEditingController();
final _key = GlobalKey();
@override
void dispose() {
_textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Enter an equation and press the big red button:', key: _key),
Center(
child: TextField(
controller: _textController,
textInputAction: TextInputAction.done,
onTap: _scrollToStart,
style: TextStyle(
fontSize: 20.0,
),
decoration: InputDecoration(
hintText: widget.placeholder,
),
textCapitalization: TextCapitalization.characters,
),
),
SizedBox(height: 25),
Center(
child: ButtonBar(
alignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
addButton(' + ', '+'),
addButton(' => ', '→'),
addButton('(', '('),
addButton(')', ')'),
])),
Center(
child: ButtonBar(
alignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
addButton('(s)', "(s)"),
addButton('(l)', "(l)"),
addButton('(g)', "(g)"),
addButton('(aq)', "(aq)"),
],
)),
SizedBox(height: 25),
Center(
child: SizedBox(
width: widget.buttonSideLength.toDouble(),
height: widget.buttonSideLength.toDouble(),
child: FloatingActionButton(
heroTag: '_onPressed',
child: Icon(Icons.forward),
onPressed: () {
try {
Equation e = new Equation(_textController.text);
e.balance();
widget.onPressed(context, e);
_textController.text = '';
FocusScope.of(context).unfocus();
} catch (err) {
Fluttertoast.showToast(
msg: "Sorry, I can't solve that!",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.teal[900],
textColor: Colors.white,
fontSize: 16.0);
}
},
),
))
]);
}
/// Returns a button that adds [append] to the end of [_textController]'s text
/// and has the label [display].
Widget addButton(String append, String display) {
return RaisedButton(
padding: EdgeInsets.all(8.0),
onPressed: () => _addText(append),
child: Text(display));
}
/// Adds [append] to [_textController]'s text and moves the cursor to the end.
void _addText(String append) {
int prevOffset = _textController.selection.baseOffset;
_textController.text = _textController.text.substring(0, prevOffset) +
append +
_textController.text.substring(prevOffset);
_textController.selection = TextSelection.fromPosition(
TextPosition(offset: prevOffset + append.length));
}
/// Scrolls to the start of the equation input.
void _scrollToStart() async {
RenderBox box = _key.currentContext.findRenderObject();
Offset position = box.localToGlobal(Offset.zero);
await Future.delayed(const Duration(milliseconds: 500), () {});
widget.scrollController.animateTo(position.dy - 20,
duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
}
}
| 0 |
mirrored_repositories/chemfriend-mobile | mirrored_repositories/chemfriend-mobile/lib/main.dart | import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:chemfriend/chemistry/chemistry.dart';
import 'pages/solution.dart';
import 'pages/about.dart';
import 'pages/tutorial.dart';
import 'input.dart';
import 'custom_header.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Chemfriend',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: MyHomePage(title: 'Chemfriend'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _textController = TextEditingController();
final _scrollController = ScrollController();
void startup() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool opened = prefs.getBool('opened');
if (opened == null) {
prefs.setBool('opened', true);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Tutorial()),
);
}
}
@override
void initState() {
super.initState();
startup();
}
@override
void dispose() {
_textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
centerTitle: true,
),
body: ListView(controller: _scrollController, children: <Widget>[
SizedBox(height: 40),
Input(
onPressed: _pushSolution,
scrollController: _scrollController,
placeholder: "E.g. C6H12O6(s) + O2(g)",
buttonSideLength: 115,
)
]),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
customHeader(),
ListTile(
leading: Icon(Icons.info_outline),
title: Text('About'),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => About()),
);
},
),
ListTile(
leading: Icon(Icons.school),
title: Text('Tutorial'),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Tutorial()),
);
},
),
],
)),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (context) => Tutorial()),
),
child: Icon(Icons.info_outline),
backgroundColor: Colors.green,
),
);
}
void _pushSolution(BuildContext context, Equation e) async {
String solution = e.toString();
String type = typeToString[e.type];
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Solution(equation: e, solution: solution, type: type)),
);
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib | mirrored_repositories/chemfriend-mobile/lib/pages/explanation.dart | import 'package:flutter/material.dart';
import 'package:chemfriend/chemistry/chemistry.dart';
class Explanation extends StatefulWidget {
Explanation({Key key, this.equation}) : super(key: key);
final Equation equation;
@override
_ExplanationState createState() => _ExplanationState();
}
class _ExplanationState extends State<Explanation> {
final _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
controller: _scrollController,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 80.0),
child: Column(
children: <Widget>[
Text(
"Type",
style: TextStyle(fontSize: 16.0),
),
Text(widget.equation.typeSteps.join('\n') + '\n'),
Text(
"Product(s)",
style: TextStyle(fontSize: 16.0),
),
Text(widget.equation.productSteps.join('\n') + '\n'),
Text(
"Balancing",
style: TextStyle(fontSize: 16.0),
),
Text(widget.equation.balanceSteps.join('\n') + '\n'),
Text(
'Final Equation',
style: TextStyle(fontSize: 16.0),
),
Text('${widget.equation}')
],
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.pop(context),
child: Icon(Icons.arrow_back)));
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib | mirrored_repositories/chemfriend-mobile/lib/pages/solution.dart | import 'package:flutter/material.dart';
import 'package:chemfriend/chemistry/chemistry.dart';
import '../input.dart';
import '../custom_header.dart';
import 'explanation.dart';
import 'about.dart';
import 'tutorial.dart';
class Solution extends StatefulWidget {
Solution({Key key, this.equation, this.solution, this.type})
: super(key: key);
final Equation equation;
final String solution;
final String type;
@override
_SolutionState createState() => _SolutionState();
}
class _SolutionState extends State<Solution> {
final _textController = TextEditingController();
final _scrollController = ScrollController();
Equation equation;
String solution;
String type;
@override
void initState() {
super.initState();
equation = widget.equation;
solution = widget.solution;
type = widget.type;
}
@override
void dispose() {
_textController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Chemfriend',
style: TextStyle(fontFamily: 'open_sans'),
),
centerTitle: true,
),
body: ListView(
controller: _scrollController,
children: <Widget>[
SizedBox(height: 20),
Center(
child: Text(
'Type: $type',
style: TextStyle(fontSize: 25.0, fontStyle: FontStyle.italic),
textAlign: TextAlign.center,
)),
SizedBox(height: 20),
Center(
child: Row(children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: EdgeInsets.all(12.0),
child: FloatingActionButton(
heroTag: '_pushExplanation',
child: Icon(Icons.info),
mini: true,
backgroundColor: Colors.green,
onPressed: () {
_pushExplanation(context);
_textController.text = '';
},
),
),
),
Expanded(
flex: 6,
child: Padding(
padding: EdgeInsets.all(3.0),
child: Text(solution,
style: TextStyle(fontSize: 20.0),
textAlign: TextAlign.center))),
])),
SizedBox(height: 20),
SizedBox(height: 20),
Input(
onPressed: _reloadSolution,
scrollController: _scrollController,
placeholder: "",
buttonSideLength: 88,
)
],
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
customHeader(),
ListTile(
leading: Icon(Icons.info_outline),
title: Text('About'),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => About()),
);
},
),
ListTile(
leading: Icon(Icons.school),
title: Text('Tutorial'),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Tutorial()),
);
},
),
],
)),
);
}
void _reloadSolution(BuildContext context, Equation e) async {
setState(() {
equation = e;
solution = e.toString();
type = typeToString[e.type];
});
}
void _pushExplanation(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Explanation(equation: equation)),
);
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib | mirrored_repositories/chemfriend-mobile/lib/pages/about.dart | import 'package:flutter/material.dart';
import 'tutorial.dart';
import '../main.dart';
import '../custom_header.dart';
class About extends StatefulWidget {
About({Key key}) : super(key: key);
@override
_AboutState createState() => _AboutState();
}
class _AboutState extends State<About> {
final _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chemfriend'),
centerTitle: true,
),
body: ListView(
controller: _scrollController,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 80.0),
child: Column(
children: <Widget>[
Text(
"About Chemfriend",
style: TextStyle(fontSize: 18.0),
textAlign: TextAlign.left,
),
SizedBox(height: 8),
Text(
"Chemfriend is an app for high school students studying chemistry. Currently, it is able to solve chemical equations taught in the Alberta Science 10 PreAP curriculum.",
style: TextStyle(fontSize: 14.0),
textAlign: TextAlign.left,
),
SizedBox(height: 18),
ListTile(
leading: Icon(Icons.create),
title:
Text("Created by Saptarshi Bhattacherya in 2020")),
ListTile(
leading: Icon(Icons.email),
title: Text("[email protected]")),
ListTile(
leading: Icon(Icons.view_carousel),
title: Text("v1.0.0"))
],
),
),
],
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
customHeader(),
ListTile(
leading: Icon(Icons.edit),
title: Text('Solver'),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyHomePage(title: 'Chemfriend')),
);
},
),
ListTile(
leading: Icon(Icons.school),
title: Text('Tutorial'),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Tutorial()),
);
},
),
],
)),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.pop(context),
child: Icon(Icons.cancel)));
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib | mirrored_repositories/chemfriend-mobile/lib/pages/tutorial.dart | import 'package:flutter/material.dart';
import 'about.dart';
import '../main.dart';
import '../custom_header.dart';
class Tutorial extends StatefulWidget {
Tutorial({Key key}) : super(key: key);
@override
_TutorialState createState() => _TutorialState();
}
class _TutorialState extends State<Tutorial> {
final _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chemfriend'),
centerTitle: true,
),
body: ListView(
controller: _scrollController,
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 80.0),
child: Column(
children: <Widget>[
Text(
"Tutorial",
style: TextStyle(fontSize: 18.0),
textAlign: TextAlign.left,
),
SizedBox(height: 8),
Text(
"Enter any equation in the text field, with or without products. Examples:\n",
style: TextStyle(fontSize: 14.0),
textAlign: TextAlign.left,
),
Text(
"• C6H12O6(s) + O2(g)",
style: TextStyle(fontSize: 16.0),
textAlign: TextAlign.left,
),
Text(
"• H2(g) + O2(g) => H2O(l)\n",
style: TextStyle(fontSize: 16.0),
textAlign: TextAlign.left,
),
Text(
"Be sure to use the buttons to help enter your equation (for example, instead of typing \"=>\" use the → button):",
style: TextStyle(fontSize: 14.0),
textAlign: TextAlign.left,
),
Image(image: AssetImage('assets/InputButtons.png')),
Text(
"Finally, tap the info button that appears to the left of the equations to find out how the equation was solved:\n",
style: TextStyle(fontSize: 14.0),
),
Image(image: AssetImage('assets/InfoButton.png')),
],
),
),
],
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
customHeader(),
ListTile(
leading: Icon(Icons.edit),
title: Text('Solver'),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MyHomePage(title: 'Chemfriend')),
);
},
),
ListTile(
leading: Icon(Icons.info_outline),
title: Text('About'),
onTap: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => About()),
);
},
),
],
)),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.pop(context),
child: Icon(Icons.cancel)));
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib | mirrored_repositories/chemfriend-mobile/lib/chemistry/chemistry.dart | library chemistry;
import 'package:periodic_table/periodic_table.dart';
part 'src/common_ions.dart';
part 'src/compound.dart';
part 'src/compound_unit.dart';
part 'src/element.dart';
part 'src/equation.dart';
part 'src/helpers.dart';
| 0 |
mirrored_repositories/chemfriend-mobile/lib/chemistry | mirrored_repositories/chemfriend-mobile/lib/chemistry/src/helpers.dart | part of chemistry;
/// Maps MatterPhases to their Phase variants.
///
/// MatterPhases are used in ChemicalElements and Phases are used in Elements
/// and Compounds.
Map<MatterPhase, Phase> mPhaseToPhase = {
MatterPhase.solid: Phase.solid,
MatterPhase.liquid: Phase.liquid,
MatterPhase.gas: Phase.gas,
};
/// Maps characters to their superscript and subscript variants.
Map<String, List<String>> changeScript = {
'0': ['\u2070', '\u2080'],
'1': ['\u00B9', '\u2081'],
'2': ['\u00B2', '\u2082'],
'3': ['\u00B3', '\u2083'],
'4': ['\u2074', '\u2084'],
'5': ['\u2075', '\u2085'],
'6': ['\u2076', '\u2086'],
'7': ['\u2077', '\u2087'],
'8': ['\u2078', '\u2088'],
'9': ['\u2079', '\u2089'],
's': ['\u02e2', '\u209b'],
'l': ['\u02e1', '\u2097'],
'g': ['\u1d4d', '?'],
'a': ['\u1d43', '\u2090'],
'q': ['?', '?'],
'(': ['\u207D', '\u208D'],
')': ['\u207E', '\u208E'],
};
/// Maps Phases to their String variants.
Map<Phase, String> phaseToString = {
Phase.solid: '(s)',
Phase.liquid: '(l)',
Phase.gas: '(g)',
Phase.aqueous: '(aq)'
};
/// Maps Types (for Equations) to their String variants.
Map<Type, String> typeToString = {
Type.comp: 'Simple Composition',
Type.compAcid: 'Composition of an Acid',
Type.compBase: 'Composition of a Base',
Type.compSalt: 'Composition of a Salt',
Type.decomp: 'Simple Decomposition',
Type.decompAcid: 'Decomposition of an Acid',
Type.decompBase: 'Decomposition of a Base',
Type.decompSalt: 'Decomposition of a Salt',
Type.combustion: 'Hydrocarbon Combustion',
Type.singleReplacement: 'Single Replacement',
Type.doubleReplacement: 'Double Replacement',
Type.neutralization: 'Double Replacement (Neutralization)'
};
/// Maps ions to ions they combine with to become solid in water.
Map<List<String>, List<String>> ionToSolid = {
[
'H',
'Li',
'Na',
'K',
'Rb',
'Cs',
'Fr',
'NH4',
'NO3',
'ClO3',
'ClO4',
'CH3COO'
]: [],
['F']: ['Li', 'Mg', 'Ca', 'Sr', 'Ba', 'Fe2+', 'Hg22+', 'Pb2+'],
['Cl', 'Br', 'I']: ['Cu+', 'Ag', 'Hg22+', 'Pb2+', 'Tl+'],
['SO4']: ['Ca', 'Sr', 'Ba', 'Ag', 'Hg22+', 'Pb2+', 'Ra']
};
/// Maps ions to ions they combine with to become aqueous in water.
Map<List<String>, List<String>> ionToAqueous = {
['CO3', 'PO4', 'SO3']: ['H', 'Li', 'Na', 'K', 'Rb', 'Cs', 'Fr', 'NH4'],
['IO3', 'OOCCOO']: ['H', 'Li', 'Na', 'K', 'Rb', 'Cs', 'Fr', 'NH4'],
['OH']: ['H', 'Li', 'Na', 'K', 'Rb', 'Cs', 'Fr', 'NH4']
};
/// List of formulas of compounds that are solid in water.
List<String> solidCompounds = [
'RbClO4',
'CsClO4',
'AgCH3COO',
'Hg2(CH3COO)2'
];
/// List of formulas of compounds that are aqueous in water.
List<String> aqueousCompounds = ['Co(IO3)2', 'Fe2(OOCCOO)3'];
/// Returns `true` if [c] is `Hg₂2+`.
bool isHg22plus(MapEntry<CompoundUnit, int> c) {
return c.key.equals('Hg') && c.value == 2 && c.key.charge == 2;
}
/// Returns `true` if [s] contains a number.
bool isNumeric(String s) => double.tryParse(s) != null;
/// Returns the least common multiple of [a] and [b].
int lcm(int a, int b) => (a * b) ~/ gcd(a, b);
/// Returns the greatest common divisor of [a] and [b].
int gcd(int a, int b) {
while (b != 0) {
var t = b;
b = a % t;
a = t;
}
return a;
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib/chemistry | mirrored_repositories/chemfriend-mobile/lib/chemistry/src/compound.dart | part of chemistry;
/// Enum for each possible state of compounds.
enum Phase { solid, liquid, gas, aqueous }
/// A class that represents a chemical compound.
class Compound with CompoundUnit {
/// A list of MapEntries that map each unit to the number of molecules
/// present.
List<MapEntry<CompoundUnit, int>> compoundUnits;
/// A Boolean value that represents whether or not this compound is
/// ionic.
bool ionic;
/// The state of this compound.
Phase state;
/// The chemical formula of this compound.
String formula;
/// The charge of this compound.
int charge;
/// Constructs a compound from its chemical [formula].
///
/// ```dart
/// Compound c = new Compound('H2O(l)');
/// ```
Compound(String formula, {bool nested = false, int charge}) {
this.formula = formula;
this.charge = charge;
compoundUnits = [];
ionic = false;
bool containsMetal = false;
bool containsNonmetal = false;
int i = 0;
Element current;
bool hasState = formula[formula.length - 1].compareTo(')') == 0;
while (i <
formula.length -
(nested
? 0
: hasState
? formula[formula.length - 2].compareTo('q') == 0 ? 4 : 3
: 0)) {
if (i == formula.length - 1) {
current = new Element(formula[i]);
i++;
} else if (formula[i].compareTo('(') != 0) {
if (Element.exists(formula.substring(i, i + 2))) {
current = new Element(formula.substring(i, i + 2));
i += 2;
} else {
current = new Element(formula[i]);
i++;
}
} else {
int j = formula.indexOf(')', i);
int k = j + 1;
while (k < formula.length && isNumeric(formula[k])) k++;
Compound c = Compound(formula.substring(i + 1, j), nested: true);
if (k == j + 1)
compoundUnits.add(MapEntry(c, 1));
else
compoundUnits
.add(MapEntry(c, int.parse(formula.substring(j + 1, k))));
for (MapEntry cu in c.compoundUnits) {
if (cu.key.metal)
containsMetal = true;
else if (!cu.key.metal) containsNonmetal = true;
}
if (c.formula.compareTo('NH4') == 0) containsMetal = true;
i = k;
continue;
}
if (current.metal)
containsMetal = true;
else if (!current.metal) containsNonmetal = true;
int j = i;
while (j < formula.length && isNumeric(formula[j])) j++;
if (i == j)
compoundUnits.add(MapEntry(current, 1));
else
compoundUnits
.add(MapEntry(current, int.parse(formula.substring(i, j))));
current = null;
i = j;
}
if (!nested && hasState) {
switch (formula[formula.length - 2]) {
case 's':
this.state = Phase.solid;
break;
case 'l':
this.state = Phase.liquid;
break;
case 'g':
this.state = Phase.gas;
break;
case 'q':
this.state = Phase.aqueous;
break;
}
} else
state = null;
if (containsMetal && containsNonmetal) ionic = true;
_commonIonCharge();
_multivalent();
}
/// Contructs a compound from its individual [units] and its [state].
///
/// ```dart
/// List<MapEntry<CompoundUnit, int>> units = [
/// MapEntry(new Element('Na'), 2),
/// MapEntry(Compound('SO3'), 1)
/// ];
/// Compound c = Compound.fromUnits(units, Phase.solid);
/// ```
Compound.fromUnits(List<MapEntry<CompoundUnit, int>> units,
[Phase state]) {
this.compoundUnits = units;
this.state = state;
formula = '';
for (MapEntry<CompoundUnit, int> c in this.compoundUnits) {
if (c.key.isElement() || c.value == 1)
formula += c.key.formula;
else
formula += '(${c.key.formula})';
if (c.value != 1) formula += c.value.toString();
}
ionic = this.isIonic();
_commonIonCharge();
_multivalent();
}
/// Returns a copy of this compound with no state.
Compound withoutState() {
return Compound.fromUnits(this.compoundUnits, null);
}
/// Returns true if the compound with [units] is ionic.
bool isIonic() {
if (this.equals('H2O')) return false;
bool _containsMetal = false;
bool _containsNonmetal = false;
for (MapEntry c in compoundUnits) {
if (c.key.isElement()) {
if (c.key.metal)
_containsMetal = true;
else
_containsNonmetal = true;
} else {
if (c.key.getCharge() > 0)
_containsMetal = true;
else
_containsNonmetal = true;
}
}
return _containsMetal && _containsNonmetal;
}
/// Determines the charge of a multivalent metal if this compound is ionic.
///
/// To do so, it uses the anion in the compound and assumes the compound is
/// properly balanced.
/// For example, to find the charge of `Fe` in `Fe₂(SO₃)₃`, the following
/// process is used:
///
/// 1. Charge of SO₃ = -2
/// 2. ∴ Charge of (SO₃)₃ = -2 * 3 = -6
/// 3. ∴ Charge of Fe₂ = -6 * -1 = 6
/// 4. ∴ Charge of Fe = 6 / 2 = +3
void _multivalent() {
if (ionic) {
CompoundUnit first = compoundUnits[0].key;
if (first.isElement() &&
first.category.compareTo('transition metal') == 0) {
int negative =
compoundUnits[1].key.getCharge() * compoundUnits[1].value;
compoundUnits[0].key.charge = -(negative ~/ compoundUnits[0].value);
}
}
}
/// Determines the charge of this compound if it is a common ion.
///
/// This uses the [commonIons] map of common polyatomic ions.
void _commonIonCharge() {
String formulaWithoutState =
(this.formula[this.formula.length - 1].compareTo(')') != 0)
? this.formula
: this.formula.substring(
0,
this.formula.length -
((this.state == Phase.aqueous) ? 4 : 3));
if (this.getCharge() == null) {
if (commonIons.containsKey(formulaWithoutState)) {
this.charge = commonIons[formulaWithoutState];
}
}
}
/// Returns the String representation of this compound.
@override
String toString() {
String result = '';
for (MapEntry<CompoundUnit, int> c in this.compoundUnits) {
if (c.key.isElement())
result += c.key.formula;
else {
if (c.value != 1)
result += '(${c.key.toString()})';
else
result += '${c.key.toString()}';
}
String intString = c.value.toString();
String specialString = '';
for (int i = 0; i < intString.length; i++)
specialString += '${changeScript[intString[i]][1]}';
if (c.value != 1) result += specialString;
}
if (this.state != null) result += phaseToString[this.state];
return result;
}
/// Returns `true` if this element has the formula [formula].
///
/// ```dart
/// Compound c = new Compound('H2O(l)');
/// print(c.equals('H2O2(l)')); // false
/// print(c.equals('H2O(l)')); // true
/// ```
@override
bool equals(String formula) {
return this.formula.compareTo(formula) == 0;
}
/// Returns `true` if this compound contains [substance].
///
/// ```dart
/// Compound c = new Compound('H2O(l)');
/// print(c.contains('H')); // true
/// print(c.contains('Ca')); // false
/// ```
bool contains(String substance) {
return this.formula.contains(substance);
}
/// Returns `true` if this compound is an acid.
///
/// Checks if the first element is `H` and the phase is `Phase.aqueous`.
/// ```dart
/// Compound c = new Compound('H2O(l)');
/// Compound d = new Compound('H2CO3(aq)');
/// print(c.isAcid()); // false
/// print(d.isAcid()); // true
/// ```
bool isAcid() {
return this.compoundUnits[0].key.equals('H') &&
this.state == Phase.aqueous;
}
/// Returns `true` is this compound is a base.
///
/// Checks is this is ammonia (`NH3`), or is ionic and contains hydroxide
/// (`OH`) or carbonate (`CO3`).
/// ```dart
/// Compound c = new Compound('H2O(l)');
/// Compound d = new Compound('NaOH(aq)');
/// print(c.isBase()); // false
/// print(d.isBase()); // true
/// ```
bool isBase() {
return this.equals('NH₃') ||
(this.ionic && (this.contains('OH') || this.contains('CO₃')));
}
/// Returns the state of this compound when in water.
///
/// This method uses data from the solubility chart.
Phase getWaterState() {
Phase result;
for (int i = 0; i < 2; i++) {
Map<List<String>, List<String>> ionMap = [ionToSolid, ionToAqueous][i];
ionMap.forEach((List<String> first, List<String> second) {
for (String f in first) {
if (this.compoundUnits[0].key.equals(f) ||
(f.compareTo('Hg22+') == 0 &&
isHg22plus(this.compoundUnits[0]))) {
for (String s in second) {
if (this.compoundUnits[1].key.equals(s)) {
result = (i == 0) ? Phase.solid : Phase.aqueous;
break;
}
}
if (result == null) {
result = (i == 0) ? Phase.aqueous : Phase.solid;
break;
}
} else if (this.compoundUnits[1].key.equals(f) ||
(f.compareTo('Hg22+') == 0 &&
isHg22plus(this.compoundUnits[0]))) {
for (String s in second) {
if (this.compoundUnits[0].key.equals(s)) {
result = (i == 0) ? Phase.solid : Phase.aqueous;
break;
}
}
if (result == null) {
result = (i == 0) ? Phase.aqueous : Phase.solid;
break;
}
}
}
});
}
// Exceptions to the above.
solidCompounds.forEach((String s) {
if (this.equals(s)) result = Phase.solid;
});
aqueousCompounds.forEach((String s) {
if (this.equals(s)) result = Phase.aqueous;
});
if (result == null) result = Phase.solid;
return result;
}
/// Prints the individual units of this compound.
void printUnits() {
for (MapEntry c in compoundUnits) {
if (c.key.isElement())
print('${c.key.name}: ${c.value}');
else
print('${c.key.formula}: ${c.value}');
}
}
/// Prints the formula, category, and state of this compound.
void printInfo() {
print('Compound: ${this.toString()}');
print('Category: ${(ionic) ? 'Ionic' : 'Molecular'}');
print(
'State: ${(state == Phase.solid) ? 'Solid' : (state == Phase.liquid) ? 'Liquid' : (state == Phase.gas) ? 'Gas' : 'Aqueous'}');
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib/chemistry | mirrored_repositories/chemfriend-mobile/lib/chemistry/src/equation.dart | part of chemistry;
/// Enum for each possible type of reaction.
enum Type {
comp,
compAcid,
compBase,
compSalt,
decomp,
decompAcid,
decompBase,
decompSalt,
combustion,
singleReplacement,
doubleReplacement,
neutralization
}
/// A class representing a chemical equation.
class Equation {
/// The reactants of this equation.
List<MapEntry<CompoundUnit, int>> reactants;
/// The products of this equation.
List<MapEntry<CompoundUnit, int>> products;
/// A Boolean that represents whether or not the reactants of this equation
/// are in water.
bool rInWater;
/// A Boolean that represents whether or not the products of this equation
/// are in water.
bool pInWater;
/// The type of this reaction.
Type type;
/// A list of Strings containing the steps of how to find the type of this
/// reaction.
List<String> typeSteps = [];
/// A list of Strings containing the steps of how to find the products of
/// this reaction.
List<String> productSteps = [];
/// A list of Strings containing the steps of how to balance this reaction.
List<String> balanceSteps = [];
/// Constructs an equation from a String.
///
/// [s] contains the reactants and optionally the products as well.
/// For example:
/// ```dart
/// Equation e = new Equation('H2O(l) + CO2(g)');
/// Equation f = new Equation('H2(g) + O2(g) => H2O(l)');
/// ```
Equation(String s) {
List<MapEntry<CompoundUnit, int>> reactants = [];
List<MapEntry<CompoundUnit, int>> products = [];
String reactantStr;
String productStr;
reactantStr = (s.contains('=>')) ? s.split('=>')[0].trim() : s;
productStr = (s.contains('=>')) ? s.split('=>')[1].trim() : null;
for (String r in reactantStr.split('+')) {
r = r.trim();
int i = 0;
while (isNumeric(r[i])) i++;
bool hasState = r[r.length - 1].compareTo(')') == 0;
int j = (hasState) ? r.length - 3 : r.length;
while (isNumeric(r[j - 1])) j--;
int number = (i != 0) ? int.parse(r.substring(0, i)) : 1;
if (Element.exists(r.substring(i, j)))
reactants.add(MapEntry(new Element(r.substring(i, j)), 1));
else
reactants.add(MapEntry(Compound(r.substring(i)), number));
}
if (productStr != null) {
for (String p in productStr.split('+')) {
p = p.trim();
int i = 0;
while (isNumeric(p[i])) i++;
bool hasState = p[p.length - 1].compareTo(')') == 0;
int j = (hasState) ? p.length - 3 : p.length;
while (isNumeric(p[j - 1])) j--;
int number = (i != 0) ? int.parse(p.substring(0, i)) : 1;
if (Element.exists(p.substring(i, j)))
products.add(MapEntry(new Element(p.substring(i, j)), 1));
else
products.add(MapEntry(Compound(p.substring(i)), number));
}
} else
products = null;
this.reactants = reactants;
this.products = products;
this.type = this.getType();
_getInWater();
}
/// Constructs an equation from the [reactants] and optionally the
/// [products].
///
/// ```dart
/// List<MapEntry<CompoundUnit, int>> reactants = [
/// MapEntry(Compound('H2O(l)'), 1),
/// MapEntry(Compound('CO2(g)'), 1)
/// ];
/// List<MapEntry<CompoundUnit, int>> products = [
/// MapEntry(Compound('H2CO3(aq)'), 1)
/// ];
/// Equation e = new Equation.fromUnits(reactants);
/// Equation f = new Equation.fromUnits(reactants, products);
/// ```
Equation.fromUnits(List<MapEntry<CompoundUnit, int>> reactants,
[List<MapEntry<CompoundUnit, int>> products]) {
this.reactants = reactants;
this.products = products;
this.type = this.getType();
_getInWater();
}
/// Finds the products of this equation and balances it based on its type.
///
/// ```dart
/// Equation e = Equation('Na3P(aq) + CaCl2(aq)');
/// e.balance();
/// print(e); // 2Na₃P(aq) + 3CaCl₂(aq) → 6NaCl + Ca₃P₂
///
/// Equation f = Equation('H2(g) + O2(g) => H2O(l)');
/// f.balance();
/// print(f); // 2H₂(g) + O₂(g) → 2H₂O(l)
/// ```
void balance() {
this.products =
(this.products == null) ? this.getProducts() : this.products;
this.productSteps.add("So, the equation (before balancing) is: $this.");
// Balancing
switch (this.type) {
case Type.comp:
// A list to keep track of the count of each reactant/product.
List<List<double>> counts = [
[1, 1],
[1]
];
// Loop through each reactant and find the counts needed to make the
// total number of each element the same on both sides.
for (int i = 0; i < 2; i++) {
counts[0][i] = this.products[0].key.compoundUnits[i].value /
this.reactants[i].key.count;
this.balanceSteps.add(
"Since the number of ${this.reactants[i].key} on the reactants side is ${this.reactants[i].key.count} and the number on the products side is ${this.products[0].key.compoundUnits[i].value}, the count of ${this.reactants[i].key.formula} will be ${counts[0][i] == counts[0][i].toInt() ? counts[0][i].toInt() : counts[0][i]}.");
}
// If the counts of the elements are not whole, multiply everything by
// 2.
while (counts[0][0] != counts[0][0].toInt()) {
counts[0][0] *= 2;
counts[0][1] *= 2;
counts[1][0] *= 2;
this.balanceSteps.add(
"Since the count of ${this.reactants[0].key} is not a whole number, we multiply the counts of both reactants and the product by 2.");
}
while (counts[0][1] != counts[0][1].toInt()) {
counts[0][0] *= 2;
counts[0][1] *= 2;
counts[1][0] *= 2;
this.balanceSteps.add(
"Since the count of ${this.reactants[1].key} is not a whole number, we multiply the counts of both reactants and the product by 2.");
}
// Set the counts of the reactants and product.
for (int i = 0; i < this.reactants.length; i++)
this.reactants[i] =
MapEntry(this.reactants[i].key, counts[0][i].toInt());
this.products[0] =
MapEntry(this.products[0].key, counts[1][0].toInt());
break;
case Type.compAcid: // No balancing required
this.balanceSteps.add(
"Since this is the composition of an acid, balancing is not required.");
break;
case Type.compBase:
// Match each water molecule to one oxygen from the metal oxide.
this.reactants[0] = MapEntry(
reactants[0].key, reactants[1].key.compoundUnits[1].value);
this.balanceSteps.add(
"In order to form the hydroxide for the base, we need to match each water molecule with one oxygen atom from the metal oxide. Since there ${this.reactants[0].value == 1 ? 'is' : 'are'} ${this.reactants[0].value} oxygen atom${this.reactants[0].value == 1 ? '' : 's'}, the count of water will also be ${this.reactants[0].value}.");
// Set the number of base molecules to be the number of molecules of
// metal in the metal oxide.
this.products[0] = MapEntry(
this.products[0].key, reactants[1].key.compoundUnits[0].value);
this.balanceSteps.add(
"In order for the count of ${this.reactants[1].key.compoundUnits[0].key.formula} (the metal) to be the same on both sides, the count of ${this.products[0].key} (the base) should be the the same as the count of ${this.reactants[1].key.compoundUnits[0].key.formula} in ${this.reactants[1].key} (the metal oxide). So, the count of ${this.products[0].key} is ${this.products[0].value}.");
break;
case Type.compSalt: // No balancing required
this.balanceSteps.add(
"Since this is the composition of a salt, balancing is not required.");
break;
case Type.decomp:
// The same method used for Simple Composition, but reversed.
List<List<double>> counts = [
[1],
[1, 1]
];
for (int i = 0; i < 2; i++) {
counts[1][i] = this.reactants[0].key.compoundUnits[i].value /
this.products[i].key.count;
this.balanceSteps.add(
"Since the number of ${this.products[i].key.formula} on the reactants side is ${this.reactants[0].key.compoundUnits[i].value} and the number on the products side is ${this.products[i].key.count}, the count of ${this.products[i].key} will be ${counts[1][i] == counts[1][i].toInt() ? counts[1][i].toInt() : counts[1][i]}.");
}
while (counts[1][0] != counts[1][0].toInt()) {
counts[0][0] *= 2;
counts[1][0] *= 2;
counts[1][1] *= 2;
this.balanceSteps.add(
"Since the count of ${this.products[0].key} is not a whole number, we multiply the counts of both reactants and the product by 2.");
}
while (counts[1][1] != counts[1][1].toInt()) {
counts[0][0] *= 2;
counts[1][0] *= 2;
counts[1][1] *= 2;
this.balanceSteps.add(
"Since the count of ${this.products[1].key} is not a whole number, we multiply the counts of both reactants and the product by 2.");
}
for (int i = 0; i < this.products.length; i++)
this.products[i] =
MapEntry(this.products[i].key, counts[1][i].toInt());
this.reactants[0] =
MapEntry(this.reactants[0].key, counts[0][0].toInt());
break;
case Type.decompAcid: // No balancing required
this.balanceSteps.add(
"Since this is the decomposition of an acid, balancing is not required.");
break;
case Type.decompBase:
// The same method used for Composition of a Base, but reversed.
this.reactants[0] = MapEntry(
this.reactants[0].key, products[1].key.compoundUnits[0].value);
this.balanceSteps.add(
"In order for the count of ${this.products[1].key.compoundUnits[0].key.formula} (the metal) to be the same on both sides, the count of ${this.reactants[0].key} (the base) should be the the same as the count of ${this.products[1].key.compoundUnits[0].key.formula} in ${this.products[1].key} (the metal oxide). So, the count of ${this.reactants[0].key} is ${this.reactants[0].value}.");
this.products[0] = MapEntry(
this.products[0].key,
reactants[0].value *
reactants[0].key.compoundUnits[1].value ~/
2);
this.balanceSteps.add(
"In order to form the hydroxide for the base, we need to match each water molecule with one oxygen atom from the metal oxide. Since there ${this.products[0].value == 1 ? 'is' : 'are'} ${this.products[0].value} oxygen atom${this.products[0].value == 1 ? '' : 's'}, the count of water will also be ${this.products[0].value}.");
break;
case Type.decompSalt: // No balancing required
this.balanceSteps.add(
"Since this is the decomposition of a salt, balancing is not required.");
break;
case Type.combustion:
// A list to keep track of the count of each reactant/product.
List<List<double>> counts = [
[1, 1],
[1, 1]
];
// Set the count of carbon dioxide to the number of carbons in the
// hydrocarbon.
counts[1][1] = reactants[0].key.compoundUnits[0].value.toDouble();
this.balanceSteps.add(
"Since there are ${counts[1][1].toInt()} carbons in ${reactants[0].key}, there will also be ${counts[1][1].toInt()} CO₂(g) molecule${counts[1][1] == 1 ? '' : 's'}. This is because each CO₂(g) molecule has 1 carbon atom.");
// Set the count of water to the number of hydrogens in the
// hydrocarbon divided by 2 since H₂O has 2 hydrogens.
counts[1][0] = (reactants[0].key.compoundUnits[1].value) / 2;
this.balanceSteps.add(
"Since there are ${reactants[0].key.compoundUnits[1].value} hydrogens in ${reactants[0].key}, there will be ${reactants[0].key.compoundUnits[1].value} / 2 = ${counts[1][0].toInt()} H₂O(g) molecule${counts[1][0] == 1 ? '' : 's'}. This is because each H₂O(g) molecule has 2 hydrogen atoms.");
// Set the count of oxygen to be the total number of oxygen in the
// products, minus the number of oxygens in the hydrocarbon, divided
// by two since there are two oxygens in O₂.
counts[0][1] =
(products[0].key.compoundUnits[1].value * counts[1][0] +
products[1].key.compoundUnits[1].value * counts[1][1])
.toDouble();
this.balanceSteps.add(
"Since there are ${products[0].key.compoundUnits[1].value} * ${counts[1][0].toInt()} + ${products[1].key.compoundUnits[1].value} * ${counts[1][1].toInt()} = ${counts[0][1].toInt()} oxygen atoms on the products side, there should be ${counts[0][1].toInt()} oxygen atoms on the reactants side.");
if (reactants[0].key.compoundUnits.length > 2) {
counts[0][1] -=
(reactants[0].key.compoundUnits[2].value * counts[0][0]);
this.balanceSteps.add(
"Since ${reactants[0].key} contains oxygen, the count of oxygen atoms in the molecules of oxygen plus the count of oxygen in ${reactants[0].key} needs to add up to the count of oxygen on the products side. In other words, the number of oxygen atoms in O₂(g) needs to be ${(products[0].key.compoundUnits[1].value * counts[1][0] + products[1].key.compoundUnits[1].value * counts[1][1]).toInt()} - ${reactants[0].key.compoundUnits[2].value} = ${counts[0][1].toInt()}.");
}
counts[0][1] /= 2;
this.balanceSteps.add(
"Because there are two oxygen atoms in each molecule of O₂(g), the count of O₂(g) should be ${(counts[0][1] * 2).toInt()} / 2 = ${counts[0][1] == counts[0][1].toInt() ? counts[0][1].toInt() : counts[0][1]}.");
// If the count of oxygen is non-whole, multiply each count by 2.
if (counts[0][1] != counts[0][1].toInt()) {
this.balanceSteps.add(
"So, the count of ${this.reactants[0].key} is ${counts[0][0].toInt()}, the count of ${this.reactants[1].key} is ${counts[0][1]}, the count of ${this.products[0].key} is ${counts[1][0].toInt()}, and the count of ${this.products[1].key} is ${counts[1][1].toInt()}.");
counts[0][0] *= 2;
counts[0][1] *= 2;
counts[1][0] *= 2;
counts[1][1] *= 2;
this.balanceSteps.add(
"Since ${counts[0][1] / 2} is not a whole number, we multiply the count of each reactant and each product by 2 so that the count of O₂(g) becomes whole.");
}
// Set the counts of each reactant and product.
reactants[0] = MapEntry(reactants[0].key, counts[0][0].toInt());
reactants[1] = MapEntry(reactants[1].key, counts[0][1].toInt());
products[0] = MapEntry(products[0].key, counts[1][0].toInt());
products[1] = MapEntry(products[1].key, counts[1][1].toInt());
break;
case Type.singleReplacement:
// 2-dimensional list to hold number of each molecule.
List<List<double>> counts = [new List(2), new List(2)];
MapEntry<CompoundUnit, int> e1 =
(reactants[0].key.isElement()) ? reactants[0] : reactants[1];
MapEntry<CompoundUnit, int> e2 = products[0];
MapEntry<CompoundUnit, int> c1 =
(reactants[0].key.isCompound()) ? reactants[0] : reactants[1];
MapEntry<CompoundUnit, int> c2 = products[1];
// The indices of the element being replaced and the one staying the same.
int rIndex = e1.key.metal ? 0 : 1;
int sIndex = 1 - rIndex;
// Find the least common multiple of the count of the element that
// stays in the compound.
int lcmCount = lcm(c1.key.compoundUnits[sIndex].value,
c2.key.compoundUnits[sIndex].value)
.abs();
this.balanceSteps.add(
"First, we need to make the number of ${c1.key.compoundUnits[sIndex].key.formula} equal on both sides. To do this, we find the least common multiple of the number of ${c1.key.compoundUnits[sIndex].key.formula} atoms on both sides. The least common multiple of ${c1.key.compoundUnits[sIndex].value} (from ${c1.key}) and ${c2.key.compoundUnits[sIndex].value} (from ${c2.key}) is $lcmCount. We then divide this number by the number of ${c1.key.compoundUnits[sIndex].key.formula} atoms in each compound to get the counts of the compounds that will make the number of ${c1.key.compoundUnits[sIndex].key.formula} atoms the same on both sides.");
int e2Count = e2.key.isElement() ? e2.key.count : 1;
// Set the count of the compound in the reactants to be the least
// common multiple divided by the count of the element that stays in
// the compound on the reactants side and on the products side.
counts[0][1] = lcmCount / c1.key.compoundUnits[sIndex].value;
// Set the count of the compound in the products to be the least
// common multiple divided by the count of the element that stays in
// the compound.
counts[1][1] = lcmCount / c2.key.compoundUnits[sIndex].value;
this.balanceSteps.add(
"So, the count of ${c1.key} should be $lcmCount / ${c1.key.compoundUnits[sIndex].value} = ${counts[0][1].toInt()} and the count of ${c2.key} should be $lcmCount / ${c2.key.compoundUnits[sIndex].value} = ${counts[1][1].toInt()}.");
this.balanceSteps.add(
"Next, we find the counts of the individual elements by dividing their count in the compound on the other side of the equation by their count as an element.");
// Set the count of the element in the reactants to be the total
// number of the element in the products side divided by the count of
// the element.
counts[0][0] = (counts[1][1] * c2.key.compoundUnits[rIndex].value) /
e1.key.count;
this.balanceSteps.add(
"Since the number of ${e1.key.formula} atoms in ${c2.key} is ${c2.key.compoundUnits[rIndex].value} and the number of ${e1.key.formula} atoms in ${e1.key} is ${e1.key.count}, the count of ${e1.key} should be (${counts[1][1].toInt()} * ${c2.key.compoundUnits[rIndex].value}) / ${e1.key.count} = ${counts[0][0] == counts[0][0].toInt() ? counts[0][0].toInt() : counts[0][0]}.");
// Set the count of the element in the products to be the total
// number of the element in the reactants side divided by the count of
// the element.
counts[1][0] =
(counts[0][1] * c1.key.compoundUnits[rIndex].value) / e2Count;
this.balanceSteps.add(
"Since the number of ${e2.key.formula} atoms in ${c1.key} is ${c1.key.compoundUnits[rIndex].value} and the number of ${e2.key.formula} atoms in ${e2.key} is $e2Count, the count of ${e2.key} should be (${counts[0][1].toInt()} * ${c1.key.compoundUnits[rIndex].value}) / $e2Count = ${counts[1][0] == counts[1][0].toInt() ? counts[1][0].toInt() : counts[1][0]}.");
// If the counts of the elements are not whole, multiply everything by
// 2.
while (counts[0][0] != counts[0][0].toInt()) {
this.balanceSteps.add(
"So, the count of ${e1.key} is ${counts[0][0]}, the count of ${c1.key} is ${counts[0][1]}, the count of ${e2.key} is ${counts[1][0] == counts[1][0].toInt() ? counts[1][0].toInt() : counts[1][0]}, and the count of ${c2.key} is ${counts[1][1].toInt()}.");
counts[0][0] *= 2;
counts[0][1] *= 2;
counts[1][0] *= 2;
counts[1][1] *= 2;
this.balanceSteps.add(
"Since ${counts[0][0] / 2} is not a whole number, we multiply the count of each reactant and each product by 2 so that the count of ${e1.key} becomes whole.");
}
while (counts[1][0] != counts[1][0].toInt()) {
this.balanceSteps.add(
"So, the count of ${e1.key} is ${counts[0][0]}, the count of ${c1.key} is ${counts[0][1].toInt()}, the count of ${e2.key} is ${counts[1][0] == counts[1][0].toInt() ? counts[1][0].toInt() : counts[1][0]}, and the count of ${c2.key} is ${counts[1][1].toInt()}.");
counts[0][0] *= 2;
counts[0][1] *= 2;
counts[1][0] *= 2;
counts[1][1] *= 2;
this.balanceSteps.add(
"Since ${counts[1][0] / 2} is not a whole number, we multiply the count of each reactant and each product by 2 so that the count of ${e2.key} becomes whole.");
}
// Set the counts of each reactant and product.
reactants[0] = MapEntry(e1.key, counts[0][0].toInt());
reactants[1] = MapEntry(c1.key, counts[0][1].toInt());
products[0] = MapEntry(e2.key, counts[1][0].toInt());
products[1] = MapEntry(c2.key, counts[1][1].toInt());
break;
case Type.doubleReplacement:
// 2-dimensional list to hold number of each molecule.
List<List<int>> counts = [
[1, 1],
[1, 1]
];
Compound r1 = reactants[0].key;
Compound r2 = reactants[1].key;
Compound p1 = products[0].key;
Compound p2 = products[1].key;
// For each element, find the count of the element on each side, then
// multiply the counts on each side in order to make the count of the
// element the same.
this.balanceSteps.add(
"In order to balance this equation, we will go through each element and find the number of atoms of the element on each side of the equation. Then, we will multiply the counts of the compounds that contain the element in such a way that the total number of atoms of the element is the same on both sides. We can do this using the following formula for each compound: new count = old count * (least common multiple / number of atoms of the element).");
// Find the least common multiple of the count of the first element on
// both sides.
int lcmCountA =
lcm(r1.compoundUnits[0].value, p1.compoundUnits[0].value).abs();
counts[0][0] *= lcmCountA ~/ r1.compoundUnits[0].value;
counts[1][0] *= lcmCountA ~/ p1.compoundUnits[0].value;
this.balanceSteps.add(
"Starting with ${r1.compoundUnits[0].key.formula}, its count in $r1 is ${r1.compoundUnits[0].value} and its count in $p1 is ${p1.compoundUnits[0].value}. The least common multiple of ${r1.compoundUnits[0].value} and ${p1.compoundUnits[0].value} is $lcmCountA. So, the count of $r1 is multiplied by $lcmCountA / ${r1.compoundUnits[0].value} = ${counts[0][0].toInt()} and the count of $p1 is multiplied by $lcmCountA / ${p1.compoundUnits[0].value} = ${counts[1][0].toInt()}. So, the new count of $r1 is 1 * ${counts[0][0].toInt()} = ${counts[0][0].toInt()} and the new count of $p1 is 1 * ${counts[1][0].toInt()} = ${counts[1][0].toInt()}.");
// Find the least common multiple of the count of the second element on
// both sides.
int lcmCountB = lcm(counts[0][0] * r1.compoundUnits[1].value,
p2.compoundUnits[1].value)
.abs();
this.balanceSteps.add(
"The count of ${r1.compoundUnits[1].key.formula} in $r1 is ${counts[0][0]} * ${r1.compoundUnits[1].value} = ${counts[0][0] * r1.compoundUnits[1].value} and its count in $p2 is 1 * ${p2.compoundUnits[1].value} = ${p2.compoundUnits[1].value}. The least common multiple of ${counts[0][0] * r1.compoundUnits[1].value} and ${p2.compoundUnits[1].value} is $lcmCountB. So, the count of $r1 is multiplied by $lcmCountB / ${counts[0][0] * r1.compoundUnits[1].value} = ${lcmCountB ~/ (counts[0][0] * r1.compoundUnits[1].value)} and the count of $p2 is multiplied by $lcmCountB / ${p2.compoundUnits[1].value} = ${lcmCountB ~/ p2.compoundUnits[1].value}. The new count of $r1 is ${counts[0][0].toInt()} * ${lcmCountB ~/ (counts[0][0] * r1.compoundUnits[1].value)} = ${counts[0][0].toInt() * lcmCountB ~/ (counts[0][0] * r1.compoundUnits[1].value)}, and the new count of $p2 is 1 * ${lcmCountB ~/ p2.compoundUnits[1].value} = ${lcmCountB ~/ p2.compoundUnits[1].value}.");
counts[0][0] *=
lcmCountB ~/ (counts[0][0] * r1.compoundUnits[1].value);
counts[1][1] *= lcmCountB ~/ p2.compoundUnits[1].value;
// Find the least common multiple of the count of the third element on
// both sides.
int lcmCountC = lcm(r2.compoundUnits[0].value,
counts[1][1] * p2.compoundUnits[0].value)
.abs();
this.balanceSteps.add(
"The count of ${r2.compoundUnits[0].key.formula} in $r2 is 1 * ${r2.compoundUnits[0].value} = ${r2.compoundUnits[0].value} and its count in $p2 is ${counts[1][1]} * ${p2.compoundUnits[0].value} = ${counts[1][1] * p2.compoundUnits[0].value}. The least common multiple of ${r2.compoundUnits[0].value} and ${counts[1][1] * p2.compoundUnits[0].value} is $lcmCountC. So, the count of $r2 is multiplied by $lcmCountC / ${r2.compoundUnits[0].value} = ${lcmCountC ~/ r2.compoundUnits[0].value} and the count of $p2 is multiplied by $lcmCountC / ${counts[1][1] * p2.compoundUnits[0].value} = ${lcmCountC ~/ (counts[1][1] * p2.compoundUnits[0].value)}. The new count of $r2 is 1 * ${lcmCountC ~/ r2.compoundUnits[0].value} = ${lcmCountC ~/ r2.compoundUnits[0].value}, and the new count of $p2 is ${counts[1][1]} * ${lcmCountC ~/ (counts[1][1] * p2.compoundUnits[0].value)} = ${lcmCountC ~/ (counts[1][1] * p2.compoundUnits[0].value)}.");
counts[0][1] *= lcmCountC ~/ r2.compoundUnits[0].value;
counts[1][1] *=
lcmCountC ~/ (counts[1][1] * p2.compoundUnits[0].value);
// Find the least common multiple of the count of the fourth element
// on both sides.
int lcmCountD = lcm(counts[0][1] * r2.compoundUnits[1].value,
counts[1][0] * p1.compoundUnits[1].value)
.abs();
this.balanceSteps.add(
"The count of ${r2.compoundUnits[1].key.formula} in $r2 is ${counts[0][1]} * ${r2.compoundUnits[1].value} = ${counts[0][1] * r2.compoundUnits[1].value} and its count in $p1 is ${counts[1][0]} * ${p1.compoundUnits[1].value} = ${counts[1][0] * p1.compoundUnits[1].value}. The least common multiple of ${counts[0][1] * r2.compoundUnits[1].value} and ${counts[1][0] * p1.compoundUnits[1].value} is $lcmCountD. So, the count of $r2 is multiplied by $lcmCountD / ${counts[0][1] * r2.compoundUnits[1].value} = ${lcmCountD ~/ (counts[0][1] * r2.compoundUnits[1].value)} and the count of $p1 is multiplied by $lcmCountD / ${counts[1][0] * p1.compoundUnits[1].value} = ${lcmCountD ~/ (counts[1][0] * p1.compoundUnits[1].value)}. The new count of $r2 is ${counts[0][1]} * ${lcmCountD ~/ (counts[0][1] * r2.compoundUnits[1].value)} = ${counts[0][1] * (lcmCountD ~/ (counts[0][1] * r2.compoundUnits[1].value))}, and the new count of $p1 is ${counts[1][0]} * ${lcmCountD ~/ (counts[1][0] * p1.compoundUnits[1].value)} = ${counts[1][0] * (lcmCountD ~/ (counts[1][0] * p1.compoundUnits[1].value))}.");
counts[0][1] *=
lcmCountD ~/ (counts[0][1] * r2.compoundUnits[1].value);
counts[1][0] *=
lcmCountD ~/ (counts[1][0] * p1.compoundUnits[1].value);
// Set the counts of each reactant and product.
reactants[0] = MapEntry(r1, counts[0][0].toInt());
reactants[1] = MapEntry(r2, counts[0][1].toInt());
products[0] = MapEntry(p1, counts[1][0].toInt());
products[1] = MapEntry(p2, counts[1][1].toInt());
_gasFormation();
break;
case Type.neutralization:
// 2-dimensional list to hold number of each molecule.
List<List<double>> counts = [new List(2), new List(2)];
Compound r1 = reactants[0].key;
Compound r2 = reactants[1].key;
Compound p1 = products[0].key;
Compound p2 = products[1].key;
int acidIndex = reactants[0].key.isAcid() ? 0 : 1;
int baseIndex = 1 - acidIndex;
Compound acid = reactants[acidIndex].key;
Compound base = reactants[baseIndex].key;
// Find the least common multiple of the charges of the nonmetal oxide
// in the acid and the charge of the metal in the base.
int lcmCharge = lcm(acid.compoundUnits[0].value,
base.compoundUnits[0].key.charge)
.abs();
this.balanceSteps.add(
"First, we balance the acid and the base by making sure that the number of H atoms and OH ions are the same on both sides. To do this, we need to make sure that the number of H atoms in $acid, the number of OH ions in $base, and the number of H₂O(l) molecules are equal to each other. To do this, we use the least common multiple of the number of H atoms and the number of OH ions.");
this.balanceSteps.add(
"The least common multiple of ${acid.compoundUnits[0].value} and ${base.compoundUnits[0].key.charge} is $lcmCharge.");
// Set the counts of the acid and base so that the charges of the
// elements in the salt will be balanced.
counts[0][acidIndex] = lcmCharge / acid.compoundUnits[0].value;
counts[0][baseIndex] = lcmCharge / base.compoundUnits[0].key.charge;
// Set the count of water so that it has the same number of hydrogens
// as the acid.
counts[1][0] = lcmCharge.toDouble();
this.balanceSteps.add(
"The count of $acid will be $lcmCharge / ${acid.compoundUnits[0].value} = ${lcmCharge ~/ acid.compoundUnits[0].value}, and the count of $base will be $lcmCharge / ${base.compoundUnits[0].key.charge} = ${lcmCharge ~/ base.compoundUnits[0].key.charge}. Since there are now $lcmCharge H atoms and $lcmCharge OH ions on the reactants side, and each molecule of H₂O(l) is made of 1 H atom and 1 OH ion, the count of H₂O(l) will also be $lcmCharge.");
// Set the count of the salt so that the count of the metal is the
// same on both sides.
counts[1][1] = (counts[0][baseIndex] * base.compoundUnits[0].value) /
p2.compoundUnits[0].value;
this.balanceSteps.add(
"We determine the count of $p2 by making sure that the number of ${p2.compoundUnits[0].key.formula} atoms is the same on both sides. Since there are ${counts[0][baseIndex].toInt()} $base molecules, and ${base.compoundUnits[0].value} ${p2.compoundUnits[0].key.formula} atom${base.compoundUnits[0].value == 1 ? '' : 's'} per molecule, there are a total of ${counts[0][baseIndex].toInt()} * ${base.compoundUnits[0].value} = ${(counts[0][baseIndex] * base.compoundUnits[0].value).toInt()} ${p2.compoundUnits[0].key.formula} atoms in the reactants. Since there are ${p2.compoundUnits[0].value} ${p2.compoundUnits[0].key.formula} atom${p2.compoundUnits[0].value == 1 ? '' : 's'} per $p2 molecule, and ${(counts[0][baseIndex] * base.compoundUnits[0].value).toInt()} ${p2.compoundUnits[0].key.formula} atom${(counts[0][baseIndex] * base.compoundUnits[0].value).toInt() == 1 ? '' : 's'}, there must be ${(counts[0][baseIndex] * base.compoundUnits[0].value).toInt()} / ${p2.compoundUnits[0].value} = ${counts[1][1].toInt()} $p2 molecule${counts[1][1] == 1 ? '' : 's'}.");
reactants[0] = MapEntry(r1, counts[0][0].toInt());
reactants[1] = MapEntry(r2, counts[0][1].toInt());
products[0] = MapEntry(p1, counts[1][0].toInt());
products[1] = MapEntry(p2, counts[1][1].toInt());
break;
}
}
/// Converts the appropriate products of this equation to gases.
/// ```
/// H₂CO₃ → H₂O(l) + CO₂(g)
/// H₂SO₃ → H₂O(l) + SO₂(g)
/// NH₄OH → H₂O(l) + NH₃(g)
/// ```
/// For example:
/// ```dart
/// Equation e = Equation('(NH4)2S(aq) + Al(OH)3(aq)');
/// e.balance();
/// print(e); // 3(NH₄)₂S(aq) + 2Al(OH)₃(aq) → 6H₂O(l) + 6NH₃(g) + Al₂S₃
/// ```
void _gasFormation() {
for (int i = 0; i < products.length; i++) {
if (products[i].key.equals('H2CO3')) {
products[i] = MapEntry(Compound('H2O(l)'), products[i].value);
products.insert(
i + 1, MapEntry(Compound('CO2(g)'), products[i].value));
this.balanceSteps.add(
"Since one of the products of this equation is H₂CO₃, it decomposes into H₂O(l) and CO₂(g). The counts of these compounds are the same as the count of H₂CO₃ in the original equation.");
} else if (products[i].key.equals('H2SO3')) {
products[i] = MapEntry(Compound('H2O(l)'), products[i].value);
products.insert(
i + 1, MapEntry(Compound('SO2(g)'), products[i].value));
this.balanceSteps.add(
"Since one of the products of this equation is H₂SO₃, it decomposes into H₂O(l) and SO₂(g). The counts of these compounds are the same as the count of H₂SO₃ in the original equation.");
} else if (products[i].key.equals('NH4OH')) {
products[i] = MapEntry(Compound('H2O(l)'), products[i].value);
products.insert(
i + 1, MapEntry(Compound('NH3(g)'), products[i].value));
this.balanceSteps.add(
"Since one of the products of this equation is NH₄OH, it decomposes into H₂O(l) and NH₃(g). The counts of these compounds are the same as the count of NH₄OH in the original equation.");
}
}
}
/// Returns the String representation of this equation with the correct
/// subscripts.
@override
String toString() {
String result = '';
for (MapEntry r in this.reactants) {
if (r.value != 1) result += r.value.toString();
result += r.key.toString();
result += ' + ';
}
result = result.substring(0, result.length - 3);
result += ' \u2192 ';
for (MapEntry p in this.products) {
if (p.value != 1) result += p.value.toString();
result += p.key.toString();
result += ' + ';
}
result = result.substring(0, result.length - 3);
return result;
}
/// Returns the products of an equation based on its [reactants] and [type].
///
/// The count of each product is 1 because the equation has not yet been
/// balanced.
/// ```dart
/// Equation e = Equation('CaO(s) + Na3P(s)');
/// print(e.getProducts()); // [MapEntry(Ca₃P₂: 1), MapEntry(Na₂O: 1)]
/// ```
List<MapEntry<CompoundUnit, int>> getProducts() {
List<MapEntry<CompoundUnit, int>> result;
switch (this.type) {
case Type.comp:
bool ionic = false;
if (reactants[0].key.metal != reactants[1].key.metal) {
this.productSteps.add(
"Since one of the reactants is a metal and the other is a nonmetal, the product of this equation is an ionic compound.");
ionic = true;
}
int count0;
int count1;
if (ionic) {
int lcmCharge =
lcm(reactants[0].key.charge, reactants[1].key.charge).abs();
count0 = lcmCharge ~/
((reactants[0].key.charge == 0) ? 1 : reactants[0].key.charge);
count1 = -lcmCharge ~/
((reactants[1].key.charge == 0) ? 1 : reactants[1].key.charge);
this.productSteps.add(
"Since the product of this equation is an ionic compound, the charges of each of its elements must add up to 0. First, we find the least common multiple of the charges of the elements. The least common multiple of ${this.reactants[0].key.charge} and ${this.reactants[1].key.charge} is $lcmCharge. ");
this.productSteps.add(
"To find the count of each element, we divide the least common multiple by the charge of each element and take the absolute value. The count of ${this.reactants[0].key.formula} is |$lcmCharge / ${this.reactants[0].key.charge}|, which equals $count0. Similarly, the count of ${this.reactants[1].key.formula} is |$lcmCharge / ${this.reactants[1].key.charge}|, which equals $count1. So, the product of this equation is: ${Compound.fromUnits([
MapEntry(reactants[0].key, count0),
MapEntry(reactants[1].key, count1),
]).toString()}. Since $count0 * ${this.reactants[0].key.charge} and $count1 * ${this.reactants[1].key.charge} add up to 0, the counts have been calculated properly.");
} else {
count0 = reactants[0].key.count;
count1 = reactants[0].key.count;
this.productSteps.add(
"Since the product of this equation is a molecular compound, and it was not given in the equation, we just assume that the product will be: ${Compound.fromUnits([
MapEntry(reactants[0].key, count0),
MapEntry(reactants[1].key, count1),
]).toString()}.");
}
result = [
MapEntry(
Compound.fromUnits([
MapEntry(reactants[0].key, count0),
MapEntry(reactants[1].key, count1),
]),
1)
];
break;
case Type.compAcid:
Compound nmOxide = Compound.fromUnits([
MapEntry(reactants[1].key.compoundUnits[0].key, 1),
MapEntry(
new Element('O'), reactants[1].key.compoundUnits[1].value + 1),
]);
result = [
MapEntry(
Compound.fromUnits([
MapEntry(new Element('H'), nmOxide.getCharge().abs()),
MapEntry(nmOxide, 1),
], Phase.aqueous),
1)
];
this.productSteps.add(
"Since the product of this equation is an acid, it will be made of H and ${reactants[1].key} with one extra oxygen from the water and the state will be aqueous. For the product to be balanced, the count of H needs to be enough for its charge and the charge of the other compound to add up to 0.");
this.productSteps.add(
"Since the charge of $nmOxide is ${nmOxide.getCharge()}, the count of H must be ${nmOxide.getCharge().abs()}. So, the product will be: ${result[0].key}.");
break;
case Type.compBase:
result = [
MapEntry(
Compound.fromUnits([
MapEntry(reactants[1].key.compoundUnits[0].key, 1),
MapEntry(Compound('OH'),
reactants[1].key.compoundUnits[0].key.charge),
]),
1)
];
this.productSteps.add(
"Since the product of this equation is a base, it will be made of ${reactants[1].key.compoundUnits[0].key.formula} and OH (hydroxide). For the product to be balanced, the count of OH needs to be enough for its charge and the charge of the other compound to add up to 0.");
this.productSteps.add(
"Since the charge of ${reactants[1].key.compoundUnits[0].key.formula} is ${reactants[1].key.compoundUnits[0].key.charge} and the charge of OH is -1, the count of OH must be ${reactants[1].key.compoundUnits[0].key.charge}. So, the product (without the state) will be: ${result[0].key}.");
break;
case Type.compSalt:
result = [
MapEntry(
Compound.fromUnits([
MapEntry(reactants[0].key.compoundUnits[0].key,
reactants[0].key.compoundUnits[0].value),
MapEntry(reactants[1].key.compoundUnits[0].key,
reactants[1].key.compoundUnits[0].value),
MapEntry(
new Element('O'),
reactants[0].key.compoundUnits[1].value +
reactants[1].key.compoundUnits[1].value),
]),
1)
];
this.productSteps.add(
"Since the product of this equation is a salt, it will be made of ${reactants[0].key.compoundUnits[0].key.formula}, ${reactants[1].key.compoundUnits[0].key.formula} (whose counts are the same as their counts in the reactants), and O (whose count is the sum of the counts of oxygen in the reactants).");
this.productSteps.add(
"So, the product (without the state) will be: ${result[0].key}.");
break;
case Type.decomp:
result = [
MapEntry(
new Element(reactants[0].key.compoundUnits[0].key.formula), 1),
MapEntry(
new Element(reactants[0].key.compoundUnits[1].key.formula), 1)
];
this.productSteps.add(
"Since this is the decomposition of a compound with 2 elements, ${reactants[0].key.compoundUnits[0].key.formula} and ${reactants[0].key.compoundUnits[1].key.formula}, the first product will be ${reactants[0].key.compoundUnits[0].key} and the second product will be ${reactants[0].key.compoundUnits[1].key}.");
break;
case Type.decompAcid:
result = [
MapEntry(Compound('H2O(l)'), 1),
MapEntry(
Compound.fromUnits([
MapEntry(
reactants[0]
.key
.compoundUnits[1]
.key
.compoundUnits[0]
.key,
reactants[0].key.compoundUnits[1].value),
MapEntry(
new Element('O'),
reactants[0]
.key
.compoundUnits[1]
.key
.compoundUnits[1]
.value -
1),
]),
1)
];
this.productSteps.add(
"Since this is the decomposition of an acid, the first product will be H₂O(l) and the second product will be a compound with ${reactants[0].key.compoundUnits[1].key.formula} and O with a count of 1 less than the count of O in the acid. So, the second product (without the state) will be ${result[1].key}.");
break;
case Type.decompBase:
int lcmCharge = lcm(reactants[0].key.compoundUnits[0].key.charge, 2);
result = [
MapEntry(Compound('H2O(l)'), 1),
MapEntry(
Compound.fromUnits([
MapEntry(
reactants[0].key.compoundUnits[0].key,
(-lcmCharge ~/
reactants[0].key.compoundUnits[0].key.charge)
.abs()),
MapEntry(new Element('O'), lcmCharge.abs() ~/ 2),
]),
1)
];
this.productSteps.add(
"Since this is the decomposition of a base, the first product will be H₂O(l) and the second product will be a compound with ${reactants[0].key.compoundUnits[0].key.formula} and O with a count of 1 less than the count of OH in the base. So, the second product (without the state) will be ${result[1].key}.");
break;
case Type.decompSalt:
Compound metalOxide = Compound.fromUnits([
MapEntry(reactants[0].key.compoundUnits[0].key,
reactants[0].key.compoundUnits[0].value),
MapEntry(
new Element('O'),
(reactants[0].key.compoundUnits[0].value *
reactants[0].key.compoundUnits[0].key.charge) ~/
2),
]);
Compound nonmetalOxide = Compound.fromUnits([
MapEntry(
reactants[0].key.compoundUnits[1].key.compoundUnits[0].key,
reactants[0].key.compoundUnits[1].key.compoundUnits[0].value),
MapEntry(
new Element('O'),
reactants[0].key.compoundUnits[1].key.compoundUnits[1].value -
metalOxide.compoundUnits[1].value),
]);
result = [MapEntry(metalOxide, 1), MapEntry(nonmetalOxide, 1)];
this.productSteps.add(
"Since this is the decomposition of a salt, the first product will be a metal oxide (the combination of the metal and oxygen) and the second product will be a nonmetal oxide (the combination of the nonmetal and oxygen).");
this.productSteps.add(
"To find the count of oxygen in the metal oxide we take the absolute value of the charge of the metal (${reactants[0].key.compoundUnits[0].key.charge}) divided by the charge of O (-2) to get ${metalOxide.compoundUnits[1].value}.");
this.productSteps.add(
"We then add the remaining oxygens to the nonmetal oxide by subtracting the count of the oxygen in the metal oxide from the count of the oxygen in the salt: ${reactants[0].key.compoundUnits[1].key.compoundUnits[1].value} - ${metalOxide.compoundUnits[1].value} = ${nonmetalOxide.compoundUnits[1].value}.");
break;
case Type.combustion:
result = [
MapEntry(Compound('H2O(g)'), 1),
MapEntry(Compound('CO2(g)'), 1)
];
this.productSteps.add(
"Since this is a hydrocarbon combustion reaction, the products will be H₂O(g) (water vapour) and CO₂(g) (carbon dioxide).");
break;
case Type.singleReplacement:
this.productSteps.add(
"Since this reaction is single replacement, the first product will be an element and the second product will be a compound. ");
int eIndex = (reactants[0].key.isElement()) ? 0 : 1;
Element e = reactants[eIndex].key;
Compound c = reactants[1 - eIndex].key;
// The indices of the element being replaced and the one staying the same.
int rIndex = e.metal ? 0 : 1;
int sIndex = 1 - rIndex;
List<int> counts = new List(2);
if (c.ionic) {
List<List<int>> charges = [
[
e.charge,
],
[
c.compoundUnits[sIndex].key.charge,
c.compoundUnits[rIndex].key.charge
]
];
int lcmCharge = lcm(charges[0][0], charges[1][0]);
counts[0] =
(lcmCharge ~/ ((charges[1][0] == 0) ? 1 : charges[1][0]))
.abs();
counts[1] =
(lcmCharge ~/ ((charges[0][0] == 0) ? 1 : charges[0][0]))
.abs();
this.productSteps.add(
"Since one reactant is an ionic compound, the product which will be a compound must also be ionic. Since ${c.compoundUnits[rIndex].key.formula} is being replaced with ${e.formula}, the ionic compound will be made of ${c.compoundUnits[sIndex].key.formula} and ${e.formula}.");
this.productSteps.add(
"To find the counts of each of the elements, we first find the least common multiple of the absolute value of the charges of the elements. In this case, the least common multiple of ${charges[1][0].abs()} and ${charges[0][0].abs()} is $lcmCharge.");
this.productSteps.add(
"We then divide this number by the absolute value of the charge of each element to find the count of each element. So, the count of ${c.compoundUnits[sIndex].key.formula} is $lcmCharge / ${charges[1][0].abs()} = ${counts[0]}. Similarly, the count of ${e.formula} is $lcmCharge / ${charges[0][0].abs()} = ${counts[1]}.");
this.productSteps.add(
"As a result, the charges of each element multiplied by their counts now sum to 0.");
} else {
counts[0] = c.compoundUnits[0].key.count;
counts[1] = e.count;
this.productSteps.add(
"Since one reactant is a molecular compound, the product which will be a compound must also be molecular. As a result, the charges do not need to be balanced.");
this.productSteps.add(
"So, we assume that the count of ${c.compoundUnits[1].key.formula} is ${c.compoundUnits[1].value} and the count of ${e.formula} is ${e.count}.");
}
if (e.metal) {
result = [
MapEntry(c.compoundUnits[rIndex].key, 1),
MapEntry(
Compound.fromUnits([
MapEntry(e, counts[1]),
MapEntry(c.compoundUnits[sIndex].key, counts[0])
]),
1)
];
} else {
result = [
MapEntry(c.compoundUnits[rIndex].key, 1),
MapEntry(
Compound.fromUnits([
MapEntry(c.compoundUnits[sIndex].key, counts[0]),
MapEntry(e, counts[1]),
]),
1)
];
}
this.productSteps.add(
"As a result, the first product is ${result[0].key} and the second product (without the state) is ${result[1].key}.");
break;
case Type.doubleReplacement:
List<List<int>> counts = [new List(2), new List(2)];
List<List<int>> charges = [
[
reactants[0].key.compoundUnits[0].key.charge,
reactants[0].key.compoundUnits[1].key.charge
],
[
reactants[1].key.compoundUnits[0].key.charge,
reactants[1].key.compoundUnits[1].key.charge
]
];
if (reactants[0].key.ionic && reactants[1].key.ionic) {
int lcmCharge1 = lcm(charges[0][0], charges[1][1]).abs();
int lcmCharge2 = lcm(charges[1][0], charges[0][1]).abs();
counts[0][0] =
lcmCharge1 ~/ ((charges[0][0] == 0) ? 1 : charges[0][0]);
counts[0][1] =
-lcmCharge1 ~/ ((charges[1][1] == 0) ? 1 : charges[1][1]);
counts[1][0] =
lcmCharge2 ~/ ((charges[1][0] == 0) ? 1 : charges[1][0]);
counts[1][1] =
-lcmCharge2 ~/ ((charges[0][1] == 0) ? 1 : charges[0][1]);
this.productSteps.add(
"Since the reactants are ionic, the products will also be ionic. The first product will be made of ${reactants[0].key.compoundUnits[0].key.formula} and ${reactants[1].key.compoundUnits[1].key.formula} and the second product will be made of ${reactants[1].key.compoundUnits[0].key.formula} and ${reactants[0].key.compoundUnits[1].key.formula}.");
this.productSteps.add(
"To find the counts of the first product, we find the least common multiple of the absolute values of the charges of ${reactants[0].key.compoundUnits[0].key.formula} and ${reactants[1].key.compoundUnits[1].key.formula}. The least common multiple of ${reactants[0].key.compoundUnits[0].key.charge.abs()} and ${reactants[1].key.compoundUnits[1].key.charge.abs()} is $lcmCharge1.");
this.productSteps.add(
"We then divide the least common multiple by the charges of ${reactants[0].key.compoundUnits[0].key.formula} and ${reactants[1].key.compoundUnits[1].key.formula} and then take the absolute value to get their counts. The count of ${reactants[0].key.compoundUnits[0].key.formula} is |$lcmCharge1 / ${reactants[0].key.compoundUnits[0].key.charge}| = ${counts[0][0]}. Similarly, the count of ${reactants[1].key.compoundUnits[1].key.formula} is |$lcmCharge1 / ${reactants[1].key.compoundUnits[1].key.charge}| = ${counts[0][1]}.");
this.productSteps.add(
"Similarly for the second product, we find that the least common multiple of the absolute values of the charges of ${reactants[1].key.compoundUnits[0].key.formula} and ${reactants[0].key.compoundUnits[1].key.formula} is $lcmCharge2.");
this.productSteps.add(
"Again, we divide the least common multiple by the charges of ${reactants[1].key.compoundUnits[0].key.formula} and ${reactants[0].key.compoundUnits[1].key.formula} and then take the absolute value. The count of ${reactants[1].key.compoundUnits[0].key.formula} is |$lcmCharge2 / ${reactants[1].key.compoundUnits[0].key.charge}| = ${counts[1][0]}. Similarly, the count of ${reactants[0].key.compoundUnits[1].key.formula} is |$lcmCharge2 / ${reactants[0].key.compoundUnits[1].key.charge}| = ${counts[1][1]}.");
this.productSteps.add(
"Using this method, we can ensure that the charges of the anion and the cation in each ionic compound sum to 0.");
} else {
counts[0] = [
reactants[0].key.compoundUnits[0].value,
reactants[0].key.compoundUnits[1].value
];
counts[1] = [
reactants[1].key.compoundUnits[0].value,
reactants[1].key.compoundUnits[1].value
];
this.productSteps.add(
"Since the reactants are molecular compounds, the products will also be molecular compounds. We assume that the counts of each element will stay the same as they were before the reaction.");
}
result = [
MapEntry(
Compound.fromUnits([
MapEntry(
reactants[0].key.compoundUnits[0].key, counts[0][0]),
MapEntry(
reactants[1].key.compoundUnits[1].key, counts[0][1]),
]),
1),
MapEntry(
Compound.fromUnits([
MapEntry(
reactants[1].key.compoundUnits[0].key, counts[1][0]),
MapEntry(
reactants[0].key.compoundUnits[1].key, counts[1][1]),
]),
1),
];
this.productSteps.add(
"As a result, the first product (without the state) is ${result[0].key} and the second product (without the state) is ${result[1].key}.");
break;
case Type.neutralization:
Compound acid =
reactants[0].key.isAcid() ? reactants[0].key : reactants[1].key;
Compound base =
reactants[0].key.isBase() ? reactants[0].key : reactants[1].key;
int otherCharge =
acid.compoundUnits[0].value ~/ acid.compoundUnits[1].value;
int lcmCharge =
lcm(otherCharge, base.compoundUnits[0].key.charge).abs();
result = [
MapEntry(Compound('H2O(l)'), 1),
MapEntry(
Compound.fromUnits([
MapEntry(base.compoundUnits[0].key,
lcmCharge ~/ base.compoundUnits[0].key.charge),
MapEntry(
acid.compoundUnits[1].key, lcmCharge ~/ otherCharge),
]),
1),
];
this.productSteps.add(
"Since this is a neutralization reaction, the first product will be H₂O(l) and the second product will be the combination of the cation of the base (${base.compoundUnits[0].key.formula}) and the anion from the acid (${acid.compoundUnits[1].key.formula}).");
this.productSteps.add(
"Since the second product will be ionic, we must calculate the least common multiple of the absolute values of the charges of ${base.compoundUnits[0].key.formula} and ${acid.compoundUnits[1].key.formula}. The least common multiple of ${base.compoundUnits[0].key.charge} and $otherCharge is $lcmCharge.");
this.productSteps.add(
"We then divide the least common multiple by the charges of the cation and anion, then take the absolute value to find the counts. The count of ${base.compoundUnits[0].key.formula} will be |$lcmCharge / ${base.compoundUnits[0].key.charge}| = ${result[1].key.compoundUnits[0].value}. Similarly, the count of ${acid.compoundUnits[1].key.formula} will be |$lcmCharge / ${acid.compoundUnits[1].key.charge}| = ${result[1].key.compoundUnits[1].value}.");
this.productSteps.add(
"As a result, the first product is H₂O(l) and the second product (without the state) is ${result[1].key}.");
}
result = _getStates(result);
return result;
}
/// Returns the type of an equation based on its [reactants].
///
/// ```dart
/// Equation e = Equation('H2(g) + O2(g) => H2O(l)');
/// print(e.getType()); // Type.comp
/// ```
Type getType() {
_fixPolyatomicIons();
if (reactants.length == 1) {
// Decomposition
if (reactants[0].key.isElement()) return null;
if (reactants[0].key.compoundUnits.length == 2 &&
reactants[0].key.compoundUnits[0].key.isElement() &&
reactants[0].key.compoundUnits[1].key.isElement()) {
typeSteps.add(
"Since this equation has one reactant with two elements, it must be Simple Decomposition.");
return Type.decomp;
}
if (reactants[0].key.isAcid()) {
typeSteps.add(
"Since this equation has one reactant which is an acid, it must be Decomposition of an Acid.");
return Type.decompAcid;
} else if (reactants[0].key.compoundUnits[0].key.metal) {
if (reactants[0].key.compoundUnits[1].key.equals('OH')) {
typeSteps.add(
"Since this equation has one reactant which is a base, it must be Decomposition of a Base.");
return Type.decompBase;
}
if (!reactants[0]
.key
.compoundUnits[1]
.key
.compoundUnits[0]
.key
.metal) {
if (reactants[0]
.key
.compoundUnits[1]
.key
.compoundUnits[1]
.key
.equals('O')) {
typeSteps.add(
"Since this equation has one reactant which is a combination of a metal, nonmetal, and oxygen, it must be Decomposition of a Salt.");
return Type.decompSalt;
}
}
}
}
if (reactants[0].key.isElement() && reactants[1].key.isElement()) {
typeSteps.add(
"Since this equation has two reactants, each of which are elements, it must be Simple Composition.");
return Type.comp; // Simple Composition
} else if (reactants[0].key.isCompound() &&
reactants[1].key.isElement() &&
reactants[0].key.compoundUnits[0].key.equals('C') &&
reactants[0].key.compoundUnits[1].key.equals('H') &&
reactants[1].key.equals('O')) {
typeSteps.add(
"Since this equation has two reactants, one of which has carbon and hydrogen, and the other of which is oxygen, it must be Hydrocarbon Combustion.");
return Type.combustion; // Hydrocarbon Combustion
} else if ((reactants[0].key.isElement() &&
reactants[1].key.isCompound()) ||
(reactants[0].key.isCompound() && reactants[1].key.isElement())) {
typeSteps.add(
"Since this equation has two reactants, one of which is an element and one of which is a compound, it must be Single Replacement.");
return Type.singleReplacement;
} else if (reactants[0].key.isAcid() && reactants[1].key.isBase() ||
reactants[0].key.isBase() && reactants[1].key.isAcid()) {
typeSteps.add(
"Since this equation has two reactants, one of which is an acid and the other of which is a base, it must be Double Replacement (Neutralization).");
return Type.neutralization;
} else if (reactants[0].key.isCompound() &&
reactants[1].key.isCompound()) {
if (reactants[0].key.formula.compareTo('H2O(l)') == 0) {
if (reactants[1].key.compoundUnits[1].key.equals('O')) {
if (!reactants[1].key.compoundUnits[0].key.metal) {
typeSteps.add(
"Since this equation has two reactants, one of which is water and the other of which is the combination of a nonmetal and oxygen (making it a nonmetal oxide), it must be Composition of an Acid.");
return Type.compAcid;
}
typeSteps.add(
"Since this equation has two reactants, one of which is water and the other of which is the combination of a metal and oxygen (making it a metal oxide), it must be Composition of a Base.");
return Type.compBase;
}
} else if (reactants[0].key.compoundUnits[1].key.equals('O') &&
reactants[1].key.compoundUnits[1].key.equals('O')) {
typeSteps.add(
"Since this equation has two reactants, one of which is the combination of metal and oxygen (making it a metal oxide) and the other of which is the combination of a nonmetal and oxygen (making it a nonmetal oxide), it must be Composition of a Salt.");
return Type.compSalt;
}
typeSteps.add(
"Since this equation has two reactants, both of which are compounds, it must be Double Replacement.");
return Type.doubleReplacement;
}
return null;
}
/// Updates this equation's properties based on whether or not its reactants
/// and products are in water.
void _getInWater() {
this.rInWater = [
Type.decompBase,
Type.decompSalt,
Type.singleReplacement,
Type.doubleReplacement,
Type.neutralization
].contains(this.type);
this.pInWater = [
Type.compBase,
Type.compSalt,
Type.singleReplacement,
Type.doubleReplacement,
Type.neutralization
].contains(this.type);
}
/// Updates each reactant and product's state based on [rInWater] and
/// [pInWater].
List<MapEntry<CompoundUnit, int>> _getStates(
List<MapEntry<CompoundUnit, int>> products) {
if (this.rInWater) {
List<Compound> ionicReactants = this
.reactants
.map((r) => r.key)
.where((cu) => (cu.isCompound() && cu.ionic))
.map((cu) => cu.toCompound())
.toList();
if (ionicReactants.length > 0)
this.productSteps.add(
"Since the type of this equation is ${typeToString[this.type]}, the reactants are in water.");
this.reactants.forEach((r) {
if (r.key.isCompound() && r.key.ionic) {
Compound c = r.key.toCompound().withoutState();
this.productSteps.add(
"Since $c is ionic and one of the reactants of this equation, we need to check the solubility chart for its state.");
r.key.state = c.getWaterState();
this.productSteps.add(
"From the solubility chart, we can see that the state of $c should be ${phaseToString[r.key.state]}.");
}
});
} else {
this.productSteps.add(
"Since the type of this equation is ${typeToString[this.type]}, the reactants are not in water; so, each of the ionic reactants must be solid.");
for (Compound c in reactants
.map((r) => r.key)
.where((cu) => (cu.isCompound() && cu.ionic)))
c.state = Phase.solid;
}
if (this.pInWater) {
List<Compound> ionicProducts = products
.map((p) => p.key)
.where((cu) => (cu.isCompound() && cu.ionic))
.map((cu) => cu.toCompound())
.toList();
if (ionicProducts.length > 0)
this.productSteps.add(
"Since the type of this equation is ${typeToString[this.type]}, the products are in water.");
products.forEach((p) {
if (p.key.isCompound() && p.key.ionic) {
Compound c = p.key.toCompound().withoutState();
this.productSteps.add(
"Since $c is ionic and one of the products of this equation, we need to check the solubility chart for its state.");
p.key.state = c.getWaterState();
this.productSteps.add(
"From the solubility chart, we can see that the state of $c should be ${phaseToString[p.key.state]}.");
}
});
} else {
this.productSteps.add(
"Since the type of this equation is ${typeToString[this.type]}, the products are not in water; so, each of the ionic products must be solid.");
for (Compound c in products
.map((p) => p.key)
.where((cu) => (cu.isCompound() && cu.ionic)))
c.state = Phase.solid;
}
return products;
}
/// Creates a separate compound unit for each polyatomic ion of the
/// reactants at the [indices].
///
/// ```dart
/// Compound([MapEntry(N: 1), MapEntry(H: 3)])
/// → Compound([MapEntry(NH₃: 1)])
/// ```
void _fixPolyatomicIons() {
for (int i = 0; i < reactants.length; i++) {
MapEntry<CompoundUnit, int> r = reactants[i];
if (r.key.isCompound() && r.key.compoundUnits.length > 2) {
if (r.key.compoundUnits[0].key.equals('N') &&
r.key.compoundUnits[0].value == 1 &&
r.key.compoundUnits[1].key.equals('H') &&
r.key.compoundUnits[1].value == 4) {
reactants[i] = MapEntry(
Compound.fromUnits([
MapEntry(Compound('NH4'), 1),
MapEntry(
Compound.fromUnits(r.key.compoundUnits.sublist(2)), 1)
], r.key.state),
1);
r = reactants[i];
}
if (r.key.compoundUnits.length > 2 &&
!(r.key.compoundUnits[0].key.equals('C') &&
r.key.compoundUnits[1].key.equals('H') &&
r.key.compoundUnits[2].key.equals('O')))
reactants[i] = MapEntry(
Compound.fromUnits([
MapEntry(r.key.compoundUnits[0].key,
r.key.compoundUnits[0].value),
MapEntry(
Compound.fromUnits(r.key.compoundUnits.sublist(1)), 1)
], r.key.state),
1);
}
}
}
/// Returns the formatted explanation of how to find the type and product(s)
/// of this equation as well as how to balance it.
String getExplanation() {
String result = 'Type\n';
result += this.typeSteps.join('\n');
result += '\n\nProduct(s)\n';
result += this.productSteps.join('\n');
result += '\n\nBalancing\n';
result += this.balanceSteps.join('\n');
result += '\n\nSo, the final equation after balancing is:';
result += '\n$this';
return result;
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib/chemistry | mirrored_repositories/chemfriend-mobile/lib/chemistry/src/element.dart | part of chemistry;
/// A class representing a chemical element.
class Element extends ChemicalElement with CompoundUnit {
/// The state of this element.
Phase state;
/// A Boolean value that represents whether or not this element is a metal.
bool metal;
/// The charge of this element.
int charge;
/// The number of atoms this element needs to have in order to be stable.
int count;
/// The number of this element in the periodic table.
int number;
/// Constructs an element with the symbol [symbol] and charge [_charge].
///
/// ```dart
/// Element e = new Element('Ca');
/// Element f = new Element('Fe', 3);
/// ```
Element(String symbol, [int _charge]) {
for (ChemicalElement e in periodicTable) {
if (e.symbol.compareTo(symbol) == 0) {
this.name = e.name;
this.formula = e.symbol;
this.category = e.category;
this.state = mPhaseToPhase[e.stpPhase];
this.number = e.number;
this.shells = e.shells;
break;
}
}
if (this.category.contains('metal'))
this.metal = !(this.category.contains('nonmetal'));
else
this.metal = false;
if (this.category.contains('diatomic'))
this.count = 2;
else if (this.formula.compareTo('P') == 0)
this.count = 4;
else if (this.formula.compareTo('S') == 0)
this.count = 8;
else
this.count = 1;
if (this.equals('H'))
this.charge = 1;
else if (_charge == null) {
int valence = this.shells[this.shells.length - 1];
if (valence < 5)
this.charge = valence;
else
this.charge = valence - 8;
} else
this.charge = _charge;
}
/// Returns the String representation of this element.
@override
String toString() {
String result = this.formula;
if (this.count != 1) result += changeScript[this.count.toString()][1];
result += phaseToString[this.state];
return result;
}
/// Returns `true` if this element's formula is [symbol].
///
/// ```dart
/// Element e = new Element('H');
/// print(e.equals('H')); // true
/// print(e.equals('Ca')); // false
/// ```
@override
bool equals(String symbol) {
String ionFormula = this.formula;
if (this.charge != null &&
(symbol.contains('+') || symbol.contains('-'))) {
if (this.charge.abs() > 1) ionFormula += this.charge.abs().toString();
if (this.charge != 0) ionFormula += (this.charge > 0) ? '+' : '-';
}
return ionFormula.compareTo(symbol) == 0;
}
/// Returns the name of this element.
String getName() {
return this.name;
}
/// Returns `true` if an element with the symbol [symbol] exists.
///
/// ```dart
/// print(Element.exists('Na')); // true
/// print(Element.exists('Rr')); // false
/// ```
static bool exists(String symbol) {
for (ChemicalElement e in periodicTable) {
if (e.symbol.compareTo(symbol) == 0) return true;
}
return false;
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib/chemistry | mirrored_repositories/chemfriend-mobile/lib/chemistry/src/compound_unit.dart | part of chemistry;
/// A class that represents one unit of a chemical compound.
///
/// This can either be an element or another compound.
abstract class CompoundUnit {
String formula;
String category;
String name;
bool metal;
int count;
int charge;
bool ionic;
List<int> shells;
List<MapEntry<CompoundUnit, int>> compoundUnits;
Phase state;
/// Returns `true` if this unit has the formula or symbol [s].
bool equals(String s);
/// Returns `true` if this unit is an element.
bool isElement() {
return this.runtimeType == Element;
}
/// Returns `true` if this unit is a compound.
bool isCompound() {
return this.runtimeType == Compound;
}
/// Returns the element with the same properties as this unit.
Element toElement() {
return new Element(this.formula);
}
/// Returns the compound with the same properties as this unit.
Compound toCompound() {
return new Compound.fromUnits(this.compoundUnits, this.state);
}
/// Returns `true` if this unit is an acid.
///
/// Checks if the first element is `H` and the phase is `Phase.aqueous`.
bool isAcid() {
return this.isCompound() && this.isAcid();
}
/// Returns `true` is this unit is a base.
///
/// Checks is this is ammonia (`NH3`), or is ionic and contains hydroxide
/// (`OH`) or carbonate (`CO3`).
bool isBase() {
return this.isCompound() && this.isBase();
}
/// Returns the charge of this unit.
///
/// ```dart
/// Compound c = new Compound('SO4');
/// print(c.getCharge()); // -2
///
/// Element e = Element.from('Na');
/// print(e.getCharge()); // 1
/// ```
int getCharge() {
if (this.equals('H')) return 1;
if (this.isElement() &&
this.category.compareTo('transition metal') != 0) {
int valence = this.shells[this.shells.length - 1];
if (valence < 5) return valence;
return valence - 8;
}
return this.charge;
}
}
| 0 |
mirrored_repositories/chemfriend-mobile/lib/chemistry | mirrored_repositories/chemfriend-mobile/lib/chemistry/src/common_ions.dart | part of chemistry;
/// A Map of the common polyatomic ions to their charges.
final Map<String, int> commonIons = {
'CH3COO': -1,
'NH4': 1,
'C6H5COO': -1,
'BO3': -3,
'C2': -2,
'CO3': -2,
'HCO3': -1,
'ClO4': -1,
'ClO3': -1,
'ClO2': -1,
'OCl': -1,
'ClO': -1,
'CrO4': -2,
'Cr2O7': -2,
'CN': -1,
'OH': -1,
'IO3': -1,
'NO3': -1,
'NO2': -1,
'OOCCOO': -2,
'HOOCCOO': -1,
'MnO4': -1,
'O2': -2,
'S2': -2,
'PO4': -3,
'HPO4': -2,
'H2PO4': -1,
'SiO3': -2,
'SO4': -2,
'HSO4': -1,
'SO3': -2,
'HSO3': -1,
'HS': -1,
'SCN': -1,
'S2O3': -2,
};
| 0 |
mirrored_repositories/chemfriend-mobile | mirrored_repositories/chemfriend-mobile/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:chemfriend/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/chemfriend-mobile | mirrored_repositories/chemfriend-mobile/test/chemistry_test.dart | import 'package:chemfriend/chemistry/chemistry.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('Element', () {
test('.getName() returns the name', () {
Element e = new Element('O');
expect(e.getName(), equals('Oxygen'));
});
test('.toString() returns the subscripted name', () {
Element e = new Element('S');
expect(e.toString(), equals('S₈(s)'));
});
test('.equals() returns equality to another element', () {
Element e = new Element('Mn');
expect(e.equals('Mn'), equals(true));
});
test('.getCharge() returns the charge', () {
Element e = new Element('Al');
expect(e.getCharge(), equals(e.charge));
});
});
group('Compound', () {
test('.isCompound() returns true', () {
Compound c = Compound('H2O');
expect(c.isCompound(), equals(true));
});
test('.toString() returns the subscripted name', () {
Compound c = Compound('C6H12O6(s)');
expect(c.toString(), equals('C₆H₁₂O₆(s)'));
});
test('.equals() returns equality to another compound', () {
Compound c = Compound('Al2O3(s)');
expect(c.equals('Al2O3(s)'), equals(true));
});
test('.getCharge() returns the charge', () {
Compound c = Compound('NO3');
expect(c.getCharge(), equals(-1));
});
});
group('Equation', () {
test('constructor works regardless of indentation', () {
Equation e = Equation('H2(g) +O2(g) => H2O(l)\n ');
expect(e.toString(), equals('H₂(g) + O₂(g) → H₂O(l)'));
});
test('constructor gives correct states for multivalent elements', () {
Equation e = Equation('FeF3 + CaCl2(aq)');
Equation f = Equation('FeF2 + CaCl2(aq)');
e.balance();
f.balance();
List<Phase> states = [
e.reactants[0].key.state,
f.reactants[0].key.state
];
expect(states, equals([Phase.aqueous, Phase.solid]));
});
test('.balance() works correctly for simple composition', () {
Equation e = Equation('H2(g) + O2(g)');
e.balance();
expect(e.toString(), equals('H₂(g) + O₂(g) → H₂O₂'));
});
test('.balance() works correctly for composition of an acid', () {
Equation e = Equation('H2O(l) + CO2(g)');
e.balance();
expect(e.toString(), equals('H₂O(l) + CO₂(g) → H₂CO₃(aq)'));
});
test('.balance() works correctly for composition of a base', () {
Equation e = Equation('H2O(l) + Na2O(aq)');
e.balance();
expect(e.toString(), equals('H₂O(l) + Na₂O(s) → 2NaOH(aq)'));
});
test('.balance() works correctly for simple decomposition', () {
Equation e = Equation('H2O2(l)');
e.balance();
expect(e.toString(), equals('H₂O₂(l) → H₂(g) + O₂(g)'));
});
test('.balance() works correctly for decomposition of an acid', () {
Equation e = Equation('H2CO3(aq)');
e.balance();
expect(e.toString(), equals('H₂CO₃(aq) → H₂O(l) + CO₂'));
});
test('.balance() works correctly for decomposition of a base', () {
Equation e = Equation('NaOH(aq)');
e.balance();
expect(e.toString(), equals('2NaOH(aq) → H₂O(l) + Na₂O(s)'));
});
test('.balance() works correctly for combustion', () {
Equation e = Equation('C6H12O6(s) + O2(g)');
e.balance();
expect(
e.toString(), equals('C₆H₁₂O₆(s) + 6O₂(g) → 6H₂O(g) + 6CO₂(g)'));
});
test('.balance() works correctly for single replacement of nonmetal',
() {
Equation e = Equation('S8(s) + GaF3(s)');
e.balance();
expect(
e.toString(), equals('3S₈(s) + 16GaF₃(aq) → 24F₂(g) + 8Ga₂S₃(s)'));
});
test('.balance() works correctly for single replacement of metal', () {
Equation e = Equation('Na(s) + GaF3(s)');
e.balance();
expect(e.toString(), equals('3Na(s) + GaF₃(aq) → Ga(s) + 3NaF(aq)'));
});
test(
'.balance() works correctly for single replacement with different order',
() {
Equation e = Equation('GaF3(s) + Na(s)');
e.balance();
expect(e.toString(), equals('3Na(s) + GaF₃(aq) → Ga(s) + 3NaF(aq)'));
});
test('.balance() works correctly for double replacement', () {
Equation e = Equation('Na3P(aq) + CaCl2(aq)');
e.balance();
expect(e.toString(),
equals('2Na₃P(aq) + 3CaCl₂(aq) → 6NaCl(aq) + Ca₃P₂(s)'));
});
test(
'.balance() works correctly for double replacement of polyatomic ions',
() {
Equation e = Equation('NH4NO3(aq) + CaSO3(aq)');
e.balance();
expect(e.toString(),
equals('2NH₄NO₃(aq) + CaSO₃(s) → (NH₄)₂SO₃(aq) + Ca(NO₃)₂(aq)'));
});
test(
'.balance() works correctly for double replacement with coinciding charges',
() {
Equation e = Equation('Na2O(aq) + CaF2(s)');
e.balance();
expect(e.toString(), equals('Na₂O(aq) + CaF₂(s) → 2NaF(aq) + CaO(s)'));
});
test('.balance() works correctly for neutralization', () {
Equation e = Equation('H2CO3(aq) + Al(OH)3(aq)');
e.balance();
expect(e.toString(),
equals('3H₂CO₃(aq) + 2Al(OH)₃(s) → 6H₂O(l) + Al₂(CO₃)₃(s)'));
});
test('.balance() works correctly for gas formation', () {
Equation e = Equation('(NH4)2S(aq) + Al(OH)3(aq)');
e.balance();
expect(
e.toString(),
equals(
'3(NH₄)₂S(aq) + 2Al(OH)₃(s) → 6H₂O(l) + 6NH₃(g) + Al₂S₃(s)'));
});
});
}
| 0 |
mirrored_repositories/chemfriend-mobile | mirrored_repositories/chemfriend-mobile/test/explanation_test.dart | import 'package:chemfriend/chemistry/chemistry.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Equation.getExplanation() works for simple composition', () {
Equation e = new Equation('Na(s) + O2(g)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works for composition of an acid', () {
Equation e = new Equation('H2O(l) + CO2(g)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works for composition of a base', () {
Equation e = new Equation('H2O(l) + Al2O3(s)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works for composition of a salt', () {
Equation e = new Equation('Al2O3(s) + CO2(g)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works for simple decomposition', () {
Equation e = new Equation('Na2O(s)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works for decomposition of an acid', () {
Equation e = new Equation('H2CO3(aq)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works for decomposition of a base', () {
Equation e = new Equation('NaOH(aq)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works for decomposition of a salt', () {
Equation e = new Equation('MgCO3(aq)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works for combustion', () {
Equation e = new Equation('C4H10(s) + O2(g)');
e.balance();
print(e.getExplanation());
});
test(
'Equation.getExplanation() works correctly for single replacement of metal',
() {
Equation e = Equation('Ga(s) + Ca3P2(s)');
e.balance();
print(e.getExplanation());
});
test(
'Equation.getExplanation() works correctly for single replacement of nonmetal',
() {
Equation e = Equation('S8(s) + Ga(OH)3(s)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works correctly for double replacement',
() {
Equation e = Equation('Na3P(aq) + CaCl2(aq)');
e.balance();
print(e.getExplanation());
});
test(
'Equation.getExplanation() works correctly for double replacement with coinciding charges',
() {
Equation e = Equation('Na2O + CaF2');
e.balance();
print(e.getExplanation());
});
test(
'Equation.getExplanation() works correctly for double replacement of polyatomic ions',
() {
Equation e = Equation('NH4NO3(aq) + CaSO3(aq)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works correctly for neutralization', () {
Equation e = Equation('H2OOCCOO(aq) + NaOH(aq)');
e.balance();
print(e.getExplanation());
});
test('Equation.getExplanation() works correctly for gas formation', () {
Equation e = Equation('(NH4)2S(aq) + Al(OH)3(aq)');
e.balance();
print(e.getExplanation());
});
}
| 0 |
mirrored_repositories/text_search_field | mirrored_repositories/text_search_field/lib/text_search_field.dart | export 'src/text_search_field.dart';
export 'src/text_search_field_data_model.dart';
export 'src/text_search_field_controller.dart';
export 'src/Utils.dart';
| 0 |
mirrored_repositories/text_search_field/lib | mirrored_repositories/text_search_field/lib/src/text_search_field_data_model.dart | class TextSearchFieldDataModel {
String? key;
String? value;
TextSearchFieldDataModel({this.key, this.value});
}
| 0 |
mirrored_repositories/text_search_field/lib | mirrored_repositories/text_search_field/lib/src/text_search_field_controller.dart | import 'package:text_search_field/src/text_search_field_data_model.dart';
class TextSearchFieldController {
String text;
bool isLoading;
void Function(TextSearchFieldDataModel model)? selected;
TextSearchFieldController(
{this.text = "", this.isLoading = false, this.selected});
}
| 0 |
mirrored_repositories/text_search_field/lib | mirrored_repositories/text_search_field/lib/src/Utils.dart | class Utils {
/// this function is going to build and return key from [text]
static String buildKey(String text) {
return text.replaceAll(" ", "").toLowerCase();
}
}
| 0 |
mirrored_repositories/text_search_field/lib | mirrored_repositories/text_search_field/lib/src/text_search_field.dart | import 'package:flutter/material.dart';
import 'package:text_search_field/src/Utils.dart';
import 'package:text_search_field/src/text_search_field_controller.dart';
import 'package:text_search_field/src/text_search_field_data_model.dart';
import 'package:touch_ripple_effect/touch_ripple_effect.dart';
import 'global_key.dart';
/// this is a search for searching or filtering item from list, server or network
/// [hint] is a string to show hint to user in textSearchField,
/// using [inputBorder] you can change your textSearchField broder colors and style,
/// with [searchFieldTextStyle] you can change input text style of textSearchField,
/// and with [searchFieldHintTextStyle] you will be able to change hint text style,
/// if you want to add default or initial value to textSearchField you will able to do it with [initialValue],
/// you can add predefine list for filter in the search field using [filterItems],
/// if you want to enable [fullTextSearch] on default filter you can do it by enable this,
/// if you want to change keyboard input type or submit button then you will be able to do it by [textInputAction],
/// if you want to handle filter or search from the server then you will be able to do it using [fetch],
/// with [query] you can added custom filter code on predefined list,
/// you can change suggestion item touch ripple colors with [rippleColor],
/// whenever user will press submit button or they will touch suggestion item then [onSelected] method is going to trigger
/// with [controller] you will be able to add dependency and able to handle textSearchField widget
/// with [dependency] you can declare dependency on other textSearchField
/// if searchFiled has dependency on other searchFiled then after fetching initial searchFiled this [dependencyFetch] method is going to trigger
/// you can change text style with [suggestionTextStyle]
/// you you want to style your suggestion item you can do with [suggestionItemDecoration]
/// you can define height of suggestion item with [suggestionItemContainerHeight]
/// you can add alignment of text with [suggestionTextAlignment]
/// with [suggestionContainerHeight] you can define suggestion height
/// with [caseSensitive] you can enable and disable case sensitive of default query filter
///
class TextSearchField extends StatefulWidget {
final String? hint;
final InputBorder? inputBorder;
final TextStyle? searchFieldTextStyle;
final TextStyle? searchFieldHintTextStyle;
final TextSearchFieldDataModel? initialValue;
final List<TextSearchFieldDataModel>? filterItems;
final bool fullTextSearch;
final TextInputAction? textInputAction;
final Future<List<TextSearchFieldDataModel>?> Function(String query)? fetch;
final List<TextSearchFieldDataModel>? Function(
List<TextSearchFieldDataModel>? filterItems, String query)? query;
final Color? rippleColor;
final Future<void> Function(
bool isPrimary, int index, TextSearchFieldDataModel selectedItem)?
onSelected;
final TextSearchFieldController? controller;
final TextSearchFieldController? dependency;
final Future<List<TextSearchFieldDataModel>> Function(
TextSearchFieldDataModel modelItem)? dependencyFetch;
final TextStyle? suggestionTextStyle;
final BoxDecoration? suggestionItemDecoration;
final double suggestionItemContainerHeight;
final Alignment? suggestionTextAlignment;
final double suggestionContainerHeight;
final bool caseSensitive;
// constructor
const TextSearchField({
super.key,
this.hint,
this.inputBorder,
this.searchFieldHintTextStyle,
this.initialValue,
this.filterItems,
this.fetch,
this.query,
this.fullTextSearch = false,
this.rippleColor,
this.onSelected,
this.controller,
this.dependency,
this.textInputAction,
this.dependencyFetch,
this.searchFieldTextStyle,
this.suggestionTextStyle,
this.suggestionItemDecoration,
this.suggestionItemContainerHeight = 50,
this.suggestionTextAlignment,
this.suggestionContainerHeight = 250,
this.caseSensitive = false
});
@override
State<TextSearchField> createState() => _SearchFieldState();
}
class _SearchFieldState extends State<TextSearchField> {
late FocusNode _focusNode;
bool isLoading = false;
List<TextSearchFieldDataModel>? items;
TextSearchFieldDataModel? currentValue;
bool isSelected = false;
final OverlayPortalController _overlayPortalController =
OverlayPortalController();
final _controller = TextEditingController();
final _globalKey = GlobalKey();
@override
void initState() {
_focusNode = FocusNode();
// setting up initial value if there any
if (widget.initialValue != null) {
setCurrentValue(widget.initialValue!);
}
_focusNode.addListener(() {
// showing and hiding search suggestion list
if (_focusNode.hasFocus) {
_overlayPortalController.show();
} else {
_overlayPortalController.hide();
}
});
items = widget.filterItems;
if (widget.dependency != null) {
widget.dependency!.selected = (TextSearchFieldDataModel item) async {
// enabling loader and search field
setState(() {
isLoading = true;
isSelected = true;
});
// calling dependency fetch method
if (widget.dependencyFetch != null) {
items = await widget.dependencyFetch!(item);
}
// disabling loader after content fetch
setState(() {
isLoading = false;
});
};
}
super.initState();
}
void setCurrentValue(TextSearchFieldDataModel value) {
currentValue = value;
_controller.text = value.value!;
if (widget.controller != null) {
if (widget.controller!.selected != null) {
widget.controller!.selected!(value);
}
}
}
@override
Widget build(BuildContext context) {
return OverlayPortal(
overlayChildBuilder: (BuildContext context) => Positioned(
width: _globalKey.globalPaintBounds!.width,
top: _globalKey.globalPaintBounds!.bottom,
left: _globalKey.globalPaintBounds!.left,
child: Container(
alignment: Alignment.center,
height: widget.suggestionContainerHeight,
decoration: const BoxDecoration(color: Colors.white, boxShadow: [
BoxShadow(color: Colors.grey, blurRadius: 15, offset: Offset(2, 3))
]),
child: isLoading
? const CircularProgressIndicator()
: ListView.builder(
itemCount: items != null ? items!.length : 0,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
return TouchRippleEffect(
rippleColor: widget.rippleColor ?? Colors.grey,
onTap: () {
_focusNode.unfocus();
setCurrentValue(items![index]);
if (widget.onSelected != null) {
widget.onSelected!(
index == 0 && _controller.value.text.isNotEmpty ? true : false, index, items![index]);
}
},
child: Container(
key: Key(items![index].key!),
alignment:
widget.suggestionTextAlignment ?? Alignment.center,
height: widget.suggestionItemContainerHeight,
decoration: widget.suggestionItemDecoration ??
const BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
border: Border(
bottom: BorderSide(
color: Colors.grey, width: 0.5))),
child: Text(
items![index].value!,
style: widget.suggestionTextStyle ??
const TextStyle(
color: Colors.black87,
fontWeight: FontWeight.bold,
fontSize: 18),
textDirection: TextDirection.ltr,
),
),
);
}),
),
),
controller: _overlayPortalController,
child: TextField(
key: _globalKey,
controller: _controller,
enabled: widget.dependency == null ? true : isSelected,
style: widget.searchFieldTextStyle ??
const TextStyle(
color: Colors.black, fontSize: 18, fontWeight: FontWeight.w400),
focusNode: _focusNode,
textInputAction: widget.textInputAction ?? TextInputAction.go,
keyboardType: TextInputType.text,
maxLines: 1,
onEditingComplete: () {
// on keyboard go button press we are treating this request as a initial / primary item selected in the list
setCurrentValue(TextSearchFieldDataModel(
key: Utils.buildKey(_controller.value.text),
value: _controller.value.text));
// triggering onSelected function
if (widget.onSelected != null) {
widget.onSelected!(_controller.value.text.isNotEmpty, 0, currentValue!);
}
// removing focus from search field
_focusNode.unfocus();
},
onChanged: (String value) async {
// enabling loader
setState(() {
isLoading = true;
});
if (widget.query != null) {
// if user wants to add custom filter on query item then this statement is going to trigger
items = widget.query!(widget.filterItems, value);
} else if (widget.fetch != null) {
// if user wants to add server / network query filter then this statement is going to trigger
final res = await widget.fetch!(value);
if (res!.isNotEmpty) {
// if there is an item in the response then trigger this
items = [
TextSearchFieldDataModel(
key: Utils.buildKey(value), value: value),
...res
];
} else {
// if there is no items in the response then add on default item
items = [
TextSearchFieldDataModel(
key: Utils.buildKey(value), value: value)
];
}
} else {
// if none of the function has defined then it's going to trigger as a default query filter function
if (value.isNotEmpty) {
String pattern = r"\b" + value + r"\b";
RegExp wordRegex = RegExp(pattern, caseSensitive: widget.caseSensitive);
final lists = widget.filterItems
?.where((element) => element.value!
.contains(widget.fullTextSearch ? wordRegex : RegExp(value, caseSensitive: widget.caseSensitive)))
.toList();
items = [
TextSearchFieldDataModel(
key: Utils.buildKey(value), value: value),
...?lists
];
} else {
// if query string is empty then add default filter list in the request
items = widget.filterItems;
}
}
// disabling loader
setState(() {
isLoading = false;
});
},
onTap: () {
// this function is going to trigger on select search field
_focusNode.requestFocus();
},
decoration: InputDecoration(
border: widget.inputBorder ??
const OutlineInputBorder(
borderSide: BorderSide(
color: Colors.black87,
width: 1.0,
style: BorderStyle.solid)),
hintText: widget.hint ?? "please type your query",
hintStyle: widget.searchFieldHintTextStyle ??
const TextStyle(
color: Colors.grey,
fontSize: 16,
fontWeight: FontWeight.w400),
),
textDirection: TextDirection.ltr,
),
);
}
}
| 0 |
mirrored_repositories/text_search_field/lib | mirrored_repositories/text_search_field/lib/src/global_key.dart | import 'package:flutter/material.dart';
extension GlobalKeyExtension on GlobalKey {
Rect? get globalPaintBounds {
final renderObject = currentContext?.findRenderObject();
final translation = renderObject?.getTransformTo(null).getTranslation();
if (translation != null && renderObject?.paintBounds != null) {
final offset = Offset(translation.x, translation.y);
return renderObject!.paintBounds.shift(offset);
} else {
return null;
}
}
}
| 0 |
mirrored_repositories/text_search_field | mirrored_repositories/text_search_field/test/my_widget_tester.dart | import 'package:flutter/material.dart';
/// this is for testing [widget]
class MyWidgetTester extends StatelessWidget {
final Widget widget;
const MyWidgetTester({super.key, required this.widget});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
height: 500,
alignment: Alignment.center,
child: widget,
),
),
);
}
}
| 0 |
mirrored_repositories/text_search_field/test | mirrored_repositories/text_search_field/test/src/text_search_field_data_model_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:text_search_field/text_search_field.dart';
void main() {
test("should have keys", () {
final model = TextSearchFieldDataModel(key: "key", value: "value");
expect(model.key, "key");
expect(model.value, "value");
});
}
| 0 |
mirrored_repositories/text_search_field/test | mirrored_repositories/text_search_field/test/src/text_search_filed_controller_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:text_search_field/text_search_field.dart';
void main() {
test("should have keys", () {
late TextSearchFieldDataModel data;
final controller = TextSearchFieldController(
text: "hello",
isLoading: true,
selected: (TextSearchFieldDataModel model) {
data = model;
});
controller.selected!(TextSearchFieldDataModel(key: "key", value: "value"));
expect(controller.text, "hello");
expect(controller.isLoading, true);
expect(data.key, "key");
expect(data.value, "value");
});
}
| 0 |
mirrored_repositories/text_search_field/test | mirrored_repositories/text_search_field/test/src/text_search_field_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:text_search_field/text_search_field.dart';
import '../my_widget_tester.dart';
void main() {
testWidgets("should have search Field", (widgetTester) async {
await widgetTester.pumpWidget(const MyWidgetTester(
widget: TextSearchField(
hint: "hello",
)));
final textFinder = find.text("hello");
expect(textFinder, findsOneWidget);
});
}
| 0 |
mirrored_repositories/text_search_field/test | mirrored_repositories/text_search_field/test/src/utils_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:text_search_field/src/Utils.dart';
void main() {
test("buildKey method Testing ", () {
final res = Utils.buildKey("hello Bro");
expect(res, "hello_bro");
});
}
| 0 |
mirrored_repositories/text_search_field/example | mirrored_repositories/text_search_field/example/lib/main.dart | import 'package:flutter/material.dart';
import 'package:text_search_field/text_search_field.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _firstController = TextSearchFieldController();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Container(
alignment: Alignment.center,
margin: const EdgeInsets.only(left: 10, right: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextSearchField(
controller: _firstController,
filterItems: [
TextSearchFieldDataModel(key: "hey", value: "hello"),
TextSearchFieldDataModel(key: "hey", value: "bro"),
TextSearchFieldDataModel(key: "hey", value: "HELLO"),
TextSearchFieldDataModel(key: "hey", value: "how are"),
TextSearchFieldDataModel(key: "hey", value: "hello"),
TextSearchFieldDataModel(key: "hey", value: "bro"),
TextSearchFieldDataModel(key: "hey", value: "how are"),
],
onSelected: (primarySelected, index, item) async {
print("primary item selected: $primarySelected");
print("selected item index: $index");
print("item key: ${item.key}, value: ${item.value}");
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/fingerprint_auth_example | mirrored_repositories/fingerprint_auth_example/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'page/fingerprint_page.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
static const String title = 'Local Auth';
@override
Widget build(BuildContext context) => MaterialApp(
debugShowCheckedModeBanner: false,
title: title,
theme: ThemeData(primarySwatch: Colors.purple),
home: FingerprintPage(),
);
}
| 0 |
mirrored_repositories/fingerprint_auth_example/lib | mirrored_repositories/fingerprint_auth_example/lib/page/home_page.dart | import 'package:fingerprint_auth_example/main.dart';
import 'package:fingerprint_auth_example/page/fingerprint_page.dart';
import 'package:flutter/material.dart';
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text(MyApp.title),
),
body: Padding(
padding: EdgeInsets.all(32),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Home',
style: TextStyle(fontSize: 40),
),
SizedBox(height: 48),
buildLogoutButton(context)
],
),
),
),
);
Widget buildLogoutButton(BuildContext context) => ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: Size.fromHeight(50),
),
child: Text(
'Logout',
style: TextStyle(fontSize: 20),
),
onPressed: () => Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => FingerprintPage()),
),
);
}
| 0 |
mirrored_repositories/fingerprint_auth_example/lib | mirrored_repositories/fingerprint_auth_example/lib/page/fingerprint_page.dart | import 'package:fingerprint_auth_example/api/local_auth_api.dart';
import 'package:fingerprint_auth_example/main.dart';
import 'package:fingerprint_auth_example/page/home_page.dart';
import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';
class FingerprintPage extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text(MyApp.title),
centerTitle: true,
),
body: Padding(
padding: EdgeInsets.all(32),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildAvailability(context),
SizedBox(height: 24),
buildAuthenticate(context),
],
),
),
),
);
Widget buildAvailability(BuildContext context) => buildButton(
text: 'Check Availability',
icon: Icons.event_available,
onClicked: () async {
final isAvailable = await LocalAuthApi.hasBiometrics();
final biometrics = await LocalAuthApi.getBiometrics();
final hasFingerprint = biometrics.contains(BiometricType.fingerprint);
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Availability'),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
buildText('Biometrics', isAvailable),
buildText('Fingerprint', hasFingerprint),
],
),
),
);
},
);
Widget buildText(String text, bool checked) => Container(
margin: EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
checked
? Icon(Icons.check, color: Colors.green, size: 24)
: Icon(Icons.close, color: Colors.red, size: 24),
const SizedBox(width: 12),
Text(text, style: TextStyle(fontSize: 24)),
],
),
);
Widget buildAuthenticate(BuildContext context) => buildButton(
text: 'Authenticate',
icon: Icons.lock_open,
onClicked: () async {
final isAuthenticated = await LocalAuthApi.authenticate();
if (isAuthenticated) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => HomePage()),
);
}
},
);
Widget buildButton({
@required String text,
@required IconData icon,
@required VoidCallback onClicked,
}) =>
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
minimumSize: Size.fromHeight(50),
),
icon: Icon(icon, size: 26),
label: Text(
text,
style: TextStyle(fontSize: 20),
),
onPressed: onClicked,
);
}
| 0 |
mirrored_repositories/fingerprint_auth_example/lib | mirrored_repositories/fingerprint_auth_example/lib/api/local_auth_api.dart | import 'package:flutter/services.dart';
import 'package:local_auth/local_auth.dart';
class LocalAuthApi {
static final _auth = LocalAuthentication();
static Future<bool> hasBiometrics() async {
try {
return await _auth.canCheckBiometrics;
} on PlatformException catch (e) {
return false;
}
}
static Future<List<BiometricType>> getBiometrics() async {
try {
return await _auth.getAvailableBiometrics();
} on PlatformException catch (e) {
return <BiometricType>[];
}
}
static Future<bool> authenticate() async {
final isAvailable = await hasBiometrics();
if (!isAvailable) return false;
try {
return await _auth.authenticateWithBiometrics(
localizedReason: 'Scan Fingerprint to Authenticate',
useErrorDialogs: true,
stickyAuth: true,
);
} on PlatformException catch (e) {
return false;
}
}
}
| 0 |
mirrored_repositories/airplane | mirrored_repositories/airplane/lib/main.dart | import 'package:airplane/cubit/auth_cubit.dart';
import 'package:airplane/cubit/destination_cubit.dart';
import 'package:airplane/cubit/page_cubit.dart';
import 'package:airplane/cubit/seat_cubit.dart';
import 'package:airplane/cubit/transaction_cubit.dart';
import 'package:airplane/ui/pages/bonus_page.dart';
import 'package:airplane/ui/pages/main_page.dart';
import 'package:airplane/ui/pages/sign_in_page.dart';
import 'package:airplane/ui/pages/sign_up_page.dart';
import 'package:airplane/ui/pages/success_checkout_page.dart';
import 'package:flutter/material.dart';
import 'ui/pages/splash_page.dart';
import 'ui/pages/get_started_page.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget{
const MyApp({ Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(create: (context) => PageCubit(),
),
BlocProvider(create: (context) => AuthCubit(),
),
BlocProvider(create: (context) => DestinationCubit()
),
BlocProvider(create: (context) => SeatCubit()),
BlocProvider(create: (context) => TransactionCubit()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
routes: {
'/': (context) => SplashPage(),
'/get-started': (context) => GetStartedPage(),
'/sign-up': (context) => SignUpPage(),
'/bonus-page': (context) => BonusPage(),
'/main': (context) => MainPage(),
'/sign-in': (context) => SignInPage(),
'/success': (context) => SuccessCheckoutPage(),
},
),
);
}
} | 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/shared/theme.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
double defaultMargin = 24.0;
double defaultRadius = 17.0;
Color kPrimaryColor = Color(0xff5C40CC);
Color kBlackColor = Color(0xff1F1449);
Color kWhiteColor = Color(0xffFFFFFF);
Color kGreyColor = Color(0xff9698A9);
Color kGreenColor = Color(0xff0EC3AE);
Color kRedColor = Color(0xffEB70A5);
Color kOrangeColor = Color(0xffFFA235);
Color kBackgroundColor = Color(0xffFAFAFA);
Color kInactiveColor = Color(0xffDBD7EC);
Color kTransparentColor = Colors.transparent;
Color kUnavailableColor = Color(0xffEBECF1);
Color kAvailableColor = Color(0xffE0D9FF);
TextStyle blackTextStyle = GoogleFonts.poppins(
color: kBlackColor,
);
TextStyle whiteTextStyle = GoogleFonts.poppins(
color: kWhiteColor,
);
TextStyle greyTextStyle = GoogleFonts.poppins(
color: kGreyColor,
);
TextStyle greenTextStyle = GoogleFonts.poppins(
color: kGreenColor,
);
TextStyle redTextStyle = GoogleFonts.poppins(
color: kRedColor,
);
TextStyle purpleTextStyle = GoogleFonts.poppins(
color: kPrimaryColor,
);
FontWeight light = FontWeight.w300;
FontWeight regular = FontWeight.w400;
FontWeight medium = FontWeight.w500;
FontWeight semiBold = FontWeight.w600;
FontWeight bold = FontWeight.w700;
FontWeight extraBold = FontWeight.w800;
FontWeight black = FontWeight.w900;
| 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/models/destination_model.dart | import 'package:equatable/equatable.dart';
class DestinationModel extends Equatable{
final String id;
final String name;
final String city;
final String imageUrl;
final double rating;
final int price;
DestinationModel({
required this.id,
this.name = '',
this.city = '',
this.imageUrl = '',
this.rating = 0.0,
this.price = 0,
});
factory DestinationModel.fromJson(String id, Map<String, dynamic> json) =>
DestinationModel(
id: id,
name: json['name'],
city: json['city'],
imageUrl: json['imageUrl'],
rating: json['rating'].toDouble(),
price: json['price']
);
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'city': city,
'imageUrl': imageUrl,
'rating': rating,
'price': price,
};
@override
List<Object?> get props => [id, name, city, imageUrl, rating, price];
} | 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/models/transaction_model.dart | import 'package:airplane/models/destination_model.dart';
import 'package:equatable/equatable.dart';
class TransactionModel extends Equatable{
final String id;
final DestinationModel destination;
final int amountOfTraveler;
final String selectedSeats;
final bool insurance;
final bool refundable;
final double vat;
final int price;
final int grandTotal;
TransactionModel({
required this.destination,
this.id = '',
this.amountOfTraveler = 0,
this.selectedSeats = '',
this.insurance = false,
this.refundable = false,
this.vat = 0,
this.price = 0,
this.grandTotal = 0,
});
factory TransactionModel.fromJson(String id, Map<String, dynamic> json) =>
TransactionModel(
id: id,
destination: DestinationModel.fromJson(json['destination']['id'], json['destination']),
amountOfTraveler: json['amountOfTraveler'],
selectedSeats: json['selectedSeat'],
insurance: json['insurance'],
refundable: json['refundable'],
vat: json['vat'],
price: json['price'],
grandTotal: json['grandTotal'],
);
@override
List<Object?> get props => [
destination,
amountOfTraveler,
selectedSeats,
insurance,
refundable,
vat,
price,
grandTotal,
];
} | 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/models/user_model.dart | import 'package:equatable/equatable.dart';
class UserModel extends Equatable {
final String id;
final String email;
final String name;
final String hobby;
final int balance;
UserModel({
required this.id,
required this.email,
required this.name,
this.hobby = '',
this.balance = 0
});
@override
List<Object?> get props => [id, email, name, hobby, balance];
} | 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/cubit/seat_cubit.dart | import 'package:bloc/bloc.dart';
class SeatCubit extends Cubit<List<String>> {
SeatCubit() : super([]);
void selectSeat(String id){
if(!isSelected(id)){
state.add(id);
} else {
state.remove(id);
}
emit(List.from(state));
}
bool isSelected(String id){
int idx = state.indexOf(id);
if(idx == -1){
return false;
} else {
return true;
}
}
}
| 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/cubit/transaction_state.dart | part of 'transaction_cubit.dart';
abstract class TransactionState extends Equatable {
const TransactionState();
@override
List<Object> get props => [];
}
class TransactionInitial extends TransactionState {}
class TransactionLoading extends TransactionState {}
class TransactionFailed extends TransactionState {
final String error;
TransactionFailed(this.error);
@override
List<Object> get props => [error];
}
class TransactionSuccess extends TransactionState {
final List<TransactionModel> transactions;
TransactionSuccess(this.transactions);
@override
List<Object> get props => [transactions];
} | 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/cubit/page_cubit.dart | import 'dart:ffi';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
class PageCubit extends Cubit<int> {
PageCubit() : super(0);
void setPage(int newPage){
emit(newPage);
}
}
| 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/cubit/destination_cubit.dart | import 'package:airplane/models/destination_model.dart';
import 'package:airplane/services/destination_service.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
part 'destination_state.dart';
class DestinationCubit extends Cubit<DestinationState> {
DestinationCubit() : super(DestinationInitial());
void fetchDestinations() async {
try {
emit(DestinationLoading());
List<DestinationModel> destinations = await DestinationService().fetchDestination();
emit(DestinationSuccess(destinations));
} catch (e){
emit(DestinationFailed(e.toString()));
}
}
}
| 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/cubit/auth_cubit.dart | import 'package:airplane/models/user_model.dart';
import 'package:airplane/services/auth_service.dart';
import 'package:airplane/services/user_service.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
part 'auth_state.dart';
class AuthCubit extends Cubit<AuthState> {
AuthCubit() : super(AuthInitial());
void signIn({
required String email,
required String password
}) async {
try {
emit(AuthLoading());
UserModel user = await AuthService().signIn(
email: email,
password: password
);
emit(AuthSuccess(user));
} catch (e){
emit(AuthFailed(e.toString()));
}
}
void signUp({
required String email,
required String password,
required String name,
String hobby =''
}) async {
try{
emit(AuthLoading());
UserModel user = await AuthService().signUp(email: email, password: password, name: name, hobby: hobby);
emit(AuthSuccess(user));
} catch (e) {
emit(AuthFailed(e.toString()));
}
}
void signOut() async {
try{
emit(AuthLoading());
await AuthService().signOut();
emit(AuthInitial());
} catch (e){
emit(AuthFailed(e.toString()));
}
}
void getCurrentUser(String id) async {
try{
UserModel user = await UserService().getUserById(id);
emit(AuthSuccess(user));
} catch (e){
emit(AuthFailed(e.toString()));
}
}
}
| 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/cubit/destination_state.dart | part of 'destination_cubit.dart';
@immutable
abstract class DestinationState extends Equatable {
const DestinationState();
@override
List<Object> get props => [];
}
class DestinationInitial extends DestinationState {}
class DestinationLoading extends DestinationState {}
class DestinationSuccess extends DestinationState {
final List<DestinationModel> destinations;
DestinationSuccess(this.destinations);
@override
List<Object> get props => [destinations];
}
class DestinationFailed extends DestinationState {
final String error;
DestinationFailed(this.error);
@override
List<Object> get props => [error];
} | 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/cubit/auth_state.dart | part of 'auth_cubit.dart';
abstract class AuthState extends Equatable {
const AuthState();
@override
List<Object> get props => [];
}
class AuthInitial extends AuthState {}
class AuthLoading extends AuthState {}
class AuthSuccess extends AuthState {
final UserModel user;
AuthSuccess(this.user);
@override
List<Object> get props => [user];
}
class AuthFailed extends AuthState {
final String error;
AuthFailed(this.error);
@override
List<Object> get props => [error];
} | 0 |
mirrored_repositories/airplane/lib | mirrored_repositories/airplane/lib/cubit/transaction_cubit.dart | import 'package:airplane/models/transaction_model.dart';
import 'package:airplane/services/transaction_service.dart';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
part 'transaction_state.dart';
class TransactionCubit extends Cubit<TransactionState> {
TransactionCubit() : super(TransactionInitial());
void createTransaction(TransactionModel transactionModel) async {
try{
emit(TransactionLoading());
await TransactionService().createTransaction(transactionModel);
emit(TransactionSuccess([]));
} catch (e){
emit(TransactionFailed(e.toString()));
}
}
void fetchTransaction() async {
try{
emit(TransactionLoading());
List<TransactionModel> transactions = await TransactionService().fetchTransaction();
emit(TransactionSuccess(transactions));
} catch (e){
emit(TransactionFailed(e.toString()));
}
}
}
| 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/interest_item.dart | import 'package:flutter/material.dart';
import '../../shared/theme.dart';
class InterestItem extends StatelessWidget{
final String text;
const InterestItem({Key? key, required this.text}) : super(key: key);
@override
Widget build(BuildContext context) {
return Expanded(
child: Row(
children: [
Container(
width: 16,
height: 16,
margin: EdgeInsets.only(
right: 6
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_checklist.png'
),
fit: BoxFit.cover
)
),
),
Text(
text,
style: blackTextStyle,
),
],
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/destination_card.dart | import 'package:airplane/models/destination_model.dart';
import 'package:flutter/material.dart';
import '../../shared/theme.dart';
import '../pages/detail_page.dart';
class DestinationCard extends StatelessWidget{
final DestinationModel destination;
const DestinationCard(this.destination, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(
builder: (context) => DetailPage(destination),
));
},
child: Container(
width: 200,
height: 323,
margin: EdgeInsets.only(
left: defaultMargin
),
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
color: kWhiteColor
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 180,
height: 220,
margin: EdgeInsets.only(
bottom: 20
),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
destination.imageUrl
)
),
borderRadius: BorderRadius.circular(18)
),
child: Align(
alignment: Alignment.topRight,
child: Container(
width: 55,
height: 30,
decoration: BoxDecoration(
color: kWhiteColor,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(18)
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 15,
height: 15,
margin: EdgeInsets.only(
left: 2,
right: 2
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_star.png'
)
)
),
),
Text(
destination.rating.toString(),
style: blackTextStyle.copyWith(
fontWeight: medium
),
)
],
),
),
),
),
Container(
margin: EdgeInsets.only(
left: 10
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
destination.name,
style: blackTextStyle.copyWith(
fontSize: 18,
fontWeight: medium,
),
),
SizedBox(
height: 5,
),
Text(
destination.city,
style: greyTextStyle.copyWith(
fontWeight: light
),
)
],
),
)
],
),
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/custom_button.dart | import 'package:flutter/material.dart';
import '../../shared/theme.dart';
class CustomButton extends StatelessWidget{
final String title;
final double width;
final EdgeInsets margin;
final Function() onPressed;
const CustomButton({
Key? key,
required this.title,
this.width = double.infinity,
required this.onPressed,
this.margin = EdgeInsets.zero
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: margin,
width: width,
height: 55,
child: TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
backgroundColor: kPrimaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(defaultRadius)
)
),
child: Text(
title,
style: whiteTextStyle.copyWith(
fontSize: 18,
fontWeight: medium
),
),
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/booking_details_item.dart | import 'package:airplane/shared/theme.dart';
import 'package:flutter/material.dart';
class BookingDetailsItem extends StatelessWidget{
final String title;
final String valueText;
final Color color;
const BookingDetailsItem({Key? key, required this.title, required this.valueText, required this.color}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(
top: 16,
),
child: Row(
children: [
Container(
width: 16,
height: 16,
margin: EdgeInsets.only(right: 6),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_checklist.png'
)
)
),
),
Text(
title,
style: blackTextStyle,
),
Spacer(),
Text(
valueText,
style: blackTextStyle.copyWith(
fontWeight: semiBold,
color: color,
),
)
],
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/seat_item.dart | import 'package:airplane/cubit/seat_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../shared/theme.dart';
class SeatItem extends StatelessWidget{
// 0 = Available
// 1 = Selected
// 2 = Unavailable
final String id;
final bool isAvailable;
const SeatItem({
Key? key,
this.isAvailable = true,
required this.id}) : super(key: key);
@override
Widget build(BuildContext context) {
bool isSelected = context.watch<SeatCubit>().isSelected(id);
backgroundColor(){
if(!isAvailable){
return kUnavailableColor;
} else {
if(isSelected){
return kPrimaryColor;
} else {
return kAvailableColor;
}
}
}
borderColor(){
if(!isAvailable){
return kUnavailableColor;
} else {
return kPrimaryColor;
}
}
child(){
if(isSelected){
return Center(
child: Text(
'YOU',
style: whiteTextStyle.copyWith(
fontWeight: semiBold
),
),
);
} else {
return SizedBox();
}
}
return GestureDetector(
onTap: (){
if(isAvailable){
context.read<SeatCubit>().selectSeat(id);
}
},
child: Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: backgroundColor(),
borderRadius: BorderRadius.circular(15),
border: Border.all(
color: borderColor(),
width: 2,
)
),
child: child()
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/photo_item.dart | import 'package:flutter/material.dart';
import '../../shared/theme.dart';
class PhotoItem extends StatelessWidget{
final String imageUrl;
const PhotoItem({Key? key, required this.imageUrl}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: 70,
height: 70,
margin: EdgeInsets.only(
right: 16
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
imageUrl
),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.circular(18)
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/destination_tile.dart | import 'package:airplane/models/destination_model.dart';
import 'package:airplane/ui/pages/detail_page.dart';
import 'package:flutter/material.dart';
import '../../shared/theme.dart';
class DestinationTile extends StatelessWidget{
final DestinationModel destinationModel;
const DestinationTile(this.destinationModel, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(
builder: (context) => DetailPage(destinationModel)
));
},
child: Container(
margin: EdgeInsets.only(
top: 16
),
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: kWhiteColor,
borderRadius: BorderRadius.circular(18)
),
child: Row(
children: [
Container(
width: 70,
height: 70,
margin: EdgeInsets.only(
right: 16
),
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
destinationModel.imageUrl,
)
),
borderRadius: BorderRadius.circular(18),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
destinationModel.name,
style: blackTextStyle.copyWith(
fontSize: 18,
fontWeight: medium,
),
),
SizedBox(
height: 5,
),
Text(
destinationModel.city,
style: greyTextStyle.copyWith(
fontWeight: light
),
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 15,
height: 15,
margin: EdgeInsets.only(
left: 2,
right: 2
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_star.png'
)
)
),
),
Text(
destinationModel.rating.toString(),
style: blackTextStyle.copyWith(
fontWeight: medium
),
)
],
),
],
),
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/custom_button_navigation_item.dart | import 'package:airplane/cubit/page_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../shared/theme.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CustomButtonNavigationItem extends StatelessWidget{
final int index;
final String imageUrl;
const CustomButtonNavigationItem({Key? key,
required this.imageUrl,
required this.index}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
context.read<PageCubit>().setPage(index);
},
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(),
Image.asset(
imageUrl,
width: 24,
height: 24,
color: (context.read<PageCubit>().state == index)
? kPrimaryColor
: kGreyColor,
),
Container(
width: 30,
height: 2,
decoration: BoxDecoration(
color: (context.read<PageCubit>().state == index)
? kPrimaryColor
: kTransparentColor,
borderRadius: BorderRadius.circular(18)
),
)
],
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/custom_text_form_field.dart | import 'package:flutter/material.dart';
import '../../shared/theme.dart';
class CustomTextFormField extends StatelessWidget{
final String title;
final String hint;
final bool obscureText;
final TextEditingController controller;
const CustomTextFormField({
Key? key,
required this.title,
required this.hint,
this.obscureText = false,
required this.controller
}): super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(
bottom: 20
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
),
SizedBox(
height: 6,
),
TextFormField(
obscureText: obscureText,
cursorColor: kBlackColor,
controller: controller,
decoration: InputDecoration(
hintText: hint,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(defaultRadius),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(defaultRadius),
borderSide: BorderSide(
color: kPrimaryColor,
)
),
),
)
],
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/widgets/transaction_card.dart | import 'package:airplane/models/transaction_model.dart';
import 'package:airplane/shared/theme.dart';
import 'package:airplane/ui/widgets/booking_details_item.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class TransactionCard extends StatelessWidget {
final TransactionModel transactionModel;
const TransactionCard(this.transactionModel, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(
top: 30
),
padding: EdgeInsets.symmetric(
horizontal: 20,
vertical: 30,
),
decoration: BoxDecoration(
color: kWhiteColor,
borderRadius: BorderRadius.circular(18),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// NOTE: DESTINATION TILE
Row(
children: [
Container(
width: 70,
height: 70,
margin: EdgeInsets.only(
right: 16
),
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
transactionModel.destination.imageUrl,
)
),
borderRadius: BorderRadius.circular(18),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
transactionModel.destination.name,
style: blackTextStyle.copyWith(
fontSize: 18,
fontWeight: medium,
),
),
SizedBox(
height: 5,
),
Text(
transactionModel.destination.city,
style: greyTextStyle.copyWith(
fontWeight: light
),
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 15,
height: 15,
margin: EdgeInsets.only(
left: 2,
right: 2
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_star.png'
)
)
),
),
Text(
transactionModel.destination.rating.toString(),
style: blackTextStyle.copyWith(
fontWeight: medium
),
)
],
),
],
),
// NOTE: BOOKING DETAILS
Container(
margin: EdgeInsets.only(top: 20),
child: Text(
'Booking Details',
style: blackTextStyle.copyWith(
fontSize: 16,
fontWeight: semiBold
),
),
),
// ITEMS
BookingDetailsItem(
title: 'Traveler',
valueText: '${transactionModel.amountOfTraveler} person',
color: kBlackColor,
),
BookingDetailsItem(
title: 'Seat',
valueText: transactionModel.selectedSeats,
color: kBlackColor,
),
BookingDetailsItem(
title: 'Insurance',
valueText: transactionModel.insurance ? 'YES' : 'NO',
color: transactionModel.insurance ? kGreenColor : kRedColor,
),
BookingDetailsItem(
title: 'Refundable',
valueText: transactionModel.refundable ? 'YES' : 'NO',
color: transactionModel.refundable ? kGreenColor : kRedColor,
),
BookingDetailsItem(
title: 'VAT',
valueText: '${(transactionModel.vat * 100).toStringAsFixed(0)}%',
color: kBlackColor,
),
BookingDetailsItem(
title: 'Price',
valueText: NumberFormat.currency(
locale: 'id',
symbol: 'IDR ',
decimalDigits: 0,
).format(transactionModel.price),
color: kBlackColor,
),
BookingDetailsItem(
title: 'Grand Total',
valueText: NumberFormat.currency(
locale: 'id',
symbol: 'IDR ',
decimalDigits: 0,
).format(transactionModel.grandTotal),
color: kPrimaryColor,
),
],
),
);
}
}
| 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/detail_page.dart | import 'package:airplane/models/destination_model.dart';
import 'package:airplane/ui/pages/choose_seat_page.dart';
import 'package:airplane/ui/widgets/custom_button.dart';
import 'package:airplane/ui/widgets/interest_item.dart';
import 'package:airplane/ui/widgets/photo_item.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../shared/theme.dart';
class DetailPage extends StatelessWidget{
final DestinationModel destinationModel;
const DetailPage(this.destinationModel, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Widget backgroundImage(){
return Container(
width: double.infinity,
height: 450,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
destinationModel.imageUrl
),
fit: BoxFit.cover,
)
),
);
}
Widget customShadow(){
return Container(
height: 214,
width: double.infinity,
margin: EdgeInsets.only(
top: 236,
),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
kWhiteColor.withOpacity(0),
Colors.black.withOpacity(0.95),
]
)
),
);
}
Widget content(){
return Container(
width: double.infinity,
margin: EdgeInsets.symmetric(
horizontal: defaultMargin,
),
child: Column(
children: [
// EMBLEM
Container(
width: 108,
height: 24,
margin: EdgeInsets.only(
top: 30,
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_emblem.png'
)
)
),
),
// TITLE
Container(
margin: EdgeInsets.only(
top: 256
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
destinationModel.name,
style: whiteTextStyle.copyWith(
fontSize: 24,
fontWeight: semiBold
),
overflow: TextOverflow.ellipsis,
),
Text(
destinationModel.city,
style: whiteTextStyle.copyWith(
fontWeight: light,
fontSize: 16,
),
)
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 15,
height: 15,
margin: EdgeInsets.only(
left: 2,
right: 2
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_star.png'
)
)
),
),
Text(
destinationModel.rating.toString(),
style: whiteTextStyle.copyWith(
fontWeight: medium
),
)
],
),
],
),
),
// DESCRIPTION
Container(
width: double.infinity,
margin: EdgeInsets.only(
top: 30,
),
padding: EdgeInsets.symmetric(
horizontal: 20,
vertical: 30
),
decoration: BoxDecoration(
color: kWhiteColor,
borderRadius: BorderRadius.circular(18),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// ABOUT
Text(
'About',
style: blackTextStyle.copyWith(
fontSize: 16,
fontWeight: semiBold
),
),
SizedBox(
height: 6,
),
Text(
'Berada di jalur jalan provinsi yang menghubungkan Denpasar Singaraja serta letaknya yang dekat dengan Kebun Raya Jinja Karya menjadikan tempat Bali.',
style: blackTextStyle.copyWith(
height: 2,
),
),
// PHOTOS
SizedBox(
height: 20,
),
Text(
'Photos',
style: blackTextStyle.copyWith(
fontSize: 16,
fontWeight: semiBold
),
),
SizedBox(
height: 6,
),
Row(
children: [
PhotoItem(imageUrl: 'assets/image_photo1.png'),
PhotoItem(imageUrl: 'assets/image_photo2.png'),
PhotoItem(imageUrl: 'assets/image_photo3.png')
],
),
SizedBox(
height: 20,
),
Text(
'Interests',
style: blackTextStyle.copyWith(
fontSize: 16,
fontWeight: semiBold
),
),
SizedBox(
height: 6,
),
Row(
children: [
InterestItem(text: 'Kids Part'),
InterestItem(text: 'City Museum'),
],
),
SizedBox(
height: 10,
),
Row(
children: [
InterestItem(text: 'Honor Bridge'),
InterestItem(text: 'Central Mall'),
],
)
],
),
),
// PRICE & BOOK BUTTON
Container(
margin: EdgeInsets.symmetric(
vertical: 30
),
width: double.infinity,
child: Row(
children: [
// PRICE
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
NumberFormat.currency(
locale: 'id',
symbol: 'IDR ',
decimalDigits: 0).format(destinationModel.price),
style: blackTextStyle.copyWith(
fontSize: 18,
fontWeight: medium
),
),
SizedBox(
height: 5,
),
Text(
'per orang',
style: greyTextStyle.copyWith(
fontWeight: light,
),
)
],
),
),
// BOOK BUTTON
CustomButton(
width: 170,
title: 'Book Now',
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => ChooseSeatPage(destinationModel)));
},
)
],
),
),
],
),
);
}
return Scaffold(
backgroundColor: kBackgroundColor,
body: SingleChildScrollView(
child: Stack(
children: [
backgroundImage(),
customShadow(),
content(),
],
),
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/choose_seat_page.dart | import 'package:airplane/cubit/seat_cubit.dart';
import 'package:airplane/models/destination_model.dart';
import 'package:airplane/models/transaction_model.dart';
import 'package:airplane/shared/theme.dart';
import 'package:airplane/ui/pages/checkout_page.dart';
import 'package:airplane/ui/widgets/custom_button.dart';
import 'package:airplane/ui/widgets/seat_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
class ChooseSeatPage extends StatelessWidget{
final DestinationModel destinationModel;
const ChooseSeatPage(this.destinationModel, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Widget title(){
return Container(
margin: EdgeInsets.only(
top: 50
),
child: Text(
'Select Your\nFavorite Seat',
style: blackTextStyle.copyWith(
fontWeight: semiBold,
fontSize: 24
),
),
);
}
Widget seatStatus(){
return Container(
margin: EdgeInsets.only(
top: 30
),
child: Row(
children: [
// NOTE: AVAILABLE
Container(
width: 16,
height: 16,
margin: EdgeInsets.only(right: 6),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_available.png'
)
)
),
),
Text(
'Available',
style: blackTextStyle,
),
// NOTE: SELECTED
Container(
width: 16,
height: 16,
margin: EdgeInsets.only(left: 10,right: 6),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_selected.png'
)
)
),
),
Text(
'Selected',
style: blackTextStyle,
),
// NOTE: UNSELECTED
Container(
width: 16,
height: 16,
margin: EdgeInsets.only(left: 10,right: 6),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_unavailable.png'
)
)
),
),
Text(
'Unavailable',
style: blackTextStyle,
)
],
),
);
}
Widget selectSeat(){
Widget indicatorName({
required String name
}){
return Container(
width: 48,
height: 48,
child: Center(
child: Text(
name,
style: greyTextStyle.copyWith(
fontSize: 16
),
),
),
);
}
return BlocBuilder<SeatCubit, List<String>>(
builder: (context, state) {
return Container(
margin: EdgeInsets.only(top: 30),
width: double.infinity,
padding: EdgeInsets.symmetric(
horizontal: 22,
vertical: 30
),
decoration: BoxDecoration(
color: kWhiteColor,
borderRadius: BorderRadius.circular(18),
),
child: Column(
children: [
// NOTE: SEAT INDICATORS
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
indicatorName(name: 'A'),
indicatorName(name: 'B'),
indicatorName(name: ' '),
indicatorName(name: 'C'),
indicatorName(name: 'D')
],
),
// NOTE: SEAT ITEM
Container(
margin: EdgeInsets.only(top: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SeatItem(id: 'A1',),
SeatItem(id: 'B1'),
indicatorName(name: '1'),
SeatItem(id: 'C1'),
SeatItem(id: 'D1'),
],
),
),
Container(
margin: EdgeInsets.only(top: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SeatItem(id: 'A2',isAvailable: false,),
SeatItem(id: 'B2'),
indicatorName(name: '2'),
SeatItem(id: 'C2'),
SeatItem(id: 'D2'),
],
),
),
Container(
margin: EdgeInsets.only(top: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SeatItem(id: 'A3'),
SeatItem(id: 'B3', isAvailable: false,),
indicatorName(name: '3'),
SeatItem(id: 'C3'),
SeatItem(id: 'D3'),
],
),
),
Container(
margin: EdgeInsets.only(top: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SeatItem(id: 'A4'),
SeatItem(id: 'B4'),
indicatorName(name: '4'),
SeatItem(id: 'C4'),
SeatItem(id: 'D4'),
],
),
),
Container(
margin: EdgeInsets.only(top: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SeatItem(id: 'A5'),
SeatItem(id: 'B5'),
indicatorName(name: '5'),
SeatItem(id: 'C5'),
SeatItem(id: 'D5'),
],
),
),
// NOTE: YOUR SEAT
Container(
margin: EdgeInsets.only(top: 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Your seat',
style: greyTextStyle.copyWith(
fontWeight: light,
),
),
Text(
state.join(', '),
overflow: TextOverflow.ellipsis,
style: blackTextStyle.copyWith(
fontWeight: medium,
fontSize: 16
),
)
],
),
),
// NOTE: TOTAL
Container(
margin: EdgeInsets.only(top: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Total',
style: greyTextStyle.copyWith(
fontWeight: light,
),
),
Text(
NumberFormat.currency(
locale: 'id',
symbol: 'IDR ',
decimalDigits: 0,
).format(state.length * destinationModel.price),
style: purpleTextStyle.copyWith(
fontWeight: semiBold,
fontSize: 16
),
)
],
),
)
],
),
);
}
);
}
Widget checkoutButton(){
return BlocBuilder<SeatCubit, List<String>>(
builder: (context, state) {
return CustomButton(
title: 'Continue to Checkout',
onPressed: () {
int price = destinationModel.price * state.length;
Navigator.push(context, MaterialPageRoute(builder: (context) => CheckoutPage(
TransactionModel(
destination: destinationModel,
amountOfTraveler: state.length,
selectedSeats: state.join(', '),
insurance: true,
refundable: false,
vat: 0.45,
price: price,
grandTotal: price + (price * 0.45).toInt()
))
));
},
margin: EdgeInsets.only(top: 30, bottom: 46),
);
}
);
}
return Scaffold(
backgroundColor: kBackgroundColor,
body: ListView(
padding: EdgeInsets.symmetric(horizontal: 24),
children: [
title(),
seatStatus(),
selectSeat(),
checkoutButton()
],
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/checkout_page.dart | import 'package:airplane/cubit/auth_cubit.dart';
import 'package:airplane/cubit/transaction_cubit.dart';
import 'package:airplane/models/transaction_model.dart';
import 'package:airplane/shared/theme.dart';
import 'package:airplane/ui/pages/success_checkout_page.dart';
import 'package:airplane/ui/widgets/booking_details_item.dart';
import 'package:airplane/ui/widgets/custom_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
class CheckoutPage extends StatelessWidget{
final TransactionModel transactionModel;
const CheckoutPage(this.transactionModel, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Widget route(){
return Container(
margin: EdgeInsets.only(
top: 50,
),
child: Column(
children: [
Container(
width: 291,
height: 65,
margin: EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/image_checkout.png'
)
)
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'CGK',
style: blackTextStyle.copyWith(
fontSize: 24,
fontWeight: semiBold
),
),
Text(
'Tangerang',
style: greyTextStyle.copyWith(
fontWeight: light
),
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'TLC',
style: blackTextStyle.copyWith(
fontSize: 24,
fontWeight: semiBold
),
),
Text(
'Ciliwung',
style: greyTextStyle.copyWith(
fontWeight: light
),
),
],
)
],
),
],
),
);
}
Widget bookingDetails(){
return Container(
margin: EdgeInsets.only(
top: 30
),
padding: EdgeInsets.symmetric(
horizontal: 20,
vertical: 30,
),
decoration: BoxDecoration(
color: kWhiteColor,
borderRadius: BorderRadius.circular(18),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// NOTE: DESTINATION TILE
Row(
children: [
Container(
width: 70,
height: 70,
margin: EdgeInsets.only(
right: 16
),
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
transactionModel.destination.imageUrl,
)
),
borderRadius: BorderRadius.circular(18),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
transactionModel.destination.name,
style: blackTextStyle.copyWith(
fontSize: 18,
fontWeight: medium,
),
),
SizedBox(
height: 5,
),
Text(
transactionModel.destination.city,
style: greyTextStyle.copyWith(
fontWeight: light
),
),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 15,
height: 15,
margin: EdgeInsets.only(
left: 2,
right: 2
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_star.png'
)
)
),
),
Text(
transactionModel.destination.rating.toString(),
style: blackTextStyle.copyWith(
fontWeight: medium
),
)
],
),
],
),
// NOTE: BOOKING DETAILS
Container(
margin: EdgeInsets.only(top: 20),
child: Text(
'Booking Details',
style: blackTextStyle.copyWith(
fontSize: 16,
fontWeight: semiBold
),
),
),
// ITEMS
BookingDetailsItem(
title: 'Traveler',
valueText: '${transactionModel.amountOfTraveler} person',
color: kBlackColor,
),
BookingDetailsItem(
title: 'Seat',
valueText: transactionModel.selectedSeats,
color: kBlackColor,
),
BookingDetailsItem(
title: 'Insurance',
valueText: transactionModel.insurance ? 'YES' : 'NO',
color: transactionModel.insurance ? kGreenColor : kRedColor,
),
BookingDetailsItem(
title: 'Refundable',
valueText: transactionModel.refundable ? 'YES' : 'NO',
color: transactionModel.refundable ? kGreenColor : kRedColor,
),
BookingDetailsItem(
title: 'VAT',
valueText: '${(transactionModel.vat * 100).toStringAsFixed(0)}%',
color: kBlackColor,
),
BookingDetailsItem(
title: 'Price',
valueText: NumberFormat.currency(
locale: 'id',
symbol: 'IDR ',
decimalDigits: 0,
).format(transactionModel.price),
color: kBlackColor,
),
BookingDetailsItem(
title: 'Grand Total',
valueText: NumberFormat.currency(
locale: 'id',
symbol: 'IDR ',
decimalDigits: 0,
).format(transactionModel.grandTotal),
color: kPrimaryColor,
),
],
),
);
}
Widget paymentDetails(){
return BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
if(state is AuthSuccess){
return Container(
margin: EdgeInsets.only(top: 30),
padding: EdgeInsets.symmetric(
vertical: 30,
horizontal: 20
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
color: kWhiteColor
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Payment Details',
style: blackTextStyle.copyWith(
fontWeight: semiBold,
fontSize: 16
),
),
Container(
margin: EdgeInsets.only(top: 16),
child: Row(
children: [
Container(
width: 100,
height: 70,
margin: EdgeInsets.only(right: 16),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(18),
image: DecorationImage(
image: AssetImage(
'assets/image_card.png'
),
fit: BoxFit.cover,
),
),
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 24,
height: 24,
margin: EdgeInsets.only(right: 6),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_plane.png',
)
)
),
),
Text(
'Pay',
style: whiteTextStyle.copyWith(
fontSize: 16,
fontWeight: medium
),
)
],
),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
NumberFormat.currency(
locale: 'id',
symbol: 'IDR ',
decimalDigits: 0,
).format(state.user.balance),
style: blackTextStyle.copyWith(
fontWeight: medium,
fontSize: 18
),
overflow: TextOverflow.ellipsis,
),
SizedBox(
height: 5,
),
Text(
'Current Balance',
style: greyTextStyle.copyWith(
fontWeight: light
),
)
],
),
),
],
),
)
],
),
);
} else {
return Center(
child: Text(
'Harga gagal dimuat'
),
);
}
}
);
}
Widget payNowButton(){
return BlocConsumer<TransactionCubit, TransactionState>(
listener: (context, state){
if(state is TransactionSuccess){
Navigator.pushNamedAndRemoveUntil(context, '/success', (route) => false);
} else if(state is TransactionFailed){
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: kRedColor,
content: Text(state.error),
)
);
}
},
builder: (context, state) {
if(State is TransactionLoading){
return Container(
alignment: Alignment.center,
margin: EdgeInsets.only(top: 30),
child: CircularProgressIndicator(),
);
}
return CustomButton(
title: 'Pay Now',
onPressed: () {
context.read<TransactionCubit>().createTransaction(transactionModel);
},
margin: EdgeInsets.only(
top: 30
),
);
}
);
}
Widget tacButton(){
return Center(
child: Container(
margin: EdgeInsets.only(
top: 30,
bottom: 30,
),
child: Text(
'Terms and Conditions',
style: greyTextStyle.copyWith(
fontSize: 16,
fontWeight: light,
decoration: TextDecoration.underline,
),
),
),
);
}
return Scaffold(
backgroundColor: kBackgroundColor,
body: ListView(
padding: EdgeInsets.symmetric(
horizontal: defaultMargin
),
children: [
route(),
bookingDetails(),
paymentDetails(),
payNowButton(),
tacButton(),
],
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/get_started_page.dart | import 'package:airplane/ui/widgets/custom_button.dart';
import 'package:flutter/material.dart';
import '../../shared/theme.dart';
class GetStartedPage extends StatelessWidget{
const GetStartedPage( {Key? key} ) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Container(
width: double.infinity,
height: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/image_get_started.png'
),
fit: BoxFit.cover,
)
),
),
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
'Fly Like a Bird',
style: whiteTextStyle.copyWith(
fontSize: 32,
fontWeight: semiBold,
),
),
SizedBox(
height: 10,
),
Text(
'Explore new world with us and let\nyourself get an amazing experiences',
style: whiteTextStyle.copyWith(
fontSize: 16,
fontWeight: light,
),
textAlign: TextAlign.center,
),
CustomButton(
title: 'Get Started',
width: 220,
onPressed: () {
Navigator.pushNamed(context, '/sign-up');
},
margin: EdgeInsets.only(
top: 50,
bottom: 80,
),
),
],
),
)
],
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/homepage.dart | import 'package:airplane/cubit/auth_cubit.dart';
import 'package:airplane/cubit/destination_cubit.dart';
import 'package:airplane/models/destination_model.dart';
import 'package:airplane/ui/widgets/destination_card.dart';
import 'package:airplane/ui/widgets/destination_tile.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../shared/theme.dart';
class HomePage extends StatefulWidget{
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void initState() {
context.read<DestinationCubit>().fetchDestinations();
super.initState();
}
@override
Widget build(BuildContext context) {
Widget header(){
return BlocBuilder<AuthCubit, AuthState>(
builder: (context,state) {
if(state is AuthSuccess){
return Container(
margin: EdgeInsets.only(
left: defaultMargin,
right: defaultMargin,
top: 30
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Hello,\n${state.user.name}!',
style: blackTextStyle.copyWith(
fontSize: 24,
fontWeight: semiBold,
),
overflow: TextOverflow.ellipsis,
),
SizedBox(
height: 6,
),
Text(
'Where to fly today?',
style: greyTextStyle.copyWith(
fontSize: 16,
fontWeight: light
),
)
],
),
),
Container(
width: 60,
height: 60,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/image_profile.png'
)
),
shape: BoxShape.circle,
),
),
],
),
);
} else {
return Center(
child: Text(
'Mohon maaf halaman tidak dapat dimuat\nMohon untuk membuka ulang aplikasi'
),
);
}
}
);
}
Widget popularDestination(List<DestinationModel> destinations){
return Container(
margin: EdgeInsets.only(
top: 30
),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: destinations.map((DestinationModel destinationModel){
return DestinationCard(destinationModel);
}).toList(),
),
),
);
}
Widget newDestination(List<DestinationModel> destination){
return Container(
margin: EdgeInsets.only(
top:30,
left: defaultMargin,
right: defaultMargin,
bottom: 100,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'New This Year',
style: blackTextStyle.copyWith(
fontSize: 18,
fontWeight: semiBold,
),
),
Column(
children: destination.map((DestinationModel destinationModel){
return DestinationTile(destinationModel);
}).toList(),
)
],
),
);
}
return BlocConsumer<DestinationCubit, DestinationState>(
listener: (context, state){
if(state is DestinationFailed){
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: kRedColor,
content: Text('Homepage Gagal Dimuat'),
)
);
}
},
builder: (context, state) {
if(state is DestinationSuccess){
return ListView(
children: [
header(),
popularDestination(state.destinations),
newDestination(state.destinations),
],
);
}
return Center(
child: CircularProgressIndicator(),
);
}
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/sign_in_page.dart | import 'package:airplane/cubit/auth_cubit.dart';
import 'package:airplane/ui/widgets/custom_button.dart';
import 'package:airplane/ui/widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../shared/theme.dart';
class SignInPage extends StatelessWidget{
SignInPage( {Key? key} ) : super(key: key);
final TextEditingController emailController = TextEditingController(text: '');
final TextEditingController passwordController = TextEditingController(text: '');
@override
Widget build(BuildContext context) {
Widget title(){
return Container(
margin: EdgeInsets.only(
top: 30
),
child: Text(
'Sign In with your\nexisting account',
style: blackTextStyle.copyWith(
fontSize: 24,
fontWeight: semiBold,
),
),
);
}
Widget inputSection(){
Widget submitButton(){
return BlocConsumer<AuthCubit, AuthState>(
listener: (context, state){
if(state is AuthSuccess){
Navigator.pushNamedAndRemoveUntil(context, '/main', (route) => false);
} else if (state is AuthFailed){
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: kRedColor,
content: Text(state.error)
)
);
}
},
builder: (context, state) {
if(state is AuthLoading){
return Center(
child: CircularProgressIndicator(),
);
}
return CustomButton(
title: 'Sign In',
onPressed: () {
context.read<AuthCubit>().signIn(
email: emailController.text,
password: passwordController.text,
);
},
);
}
);
}
return Container(
margin: EdgeInsets.only(
top: 30
),
padding: EdgeInsets.symmetric(
horizontal: 20,
vertical: 30,
),
decoration: BoxDecoration(
color: kWhiteColor,
borderRadius: BorderRadius.circular(defaultRadius),
),
child: Column(
children: [
CustomTextFormField(
title: 'Email Address',
hint: 'Your email address',
controller: emailController,
),
CustomTextFormField(
title: 'Password',
hint: 'Your password',
obscureText: true,
controller: passwordController,
),
SizedBox(
height: 10,
),
submitButton(),
],
),
);
}
Widget signButton(){
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, '/sign-up');
},
child: Center(
child: Container(
margin: EdgeInsets.only(
top: 50,
bottom: 73,
),
child: Text(
'Don\'t have an account? Sign Up',
style: greyTextStyle.copyWith(
fontSize: 16,
fontWeight: light,
decoration: TextDecoration.underline,
),
),
),
),
);
}
return Scaffold(
backgroundColor: kBackgroundColor,
body: SafeArea(
child: ListView(
padding: EdgeInsets.symmetric(
horizontal: defaultMargin,
),
children: [
title(),
inputSection(),
signButton(),
],
),
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/wallet_page.dart | import 'package:flutter/material.dart';
class WalletPage extends StatelessWidget{
const WalletPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'Wallet Page'
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/sign_up_page.dart | import 'package:airplane/cubit/auth_cubit.dart';
import 'package:airplane/cubit/page_cubit.dart';
import 'package:airplane/ui/widgets/custom_button.dart';
import 'package:airplane/ui/widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../shared/theme.dart';
class SignUpPage extends StatelessWidget{
SignUpPage( {Key? key} ) : super(key: key);
final TextEditingController nameController = TextEditingController(text: '');
final TextEditingController emailController = TextEditingController(text: '');
final TextEditingController passwordController = TextEditingController(text: '');
final TextEditingController hobbyController = TextEditingController(text: '');
@override
Widget build(BuildContext context) {
Widget title(){
return Container(
margin: EdgeInsets.only(
top: 30
),
child: Text(
'Join us and get\nyour next journey',
style: blackTextStyle.copyWith(
fontSize: 24,
fontWeight: semiBold,
),
),
);
}
Widget inputSection(){
Widget submitButton(){
return BlocConsumer<AuthCubit, AuthState>(
listener: (context, state){
if(state is AuthSuccess){
Navigator.pushNamedAndRemoveUntil(context, '/bonus-page', (route) => false);
context.read<PageCubit>().setPage(0);
} else if (state is AuthFailed){
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: kRedColor,
content: Text(state.error)
)
);
}
},
builder: (context, state) {
if(state is AuthLoading){
return Center(
child: CircularProgressIndicator(),
);
}
return CustomButton(
title: 'Get Started',
onPressed: () {
context.read<AuthCubit>().signUp(
email: emailController.text,
password: passwordController.text,
name: nameController.text,
hobby: hobbyController.text);
},
);
}
);
}
return Container(
margin: EdgeInsets.only(
top: 30
),
padding: EdgeInsets.symmetric(
horizontal: 20,
vertical: 30,
),
decoration: BoxDecoration(
color: kWhiteColor,
borderRadius: BorderRadius.circular(defaultRadius),
),
child: Column(
children: [
CustomTextFormField(
title: 'Full Name',
hint: 'Your full name',
controller: nameController,
),
CustomTextFormField(
title: 'Email Address',
hint: 'Your email address',
controller: emailController,
),
CustomTextFormField(
title: 'Password',
hint: 'Your password',
obscureText: true,
controller: passwordController,
),
CustomTextFormField(
title: 'Hobby',
hint: 'Your hobby',
controller: hobbyController,
),
SizedBox(
height: 10,
),
submitButton(),
],
),
);
}
Widget signInButton(){
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, '/sign-in');
},
child: Center(
child: Container(
margin: EdgeInsets.only(
top: 50,
bottom: 73,
),
child: Text(
'Have an account? Sign In',
style: greyTextStyle.copyWith(
fontSize: 16,
fontWeight: light,
decoration: TextDecoration.underline,
),
),
),
),
);
}
return Scaffold(
backgroundColor: kBackgroundColor,
body: SafeArea(
child: ListView(
padding: EdgeInsets.symmetric(
horizontal: defaultMargin,
),
children: [
title(),
inputSection(),
signInButton(),
],
),
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/success_checkout_page.dart | import 'package:airplane/cubit/page_cubit.dart';
import 'package:airplane/shared/theme.dart';
import 'package:airplane/ui/widgets/custom_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SuccessCheckoutPage extends StatelessWidget{
const SuccessCheckoutPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: kBackgroundColor,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 300,
height: 150,
margin: EdgeInsets.only(
bottom: 80
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/image_success.png',
)
)
),
),
Text(
'Well Booked 😍',
style: blackTextStyle.copyWith(
fontSize: 32,
fontWeight: semiBold
),
),
SizedBox(
height: 10,
),
Text(
'Are you ready to explore the new\nworld of experiences?',
style: greyTextStyle.copyWith(
fontSize: 16,
fontWeight: light
),
textAlign: TextAlign.center,
),
CustomButton(
title: 'My Bookings',
onPressed: () {
context.read<PageCubit>().setPage(1);
Navigator.pushNamedAndRemoveUntil(context, '/main', (route) => false);
},
width: 220,
margin: EdgeInsets.only(top: 50),
),
],
),
),
);
}
} | 0 |
mirrored_repositories/airplane/lib/ui | mirrored_repositories/airplane/lib/ui/pages/bonus_page.dart | import 'package:airplane/cubit/auth_cubit.dart';
import 'package:airplane/ui/widgets/custom_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../shared/theme.dart';
class BonusPage extends StatelessWidget{
const BonusPage( {Key? key} ): super(key: key);
@override
Widget build(BuildContext context) {
Widget bonusCard(){
return BlocBuilder<AuthCubit, AuthState>(
builder: (context, state) {
if(state is AuthSuccess){
return Container(
width: 300,
height: 211,
padding: EdgeInsets.all(defaultMargin),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/image_card.png'
)
),
boxShadow: [
BoxShadow(
color: kPrimaryColor.withOpacity(0.5),
blurRadius: 50,
offset: Offset(0,10),
)
]
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Name',
style: whiteTextStyle.copyWith(
fontWeight: light,
),
),
Text(
state.user.name,
style: whiteTextStyle.copyWith(
fontSize: 20,
fontWeight: medium,
),
overflow: TextOverflow.ellipsis,
)
],
),
),
Container(
width: 24,
height: 24,
margin: EdgeInsets.only(
right: 6
),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/icon_plane.png',
)
)
),
),
Text(
'Pay',
style: whiteTextStyle.copyWith(
fontSize: 16,
fontWeight: medium,
),
)
],
),
SizedBox(
height: 41,
),
Text(
'Balance',
style: whiteTextStyle.copyWith(
fontSize: 14,
fontWeight: light
),
),
Text(
'IDR ${state.user.balance}',
style: whiteTextStyle.copyWith(
fontSize: 26,
fontWeight: medium
),
)
],
),
);
} else {
return Center(
child: Text(
'Mohon maaf halaman tidak dapat dimuat\nMohon untuk membuka ulang aplikasi'
),
);
}
}
);
}
Widget title(){
return Container(
margin: EdgeInsets.only(
top: 80
),
child: Text(
'Big Bonus 🎉',
style: blackTextStyle.copyWith(
fontSize: 32,
fontWeight: semiBold,
),
),
);
}
Widget subTitle(){
return Container(
margin: EdgeInsets.only(
top: 10
),
child: Text(
'We give you early credit so that\nyou can buy a flight ticket',
style: greyTextStyle.copyWith(
fontSize: 16,
fontWeight: light,
),
textAlign: TextAlign.center,
),
);
}
Widget startButton(){
return CustomButton(
title: 'Start Fly Now',
onPressed: () {
Navigator.pushNamedAndRemoveUntil(context, '/main', (route) => false);
},
margin: EdgeInsets.only(
top: 50
),
width: 220,
);
}
return Scaffold(
backgroundColor: kBackgroundColor,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
bonusCard(),
title(),
subTitle(),
startButton(),
],
),
),
);
}
} | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.