repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/inject/inject_dependency.dart | import 'package:connect_pets/app/features/donate/utils/inject/donate_inject_dependency.dart';
import 'package:connect_pets/app/features/feed/utils/inject/feed_inject_dependency.dart';
import 'package:connect_pets/app/features/finish_signup/utils/inject/finish_inject_dependency.dart';
import 'package:connect_pets/app/features/home/utils/inject/home_inject_dependency.dart';
import 'package:connect_pets/app/features/login/utils/inject/login_inject_dependency.dart';
import 'package:connect_pets/app/features/perfil/utils/inject/perfil_inject_dependency.dart';
import 'package:connect_pets/app/features/post/utils/inject/post_inject_dependency.dart';
import 'package:connect_pets/app/features/refactor_password/utils/inject/refactor_inject_dependency.dart';
import 'package:connect_pets/app/features/signup/utils/inject/signup_inject_dependency.dart';
import 'package:connect_pets/app/features/splash/utils/inject/splash_inject.dart';
import 'package:get_it/get_it.dart';
class InjectDependency {
static void init() {
final getIt = GetIt.instance;
SplashInjectDependency.init(getIt);
SignupInjectDependency.init(getIt);
FinishSignupInjectDependency.init(getIt);
LoginInjecDependency.init(getIt);
RefactorPasswordInjectDependency.init(getIt);
HomeInjectDependency.init(getIt);
FeedInjectDependency.init(getIt);
DonateInjectDependency.init(getIt);
PerfilInjectDependency.init(getIt);
PostInjectDependency.init(getIt);
}
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/entity/post_entity.dart | import 'package:equatable/equatable.dart';
class PostEntity extends Equatable {
final String? id;
final String? urlImage;
late String? agePet;
late String? genderPet;
final int? createdAt;
final int? updatedAt;
final String? userId;
final String? nameUser;
final String? photoUser;
final String? whatsapp;
PostEntity({
this.id,
this.agePet,
this.genderPet,
this.createdAt,
this.updatedAt,
this.userId,
this.urlImage,
this.nameUser,
this.whatsapp,
this.photoUser,
});
@override
List<Object?> get props => [
id,
agePet,
genderPet,
createdAt,
updatedAt,
userId,
urlImage,
nameUser,
whatsapp,
photoUser,
];
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/entity/user_entity.dart | import 'package:equatable/equatable.dart';
class UserEntity extends Equatable {
final String? idUser;
final String? imageUser;
final String? nameUser;
final String? emailUser;
final String? cityUser;
final String? whatsappUser;
final String? passwordUser;
const UserEntity({
this.idUser,
this.imageUser,
this.cityUser,
this.emailUser,
this.nameUser,
this.passwordUser,
this.whatsappUser,
});
@override
List<Object?> get props => [
idUser,
imageUser,
nameUser,
emailUser,
cityUser,
whatsappUser,
passwordUser,
];
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/utils/routes_app.dart | class RoutesApp {
static const String root = '/';
static const String initialPage = '/inicio';
static const String signup = '/criar-conta';
static const String finishSignup = '/finalizar-inscriacao';
static const String login = '/login';
static const String refactorPassword = '/recuperação-senha';
static const String home = '/home';
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/utils/strings_app.dart | class StringsApp {
static const String nameApp = 'Connect Pet';
static const List<String> listCity = [
'Pontas de Pedras',
];
} | 0 |
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/utils/colors_app.dart | import 'package:flutter/material.dart';
class ColorsApp {
static const Color white = Color(0xFFFFFFFF);
static const Color blue = Color(0xFF004FB5);
static const Color purple = Color(0xFFCE03C6);
static const Color red = Color(0xFFCE2915);
static const Color black = Color(0xFF000000);
static const Color green200 = Color(0xFF236320);
static const Color green150 = Color(0xFF02A64D);
static const Color green100 = Color(0xFF04CB5E);
static const Color green50 = Color(0xFFC8F2DB);
static const Color grey150 = Color(0xFFBBBCBC);
static const Color grey100 = Color(0xFFD9D9D9);
static const Color grey50 = Color(0xFFE8EAED);
static const linearGradientGreen = LinearGradient(
colors: [
green150,
green100,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
);
static const linearGradientBorder = LinearGradient(colors: [
green100,
purple,
]);
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/utils/images_app.dart | class ImagesApp {
static const String logo = 'assets/images/logo.png';
static const String google = 'assets/images/google_icon.png';
static const String facebook = 'assets/images/facebook_icon.png';
static const String apple = 'assets/images/apple_icon.png';
static const String listaVazia = 'assets/images/cachorro.png';
static const String patas = 'assets/images/patas.png';
static const String error = 'assets/images/erro_desconhecido.png';
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common/utils | mirrored_repositories/connect-pets/lib/app/common/utils/keys/android_keys.dart | class AndroidKeys {
static const apiKey = String.fromEnvironment('API_KEY_ANDROID');
static const appId = String.fromEnvironment('APP_ID_ANDROID');
static const messagingSenderId =
String.fromEnvironment('MESSAGING_SENDER_ID_ANDROID');
static const projectId = String.fromEnvironment('PROJECT_ID_ANDROID');
static const databaseUrl = String.fromEnvironment("DATABASE_URL_ANDROID");
static const storageBucket = String.fromEnvironment('STORAGE_BUCKET_ANDROID');
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common/utils | mirrored_repositories/connect-pets/lib/app/common/utils/keys/Ios_keys.dart | // ignore_for_file: file_names
class IOSKeys {
static const apiKey = String.fromEnvironment('API_KEY_IOS');
static const appId = String.fromEnvironment('APP_ID_IOS');
static const messagingSenderId =
String.fromEnvironment('MESSAGING_SENDER_ID_IOS');
static const projectId = String.fromEnvironment('PROJECT_ID_IOS');
static const databaseUrl = String.fromEnvironment("DATABASE_URL_IOS");
static const storageBucket = String.fromEnvironment('STORAGE_BUCKET_IOS');
static const iosClientId = String.fromEnvironment('CLIENT_ID_IOS');
static const iosBundleId = String.fromEnvironment('BUNDLE_ID_IOS');
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/error/common_errors.dart | import 'package:connect_pets/app/common/error/failure.dart';
class CommonNoInternetConnectionError extends Failure {
CommonNoInternetConnectionError({message, stack})
: super(
errorMessage: message ?? "Sem conexão com a internet",
stackTrace: stack,
);
}
class CommonNoDataFoundError extends Failure {
CommonNoDataFoundError({message, stack})
: super(
errorMessage: message ?? "Nenhum dado encontrado",
stackTrace: stack,
);
}
class CommonDesconhecidoError extends Failure {
CommonDesconhecidoError({message, stack})
: super(
errorMessage: message ?? "Erro desconhecido",
stackTrace: stack,
);
}
| 0 |
mirrored_repositories/connect-pets/lib/app/common | mirrored_repositories/connect-pets/lib/app/common/error/failure.dart | abstract class Failure implements Exception {
final String errorMessage;
Failure({
this.errorMessage = '',
StackTrace? stackTrace,
});
}
| 0 |
mirrored_repositories/connect-pets | mirrored_repositories/connect-pets/test/test_values.dart | // ignore_for_file: subtype_of_sealed_class, must_be_immutable
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:connect_pets/app/common/entity/user_entity.dart';
import 'package:connect_pets/app/common/error/failure.dart';
import 'package:connect_pets/app/common/model/user_model.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:mockito/mockito.dart';
UserEntity Function() tUserEntity = () => const UserEntity(
cityUser: "Ponta de Pedras",
emailUser: "[email protected]",
idUser: "flaheif4f4ifa5ds4fa6sdfa6sd4fa",
nameUser: "Kevin Sarges",
passwordUser: "412341351363547354",
whatsappUser: "91985206041",
);
UserModel Function() tUserModel = () => const UserModel(
cityUser: "Ponta de Pedras",
emailUser: "[email protected]",
idUser: "flaheif4f4ifa5ds4fa6sdfa6sd4fa",
nameUser: "Kevin Sarges",
passwordUser: "412341351363547354",
whatsappUser: "91985206041",
);
class MockUserCredential extends Mock implements UserCredential {}
class MockCollectionReference extends Mock implements CollectionReference {}
class ErrorMock extends Equatable implements Failure {
@override
String get errorMessage => "Erro";
@override
List<Object?> get props => [];
}
| 0 |
mirrored_repositories/connect-pets/test/app/features/signup/data | mirrored_repositories/connect-pets/test/app/features/signup/data/repository/signup_repository_test.dart | // ignore_for_file: void_checks
import 'package:connect_pets/app/common/error/failure.dart';
import 'package:connect_pets/app/common/model/user_model.dart';
import 'package:connect_pets/app/features/signup/data/repository/signup_repository.dart';
import 'package:connect_pets/app/features/signup/domain/datasource/isignup_datasourcer.dart';
import 'package:dartz/dartz.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import '../../../../../test_values.dart';
import 'signup_repository_test.mocks.dart';
@GenerateNiceMocks([MockSpec<SignupDatasourceImpl>()])
void main() {
late MockSignupDatasourceImpl datasource;
late SignupRepository repository;
late MockUserCredential userCredential;
const user = UserModel();
setUp(() {
datasource = MockSignupDatasourceImpl();
repository = SignupRepository(datasourceImpl: datasource);
userCredential = MockUserCredential();
});
group("Signup com Email e senha", () {
test(
"Deve retorna vazio(Void) se o usuário consegui se cadastrar com email e senha",
() async {
final responseDataSource = userCredential;
final responseRepository =
Right<Failure, UserCredential>(responseDataSource);
when(datasource.signupUserEmailPassword(user)).thenAnswer(
(_) async => responseDataSource,
);
final result = await repository.signupUserEmailPassword(user);
expect(result, responseRepository);
});
test(
"Deve retorna falha(Failure) se o usuario não consegui se cadastrar com email e senha",
() async {
final responseDataSource = ErrorMock();
final responseRepository = Left<Failure, void>(responseDataSource);
when(datasource.signupUserEmailPassword(user))
.thenThrow(responseDataSource);
final result = await repository.signupUserEmailPassword(user);
expect(result, responseRepository);
});
});
group("Signup com Google", () {
test("Deve retorna um UserCredencial caso o signup seja sucesso", () async {
final responseDatasource = userCredential;
final responseRepository = Right<Failure, void>(responseDatasource);
when(datasource.signupGoogle())
.thenAnswer((_) async => responseDatasource);
final result = await repository.signupGoogle();
expect(result, responseRepository);
});
test("Deve retorna exeção caso o signup falhe", () async {
final responseDatasource = ErrorMock();
final responseRepository = Left<Failure, void>(responseDatasource);
when(datasource.signupGoogle()).thenThrow(responseDatasource);
final result = await repository.signupGoogle();
expect(result, responseRepository);
});
});
}
| 0 |
mirrored_repositories/connect-pets/test/app/features/signup/data | mirrored_repositories/connect-pets/test/app/features/signup/data/repository/signup_repository_test.mocks.dart | // Mocks generated by Mockito 5.4.4 from annotations
// in connect_pets/test/app/features/signup/data/repository/signup_repository_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:connect_pets/app/common/model/user_model.dart' as _i5;
import 'package:connect_pets/app/features/signup/domain/datasource/isignup_datasourcer.dart'
as _i3;
import 'package:firebase_auth/firebase_auth.dart' as _i2;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeUserCredential_0 extends _i1.SmartFake
implements _i2.UserCredential {
_FakeUserCredential_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [SignupDatasourceImpl].
///
/// See the documentation for Mockito's code generation for more information.
class MockSignupDatasourceImpl extends _i1.Mock
implements _i3.SignupDatasourceImpl {
@override
_i4.Future<_i2.UserCredential> signupUserEmailPassword(
_i5.UserModel? userModel) =>
(super.noSuchMethod(
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
returnValue: _i4.Future<_i2.UserCredential>.value(_FakeUserCredential_0(
this,
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
)),
returnValueForMissingStub:
_i4.Future<_i2.UserCredential>.value(_FakeUserCredential_0(
this,
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
)),
) as _i4.Future<_i2.UserCredential>);
@override
_i4.Future<_i2.UserCredential> signupGoogle() => (super.noSuchMethod(
Invocation.method(
#signupGoogle,
[],
),
returnValue: _i4.Future<_i2.UserCredential>.value(_FakeUserCredential_0(
this,
Invocation.method(
#signupGoogle,
[],
),
)),
returnValueForMissingStub:
_i4.Future<_i2.UserCredential>.value(_FakeUserCredential_0(
this,
Invocation.method(
#signupGoogle,
[],
),
)),
) as _i4.Future<_i2.UserCredential>);
}
| 0 |
mirrored_repositories/connect-pets/test/app/features/signup/domain | mirrored_repositories/connect-pets/test/app/features/signup/domain/usecase/signup_google_usecase_test.dart | import 'package:connect_pets/app/common/error/failure.dart';
import 'package:connect_pets/app/features/signup/domain/repository/isignup_repository.dart';
import 'package:connect_pets/app/features/signup/domain/usecase/signup_google_usecase.dart';
import 'package:dartz/dartz.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import '../../../../../test_values.dart';
import 'signup_email_password_usecase_test.mocks.dart';
@GenerateNiceMocks([MockSpec<SignupRepositoryImpl>()])
void main() {
late MockSignupRepositoryImpl repository;
late SignupGoogleUseCase useCase;
late UserCredential userCredential;
setUp(() {
repository = MockSignupRepositoryImpl();
useCase = SignupGoogleUseCase(repositoryImpl: repository);
userCredential = MockUserCredential();
});
test(
"Deve retorna um UserCredential se a primeira etapa do cadastro com o google deu certo",
() async {
// cenario
final setting = Right<Failure, UserCredential>(userCredential);
when(repository.signupGoogle()).thenAnswer(
(_) async => setting,
);
// ação
final result = await useCase();
// esperado
expect(result, setting);
});
test(
"Deve retorna um falha(Failure) se a primeira etapa do cadastro com google deu errado",
() async {
final setting = Left<Failure, UserCredential>(ErrorMock());
when(repository.signupGoogle()).thenAnswer(
(_) async => setting,
);
final result = await useCase();
expect(result, setting);
});
}
| 0 |
mirrored_repositories/connect-pets/test/app/features/signup/domain | mirrored_repositories/connect-pets/test/app/features/signup/domain/usecase/signup_email_password_usecase_test.mocks.dart | // Mocks generated by Mockito 5.4.4 from annotations
// in connect_pets/test/app/features/signup/domain/usecase/signup_email_password_usecase_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:connect_pets/app/common/error/failure.dart' as _i5;
import 'package:connect_pets/app/common/model/user_model.dart' as _i7;
import 'package:connect_pets/app/features/signup/domain/repository/isignup_repository.dart'
as _i3;
import 'package:dartz/dartz.dart' as _i2;
import 'package:firebase_auth/firebase_auth.dart' as _i6;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeEither_0<L, R> extends _i1.SmartFake implements _i2.Either<L, R> {
_FakeEither_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [SignupRepositoryImpl].
///
/// See the documentation for Mockito's code generation for more information.
class MockSignupRepositoryImpl extends _i1.Mock
implements _i3.SignupRepositoryImpl {
@override
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>
signupUserEmailPassword(_i7.UserModel? userModel) => (super.noSuchMethod(
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
returnValue:
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>.value(
_FakeEither_0<_i5.Failure, _i6.UserCredential>(
this,
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
)),
returnValueForMissingStub:
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>.value(
_FakeEither_0<_i5.Failure, _i6.UserCredential>(
this,
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
)),
) as _i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>);
@override
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>> signupGoogle() =>
(super.noSuchMethod(
Invocation.method(
#signupGoogle,
[],
),
returnValue:
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>.value(
_FakeEither_0<_i5.Failure, _i6.UserCredential>(
this,
Invocation.method(
#signupGoogle,
[],
),
)),
returnValueForMissingStub:
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>.value(
_FakeEither_0<_i5.Failure, _i6.UserCredential>(
this,
Invocation.method(
#signupGoogle,
[],
),
)),
) as _i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>);
}
| 0 |
mirrored_repositories/connect-pets/test/app/features/signup/domain | mirrored_repositories/connect-pets/test/app/features/signup/domain/usecase/signup_google_usecase_test.mocks.dart | // Mocks generated by Mockito 5.4.4 from annotations
// in connect_pets/test/app/features/signup/domain/usecase/signup_google_usecase_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'package:connect_pets/app/common/error/failure.dart' as _i5;
import 'package:connect_pets/app/common/model/user_model.dart' as _i7;
import 'package:connect_pets/app/features/signup/domain/repository/isignup_repository.dart'
as _i3;
import 'package:dartz/dartz.dart' as _i2;
import 'package:firebase_auth/firebase_auth.dart' as _i6;
import 'package:mockito/mockito.dart' as _i1;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeEither_0<L, R> extends _i1.SmartFake implements _i2.Either<L, R> {
_FakeEither_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [SignupRepositoryImpl].
///
/// See the documentation for Mockito's code generation for more information.
class MockSignupRepositoryImpl extends _i1.Mock
implements _i3.SignupRepositoryImpl {
@override
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>
signupUserEmailPassword(_i7.UserModel? userModel) => (super.noSuchMethod(
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
returnValue:
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>.value(
_FakeEither_0<_i5.Failure, _i6.UserCredential>(
this,
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
)),
returnValueForMissingStub:
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>.value(
_FakeEither_0<_i5.Failure, _i6.UserCredential>(
this,
Invocation.method(
#signupUserEmailPassword,
[userModel],
),
)),
) as _i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>);
@override
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>> signupGoogle() =>
(super.noSuchMethod(
Invocation.method(
#signupGoogle,
[],
),
returnValue:
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>.value(
_FakeEither_0<_i5.Failure, _i6.UserCredential>(
this,
Invocation.method(
#signupGoogle,
[],
),
)),
returnValueForMissingStub:
_i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>.value(
_FakeEither_0<_i5.Failure, _i6.UserCredential>(
this,
Invocation.method(
#signupGoogle,
[],
),
)),
) as _i4.Future<_i2.Either<_i5.Failure, _i6.UserCredential>>);
}
| 0 |
mirrored_repositories/connect-pets/test/app/features/signup/domain | mirrored_repositories/connect-pets/test/app/features/signup/domain/usecase/signup_email_password_usecase_test.dart | // ignore_for_file: void_checks
import 'package:connect_pets/app/common/error/failure.dart';
import 'package:connect_pets/app/common/model/user_model.dart';
import 'package:connect_pets/app/features/signup/domain/repository/isignup_repository.dart';
import 'package:connect_pets/app/features/signup/domain/usecase/signup_email_password_usecase.dart';
import 'package:dartz/dartz.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import '../../../../../test_values.dart';
import 'signup_email_password_usecase_test.mocks.dart';
@GenerateNiceMocks([MockSpec<SignupRepositoryImpl>()])
void main() {
late SignupEmailPasswordUseCase useCase;
late MockSignupRepositoryImpl repository;
late UserCredential userCredential;
const user = UserModel();
setUp(() {
repository = MockSignupRepositoryImpl();
userCredential = MockUserCredential();
useCase = SignupEmailPasswordUseCase(repositoryImpl: repository);
});
test(
"Deve retonar o userCredential se o cadastro com email e senha deu certo",
() async {
// Cenario
final response = userCredential;
when(repository.signupUserEmailPassword(user))
.thenAnswer((_) async => Right<Failure, UserCredential>(response));
// Ação
final result = await useCase(user);
// Esperado
expect(result, Right<Failure, UserCredential>(response));
});
test("Deve retonar falha(Failure) se o cadastro com email e senha deu errado",
() async {
// Cenario
final error = ErrorMock();
when(repository.signupUserEmailPassword(user))
.thenAnswer((_) async => Left<Failure, UserCredential>(error));
// Ação
final result = await useCase(user);
// Esperado
expect(result, Left<Failure, UserCredential>(error));
});
}
| 0 |
mirrored_repositories/solar-system-exploration | mirrored_repositories/solar-system-exploration/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:solar_system/pages/get_started.dart';
import 'package:solar_system/pages/home.dart';
import 'package:device_preview/device_preview.dart';
import 'package:solar_system/pages/planet_details.dart';
import './utils/routes.dart';
int? isViewed;
int? lastPlanetIndex;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
final prefs = await SharedPreferences.getInstance();
isViewed = prefs.getInt('getStarted');
lastPlanetIndex = prefs.getInt('lastPlanet');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
return MaterialApp(
title: 'Solar System',
theme: ThemeData(
primarySwatch: Colors.blue,
fontFamily: 'Poppins',
textTheme: const TextTheme(
headline1: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold,
color: Color(0xff020632),
fontSize: 48,
decoration: TextDecoration.none,
),
headline2: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 42,
decoration: TextDecoration.none,
),
headline3: TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.w600,
color: Colors.white,
fontSize: 18,
decoration: TextDecoration.none,
),
headline4: TextStyle(
fontFamily: 'Poppins',
fontSize: 14,
color: Color(0xff6C6C6C),
decoration: TextDecoration.none,
),
),
),
debugShowCheckedModeBanner: false,
initialRoute: isViewed != 1 ? Routes.getStarted : Routes.home,
routes: {
Routes.getStarted: (context) => const GetStarted(),
Routes.home: (context) => const Home(),
Routes.planetDetails: (context) => const PlanetDetails(),
},
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/pages/get_started.dart | import 'package:flutter/material.dart';
import 'package:solar_system/components/swipe_button.dart';
import 'package:solar_system/utils/routes.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/colors.dart' as color;
class GetStarted extends StatefulWidget {
const GetStarted({Key? key}) : super(key: key);
@override
State<GetStarted> createState() => _GetStartedState();
}
class _GetStartedState extends State<GetStarted> {
bool isFinished = false;
_getStarted() async {
int isViewed = 1;
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('getStarted', isViewed);
}
void _toHome() {
Navigator.of(context).pushReplacementNamed(Routes.home);
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
color.Colors.purple,
color.Colors.darkBlue,
color.Colors.blue,
],
),
),
),
Image.asset(
'assets/images/others/Signal.png',
),
Positioned(
top: 32,
left: 18,
child: Image.asset(
'assets/images/others/Satelite.png',
),
),
Align(
child: Image.asset(
'assets/images/others/Starts.png',
fit: BoxFit.cover,
),
),
Positioned(
right: 0,
top: 200,
// bottom: 500,
child: Image.asset(
'assets/images/others/Moon.png',
),
),
Positioned(
left: 20,
bottom: 280,
child: Image.asset(
'assets/images/others/Comet.png',
width: 66,
height: 44,
),
),
Positioned(
bottom: 0,
child: Image.asset(
'assets/images/others/Astronaut.png',
height: 264.5,
filterQuality: FilterQuality.high,
),
),
Align(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'Explore\nThe Universe',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headline2,
),
const SizedBox(
height: 12,
),
Card(
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40),
),
child: SwipeButton(
text: 'Get Started',
onTap: () async {
await _getStarted();
_toHome();
},
),
)
],
),
),
],
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/pages/planet_details.dart | import 'package:flutter/material.dart';
import 'package:solar_system/components/panel.dart';
import 'package:solar_system/components/sliding_up_panel.dart';
import 'package:solar_system/models/planet.dart';
class PlanetDetails extends StatefulWidget {
const PlanetDetails({Key? key}) : super(key: key);
@override
State<PlanetDetails> createState() => _PlanetDetailsState();
}
class _PlanetDetailsState extends State<PlanetDetails> {
final PanelController panelController = PanelController();
@override
Widget build(BuildContext context) {
final planet = ModalRoute.of(context)!.settings.arguments as Planet;
final mediaQuery = MediaQuery.of(context);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
leading: IconButton(
icon: Image.asset(
'assets/images/others/Arrow Icon.png',
color: Colors.black,
),
onPressed: () => Navigator.of(context).pop(),
),
),
extendBodyBehindAppBar: true,
body: Stack(
alignment: Alignment.center,
children: [
SlidingUpPanel(
minHeight: MediaQuery.of(context).size.height * 0.2,
maxHeight: MediaQuery.of(context).size.height * 0.5,
controller: panelController,
parallaxEnabled: true,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(60.0),
),
color: const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xff0E6CC7),
Color(0xff4B0384),
],
),
body: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: mediaQuery.size.height * 0.14,
),
Expanded(
flex: 3,
child: Container(
margin: planet.id == "6" || planet.id == "7"
? const EdgeInsets.only(left: 26, right: 26)
: const EdgeInsets.only(
bottom: 20,
),
decoration: BoxDecoration(
shape: planet.id == "6" || planet.id == "7" ? BoxShape.rectangle : BoxShape.circle,
image: DecorationImage(
image: AssetImage(planet.image),
),
boxShadow: planet.id == "6" || planet.id == "7"
? []
: [
BoxShadow(
color: planet.boxShadow,
blurRadius: 60.0,
),
],
),
),
),
Expanded(
flex: 3,
child: Padding(
padding: const EdgeInsets.only(left: 32.0, right: 32.0, bottom: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
planet.name,
style: Theme.of(context).textTheme.headline1,
// textAlign: TextAlign.justify,
// style: Theme.of(context).textTheme.headline1,
),
SizedBox(
height: 100,
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Text(
planet.description,
style: Theme.of(context).textTheme.headline4,
// textAlign: TextAlign.justify,
// style: Theme.of(context).textTheme.headline1,
),
),
),
),
],
),
),
),
],
),
Positioned(
right: -20,
bottom: 120,
child: Padding(
padding: const EdgeInsets.only(right: 26.0),
child: Text(
planet.id,
style: TextStyle(
fontFamily: 'Poppins',
fontSize: 250,
fontWeight: FontWeight.bold,
color: const Color(0xff020632).withOpacity(0.04),
),
),
),
),
],
),
panelBuilder: (controller) => PanelWidget(
controller: controller,
panelController: panelController,
planet: planet,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/pages/home.dart | import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:solar_system/components/last_exploration_card.dart';
import 'package:solar_system/components/navigation_drawer.dart';
import 'package:solar_system/components/planet_card.dart';
import 'package:solar_system/data/planet_data.dart';
import 'package:solar_system/utils/routes.dart';
import 'package:solar_system/main.dart';
import '../utils/colors.dart' as color;
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
String dropdownValue = "Planets";
List<String> dropdownItems = ['Planets', 'Others'];
int activePage = 0;
bool selected = false;
_savePlanetData(int index) async {
lastPlanetIndex = index;
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('lastPlanet', index);
}
List<Widget> indicators(cardsLength, currentIndex) {
return List<Widget>.generate(cardsLength, (index) {
return Container(
margin: const EdgeInsets.all(4.0),
width: 10,
height: 10,
decoration: BoxDecoration(
color: currentIndex == index ? Colors.white : Colors.white.withOpacity(0.5),
shape: BoxShape.circle,
),
);
});
}
@override
Widget build(BuildContext context) {
final appBar = AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
leading: Builder(
builder: (context) {
return Container(
margin: const EdgeInsets.only(left: 16),
child: IconButton(
padding: EdgeInsets.zero,
icon: Image.asset(
'assets/images/others/Hamburger_icon.png',
),
onPressed: () => Scaffold.of(context).openDrawer(),
),
);
},
),
actions: [
GestureDetector(
onTap: () {},
child: Image.asset(
'assets/images/others/Avatar.png',
),
),
const SizedBox(width: 16),
],
);
return Stack(
children: [
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
color.Colors.purple,
color.Colors.darkBlue,
color.Colors.blue,
],
),
),
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Image.asset(
'assets/images/others/Stars2.png',
scale: 0.9,
),
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: appBar,
drawer: const NavigationDrawer(),
body: Padding(
padding: const EdgeInsets.only(
left: 26,
// right: 26,
top: 22,
bottom: 26,
),
child: Stack(
children: [
LayoutBuilder(
builder: (context, constraints) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: constraints.maxHeight * 0.04,
child: Text(
'Last Exploration',
style: Theme.of(context).textTheme.headline3,
),
),
SizedBox(height: constraints.maxHeight * 0.02),
GestureDetector(
onTap: () {
Navigator.of(context)
.pushNamed(Routes.planetDetails, arguments: planetData[lastPlanetIndex ?? 0]);
},
child: Stack(
children: [
Container(
height: constraints.maxHeight * 0.25,
padding: const EdgeInsets.only(right: 26),
child: LastExplorationCard(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
planet: planetData[lastPlanetIndex ?? 0],
),
),
Positioned(
right: 58,
child: SizedBox(
height: constraints.maxHeight * 0.24,
child: Image.asset(
'assets/images/others/Astronaut2.png',
// fit: BoxFit.cover,
),
),
),
],
),
),
SizedBox(height: constraints.maxHeight * 0.03),
SizedBox(
height: constraints.maxHeight * 0.04,
child: DropdownButton<String>(
icon: Padding(
padding: const EdgeInsets.only(left: 6.0),
child: Image.asset(
'assets/images/others/chevron-down.png',
),
),
underline: const SizedBox(),
value: dropdownValue,
style: Theme.of(context).textTheme.headline3,
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: dropdownItems.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
SizedBox(height: constraints.maxHeight * 0.02),
Column(
children: [
Container(
height: constraints.maxHeight * 0.55,
padding: const EdgeInsets.only(right: 26),
child: PageView.builder(
itemCount: planetData.length,
physics: const BouncingScrollPhysics(),
onPageChanged: (int page) {
setState(() {
activePage = page;
selected = !selected;
});
},
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () async {
Navigator.of(context)
.pushNamed(Routes.planetDetails, arguments: planetData[index])
.then((e) => setState(() {}));
await _savePlanetData(index);
},
child: ClipRRect(
borderRadius: BorderRadius.circular(60.0),
child: PlanetCard(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
planet: planetData[index],
),
),
);
},
),
),
Container(
height: constraints.maxHeight * 0.05,
padding: const EdgeInsets.only(right: 26, top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: indicators(planetData.length, activePage),
),
)
],
),
],
);
},
),
Positioned(
bottom: planetData[activePage].id == "6" || planetData[activePage].id == "7" ? 120 : 170,
right: planetData[activePage].id == "6" || planetData[activePage].id == "7" ? 20 : 0,
child: Container(
height: planetData[activePage].id == "6" || planetData[activePage].id == "7"
? MediaQuery.of(context).size.height * 0.40
: MediaQuery.of(context).size.height * 0.28,
width: planetData[activePage].id == "6" || planetData[activePage].id == "7"
? MediaQuery.of(context).size.height * 0.40
: 241,
decoration: BoxDecoration(
shape: planetData[activePage].id == "6" || planetData[activePage].id == "7"
? BoxShape.rectangle
: BoxShape.circle,
image: DecorationImage(
image: AssetImage(
planetData[activePage].image,
),
),
boxShadow: planetData[activePage].id == "6" || planetData[activePage].id == "7"
? []
: [
BoxShadow(
color: planetData[activePage].boxShadow,
blurRadius: 60.0,
offset: const Offset(-8, 10),
)
],
),
),
),
],
),
),
),
],
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/components/swipe_button.dart | import 'package:flutter/material.dart';
import 'package:slidable_button/slidable_button.dart';
class SwipeButton extends StatefulWidget {
final String text;
final Function() onTap;
const SwipeButton({Key? key, required this.text, required this.onTap})
: super(key: key);
@override
State<SwipeButton> createState() => _SwipeButtonState();
}
class _SwipeButtonState extends State<SwipeButton> {
bool result = true;
@override
Widget build(BuildContext context) {
return HorizontalSlidableButton(
height: 50,
width: MediaQuery.of(context).size.width * 0.45,
buttonWidth: MediaQuery.of(context).size.width * 0.18,
color: Colors.white,
buttonColor: Theme.of(context).primaryColor,
dismissible: false,
label: Center(
child: Image.asset(
'assets/images/others/Group 15.png',
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Visibility(
visible: result,
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Text(
widget.text,
style: const TextStyle(
fontFamily: 'Poppins',
fontWeight: FontWeight.w600,
fontSize: 14,
color: Color(0xff020632),
decoration: TextDecoration.none,
),
),
),
),
],
),
onChanged: (position) {
widget.onTap;
setState(() {
if (position == SlidableButtonPosition.end) {
result = false;
widget.onTap();
} else {
result = true;
}
});
},
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/components/sliding_up_panel.dart | /*
Name: Akshath Jain
Date: 3/18/2019 - 4/2/2020
Purpose: Defines the sliding_up_panel widget
Copyright: © 2020, Akshath Jain. All rights reserved.
Licensing: More information can be found here: https://github.com/akshathjain/sliding_up_panel/blob/master/LICENSE
*/
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:flutter/physics.dart';
enum SlideDirection {
UP,
DOWN,
}
enum PanelState { OPEN, CLOSED }
class SlidingUpPanel extends StatefulWidget {
/// The Widget that slides into view. When the
/// panel is collapsed and if [collapsed] is null,
/// then top portion of this Widget will be displayed;
/// otherwise, [collapsed] will be displayed overtop
/// of this Widget. If [panel] and [panelBuilder] are both non-null,
/// [panel] will be used.
final Widget? panel;
/// WARNING: This feature is still in beta and is subject to change without
/// notice. Stability is not gauranteed. Provides a [ScrollController] and
/// [ScrollPhysics] to attach to a scrollable object in the panel that links
/// the panel position with the scroll position. Useful for implementing an
/// infinite scroll behavior. If [panel] and [panelBuilder] are both non-null,
/// [panel] will be used.
final Widget Function(ScrollController sc)? panelBuilder;
/// The Widget displayed overtop the [panel] when collapsed.
/// This fades out as the panel is opened.
final Widget? collapsed;
/// The Widget that lies underneath the sliding panel.
/// This Widget automatically sizes itself
/// to fill the screen.
final Widget? body;
/// Optional persistent widget that floats above the [panel] and attaches
/// to the top of the [panel]. Content at the top of the panel will be covered
/// by this widget. Add padding to the bottom of the `panel` to
/// avoid coverage.
final Widget? header;
/// Optional persistent widget that floats above the [panel] and
/// attaches to the bottom of the [panel]. Content at the bottom of the panel
/// will be covered by this widget. Add padding to the bottom of the `panel`
/// to avoid coverage.
final Widget? footer;
/// The height of the sliding panel when fully collapsed.
final double minHeight;
/// The height of the sliding panel when fully open.
final double maxHeight;
/// A point between [minHeight] and [maxHeight] that the panel snaps to
/// while animating. A fast swipe on the panel will disregard this point
/// and go directly to the open/close position. This value is represented as a
/// percentage of the total animation distance ([maxHeight] - [minHeight]),
/// so it must be between 0.0 and 1.0, exclusive.
final double? snapPoint;
/// A border to draw around the sliding panel sheet.
final Border? border;
/// If non-null, the corners of the sliding panel sheet are rounded by this [BorderRadiusGeometry].
final BorderRadiusGeometry? borderRadius;
/// A list of shadows cast behind the sliding panel sheet.
final List<BoxShadow>? boxShadow;
/// The color to fill the background of the sliding panel sheet.
final LinearGradient color;
/// The amount to inset the children of the sliding panel sheet.
final EdgeInsetsGeometry? padding;
/// Empty space surrounding the sliding panel sheet.
final EdgeInsetsGeometry? margin;
/// Set to false to not to render the sheet the [panel] sits upon.
/// This means that only the [body], [collapsed], and the [panel]
/// Widgets will be rendered.
/// Set this to false if you want to achieve a floating effect or
/// want more customization over how the sliding panel
/// looks like.
final bool renderPanelSheet;
/// Set to false to disable the panel from snapping open or closed.
final bool panelSnapping;
/// If non-null, this can be used to control the state of the panel.
final PanelController? controller;
/// If non-null, shows a darkening shadow over the [body] as the panel slides open.
final bool backdropEnabled;
/// Shows a darkening shadow of this [Color] over the [body] as the panel slides open.
final Color backdropColor;
/// The opacity of the backdrop when the panel is fully open.
/// This value can range from 0.0 to 1.0 where 0.0 is completely transparent
/// and 1.0 is completely opaque.
final double backdropOpacity;
/// Flag that indicates whether or not tapping the
/// backdrop closes the panel. Defaults to true.
final bool backdropTapClosesPanel;
/// If non-null, this callback
/// is called as the panel slides around with the
/// current position of the panel. The position is a double
/// between 0.0 and 1.0 where 0.0 is fully collapsed and 1.0 is fully open.
final void Function(double position)? onPanelSlide;
/// If non-null, this callback is called when the
/// panel is fully opened
final VoidCallback? onPanelOpened;
/// If non-null, this callback is called when the panel
/// is fully collapsed.
final VoidCallback? onPanelClosed;
/// If non-null and true, the SlidingUpPanel exhibits a
/// parallax effect as the panel slides up. Essentially,
/// the body slides up as the panel slides up.
final bool parallaxEnabled;
/// Allows for specifying the extent of the parallax effect in terms
/// of the percentage the panel has slid up/down. Recommended values are
/// within 0.0 and 1.0 where 0.0 is no parallax and 1.0 mimics a
/// one-to-one scrolling effect. Defaults to a 10% parallax.
final double parallaxOffset;
/// Allows toggling of the draggability of the SlidingUpPanel.
/// Set this to false to prevent the user from being able to drag
/// the panel up and down. Defaults to true.
final bool isDraggable;
/// Either SlideDirection.UP or SlideDirection.DOWN. Indicates which way
/// the panel should slide. Defaults to UP. If set to DOWN, the panel attaches
/// itself to the top of the screen and is fully opened when the user swipes
/// down on the panel.
final SlideDirection slideDirection;
/// The default state of the panel; either PanelState.OPEN or PanelState.CLOSED.
/// This value defaults to PanelState.CLOSED which indicates that the panel is
/// in the closed position and must be opened. PanelState.OPEN indicates that
/// by default the Panel is open and must be swiped closed by the user.
final PanelState defaultPanelState;
SlidingUpPanel(
{Key? key,
this.panel,
this.panelBuilder,
this.body,
this.collapsed,
this.minHeight = 100.0,
this.maxHeight = 500.0,
this.snapPoint,
this.border,
this.borderRadius,
this.boxShadow = const <BoxShadow>[
BoxShadow(
blurRadius: 8.0,
color: Color.fromRGBO(0, 0, 0, 0.25),
)
],
required this.color,
this.padding,
this.margin,
this.renderPanelSheet = true,
this.panelSnapping = true,
this.controller,
this.backdropEnabled = false,
this.backdropColor = Colors.black,
this.backdropOpacity = 0.5,
this.backdropTapClosesPanel = true,
this.onPanelSlide,
this.onPanelOpened,
this.onPanelClosed,
this.parallaxEnabled = false,
this.parallaxOffset = 0.1,
this.isDraggable = true,
this.slideDirection = SlideDirection.UP,
this.defaultPanelState = PanelState.CLOSED,
this.header,
this.footer})
: assert(panel != null || panelBuilder != null),
assert(0 <= backdropOpacity && backdropOpacity <= 1.0),
assert(snapPoint == null || 0 < snapPoint && snapPoint < 1.0),
super(key: key);
@override
_SlidingUpPanelState createState() => _SlidingUpPanelState();
}
class _SlidingUpPanelState extends State<SlidingUpPanel> with SingleTickerProviderStateMixin {
late AnimationController _ac;
late ScrollController _sc;
bool _scrollingEnabled = false;
VelocityTracker _vt = new VelocityTracker.withKind(PointerDeviceKind.touch);
bool _isPanelVisible = true;
@override
void initState() {
super.initState();
_ac = new AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
value: widget.defaultPanelState == PanelState.CLOSED
? 0.0
: 1.0 //set the default panel state (i.e. set initial value of _ac)
)
..addListener(() {
if (widget.onPanelSlide != null) widget.onPanelSlide!(_ac.value);
if (widget.onPanelOpened != null && _ac.value == 1.0) widget.onPanelOpened!();
if (widget.onPanelClosed != null && _ac.value == 0.0) widget.onPanelClosed!();
});
// prevent the panel content from being scrolled only if the widget is
// draggable and panel scrolling is enabled
_sc = new ScrollController();
_sc.addListener(() {
if (widget.isDraggable && !_scrollingEnabled) _sc.jumpTo(0);
});
widget.controller?._addState(this);
}
@override
Widget build(BuildContext context) {
return Stack(
alignment: widget.slideDirection == SlideDirection.UP ? Alignment.bottomCenter : Alignment.topCenter,
children: <Widget>[
//make the back widget take up the entire back side
widget.body != null
? AnimatedBuilder(
animation: _ac,
builder: (context, child) {
return Positioned(
top: widget.parallaxEnabled ? _getParallax() : 0.0,
child: child ?? SizedBox(),
);
},
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: widget.body,
),
)
: Container(),
//the backdrop to overlay on the body
!widget.backdropEnabled
? Container()
: GestureDetector(
onVerticalDragEnd: widget.backdropTapClosesPanel
? (DragEndDetails dets) {
// only trigger a close if the drag is towards panel close position
if ((widget.slideDirection == SlideDirection.UP ? 1 : -1) * dets.velocity.pixelsPerSecond.dy >
0) _close();
}
: null,
onTap: widget.backdropTapClosesPanel ? () => _close() : null,
child: AnimatedBuilder(
animation: _ac,
builder: (context, _) {
return Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
//set color to null so that touch events pass through
//to the body when the panel is closed, otherwise,
//if a color exists, then touch events won't go through
color: _ac.value == 0.0
? null
: widget.backdropColor.withOpacity(widget.backdropOpacity * _ac.value),
);
}),
),
//the actual sliding part
!_isPanelVisible
? Container()
: _gestureHandler(
child: AnimatedBuilder(
animation: _ac,
builder: (context, child) {
return Container(
height: _ac.value * (widget.maxHeight - widget.minHeight) + widget.minHeight,
margin: widget.margin,
padding: widget.padding,
decoration: widget.renderPanelSheet
? BoxDecoration(
border: widget.border,
borderRadius: widget.borderRadius,
boxShadow: widget.boxShadow,
gradient: widget.color,
)
: null,
child: child,
);
},
child: Stack(
children: <Widget>[
//open panel
Positioned(
top: widget.slideDirection == SlideDirection.UP ? 0.0 : null,
bottom: widget.slideDirection == SlideDirection.DOWN ? 0.0 : null,
width: MediaQuery.of(context).size.width -
(widget.margin != null ? widget.margin!.horizontal : 0) -
(widget.padding != null ? widget.padding!.horizontal : 0),
child: Container(
height: widget.maxHeight,
child: widget.panel != null ? widget.panel : widget.panelBuilder!(_sc),
)),
// header
widget.header != null
? Positioned(
top: widget.slideDirection == SlideDirection.UP ? 0.0 : null,
bottom: widget.slideDirection == SlideDirection.DOWN ? 0.0 : null,
child: widget.header ?? SizedBox(),
)
: Container(),
// footer
widget.footer != null
? Positioned(
top: widget.slideDirection == SlideDirection.UP ? null : 0.0,
bottom: widget.slideDirection == SlideDirection.DOWN ? null : 0.0,
child: widget.footer ?? SizedBox())
: Container(),
// collapsed panel
Positioned(
top: widget.slideDirection == SlideDirection.UP ? 0.0 : null,
bottom: widget.slideDirection == SlideDirection.DOWN ? 0.0 : null,
width: MediaQuery.of(context).size.width -
(widget.margin != null ? widget.margin!.horizontal : 0) -
(widget.padding != null ? widget.padding!.horizontal : 0),
child: Container(
height: widget.minHeight,
child: widget.collapsed == null
? Container()
: FadeTransition(
opacity: Tween(begin: 1.0, end: 0.0).animate(_ac),
// if the panel is open ignore pointers (touch events) on the collapsed
// child so that way touch events go through to whatever is underneath
child: IgnorePointer(ignoring: _isPanelOpen, child: widget.collapsed),
),
),
),
],
),
),
),
],
);
}
@override
void dispose() {
_ac.dispose();
super.dispose();
}
double _getParallax() {
if (widget.slideDirection == SlideDirection.UP)
return -_ac.value * (widget.maxHeight - widget.minHeight) * widget.parallaxOffset;
else
return _ac.value * (widget.maxHeight - widget.minHeight) * widget.parallaxOffset;
}
// returns a gesture detector if panel is used
// and a listener if panelBuilder is used.
// this is because the listener is designed only for use with linking the scrolling of
// panels and using it for panels that don't want to linked scrolling yields odd results
Widget _gestureHandler({required Widget child}) {
if (!widget.isDraggable) return child;
if (widget.panel != null) {
return GestureDetector(
onVerticalDragUpdate: (DragUpdateDetails dets) => _onGestureSlide(dets.delta.dy),
onVerticalDragEnd: (DragEndDetails dets) => _onGestureEnd(dets.velocity),
child: child,
);
}
return Listener(
onPointerDown: (PointerDownEvent p) => _vt.addPosition(p.timeStamp, p.position),
onPointerMove: (PointerMoveEvent p) {
_vt.addPosition(p.timeStamp, p.position); // add current position for velocity tracking
_onGestureSlide(p.delta.dy);
},
onPointerUp: (PointerUpEvent p) => _onGestureEnd(_vt.getVelocity()),
child: child,
);
}
// handles the sliding gesture
void _onGestureSlide(double dy) {
// only slide the panel if scrolling is not enabled
if (!_scrollingEnabled) {
if (widget.slideDirection == SlideDirection.UP)
_ac.value -= dy / (widget.maxHeight - widget.minHeight);
else
_ac.value += dy / (widget.maxHeight - widget.minHeight);
}
// if the panel is open and the user hasn't scrolled, we need to determine
// whether to enable scrolling if the user swipes up, or disable closing and
// begin to close the panel if the user swipes down
if (_isPanelOpen && _sc.hasClients && _sc.offset <= 0) {
setState(() {
if (dy < 0) {
_scrollingEnabled = true;
} else {
_scrollingEnabled = false;
}
});
}
}
// handles when user stops sliding
void _onGestureEnd(Velocity v) {
double minFlingVelocity = 365.0;
double kSnap = 8;
//let the current animation finish before starting a new one
if (_ac.isAnimating) return;
// if scrolling is allowed and the panel is open, we don't want to close
// the panel if they swipe up on the scrollable
if (_isPanelOpen && _scrollingEnabled) return;
//check if the velocity is sufficient to constitute fling to end
double visualVelocity = -v.pixelsPerSecond.dy / (widget.maxHeight - widget.minHeight);
// reverse visual velocity to account for slide direction
if (widget.slideDirection == SlideDirection.DOWN) visualVelocity = -visualVelocity;
// get minimum distances to figure out where the panel is at
double d2Close = _ac.value;
double d2Open = 1 - _ac.value;
double d2Snap =
((widget.snapPoint ?? 3) - _ac.value).abs(); // large value if null results in not every being the min
double minDistance = min(d2Close, min(d2Snap, d2Open));
// check if velocity is sufficient for a fling
if (v.pixelsPerSecond.dy.abs() >= minFlingVelocity) {
// snapPoint exists
if (widget.panelSnapping && widget.snapPoint != null) {
if (v.pixelsPerSecond.dy.abs() >= kSnap * minFlingVelocity || minDistance == d2Snap)
_ac.fling(velocity: visualVelocity);
else
_flingPanelToPosition(widget.snapPoint!, visualVelocity);
// no snap point exists
} else if (widget.panelSnapping) {
_ac.fling(velocity: visualVelocity);
// panel snapping disabled
} else {
_ac.animateTo(
_ac.value + visualVelocity * 0.16,
duration: Duration(milliseconds: 410),
curve: Curves.decelerate,
);
}
return;
}
// check if the controller is already halfway there
if (widget.panelSnapping) {
if (minDistance == d2Close) {
_close();
} else if (minDistance == d2Snap) {
_flingPanelToPosition(widget.snapPoint!, visualVelocity);
} else {
_open();
}
}
}
void _flingPanelToPosition(double targetPos, double velocity) {
final Simulation simulation = SpringSimulation(
SpringDescription.withDampingRatio(
mass: 1.0,
stiffness: 500.0,
ratio: 1.0,
),
_ac.value,
targetPos,
velocity);
_ac.animateWith(simulation);
}
//---------------------------------
//PanelController related functions
//---------------------------------
//close the panel
Future<void> _close() {
return _ac.fling(velocity: -1.0);
}
//open the panel
Future<void> _open() {
return _ac.fling(velocity: 1.0);
}
//hide the panel (completely offscreen)
Future<void> _hide() {
return _ac.fling(velocity: -1.0).then((x) {
setState(() {
_isPanelVisible = false;
});
});
}
//show the panel (in collapsed mode)
Future<void> _show() {
return _ac.fling(velocity: -1.0).then((x) {
setState(() {
_isPanelVisible = true;
});
});
}
//animate the panel position to value - must
//be between 0.0 and 1.0
Future<void> _animatePanelToPosition(double value, {Duration? duration, Curve curve = Curves.linear}) {
assert(0.0 <= value && value <= 1.0);
return _ac.animateTo(value, duration: duration, curve: curve);
}
//animate the panel position to the snap point
//REQUIRES that widget.snapPoint != null
Future<void> _animatePanelToSnapPoint({Duration? duration, Curve curve = Curves.linear}) {
assert(widget.snapPoint != null);
return _ac.animateTo(widget.snapPoint!, duration: duration, curve: curve);
}
//set the panel position to value - must
//be between 0.0 and 1.0
set _panelPosition(double value) {
assert(0.0 <= value && value <= 1.0);
_ac.value = value;
}
//get the current panel position
//returns the % offset from collapsed state
//as a decimal between 0.0 and 1.0
double get _panelPosition => _ac.value;
//returns whether or not
//the panel is still animating
bool get _isPanelAnimating => _ac.isAnimating;
//returns whether or not the
//panel is open
bool get _isPanelOpen => _ac.value == 1.0;
//returns whether or not the
//panel is closed
bool get _isPanelClosed => _ac.value == 0.0;
//returns whether or not the
//panel is shown/hidden
bool get _isPanelShown => _isPanelVisible;
}
class PanelController {
_SlidingUpPanelState? _panelState;
void _addState(_SlidingUpPanelState panelState) {
this._panelState = panelState;
}
/// Determine if the panelController is attached to an instance
/// of the SlidingUpPanel (this property must return true before any other
/// functions can be used)
bool get isAttached => _panelState != null;
/// Closes the sliding panel to its collapsed state (i.e. to the minHeight)
Future<void> close() {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._close();
}
/// Opens the sliding panel fully
/// (i.e. to the maxHeight)
Future<void> open() {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._open();
}
/// Hides the sliding panel (i.e. is invisible)
Future<void> hide() {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._hide();
}
/// Shows the sliding panel in its collapsed state
/// (i.e. "un-hide" the sliding panel)
Future<void> show() {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._show();
}
/// Animates the panel position to the value.
/// The value must between 0.0 and 1.0
/// where 0.0 is fully collapsed and 1.0 is completely open.
/// (optional) duration specifies the time for the animation to complete
/// (optional) curve specifies the easing behavior of the animation.
Future<void> animatePanelToPosition(double value, {Duration? duration, Curve curve = Curves.linear}) {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
assert(0.0 <= value && value <= 1.0);
return _panelState!._animatePanelToPosition(value, duration: duration, curve: curve);
}
/// Animates the panel position to the snap point
/// Requires that the SlidingUpPanel snapPoint property is not null
/// (optional) duration specifies the time for the animation to complete
/// (optional) curve specifies the easing behavior of the animation.
Future<void> animatePanelToSnapPoint({Duration? duration, Curve curve = Curves.linear}) {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
assert(_panelState!.widget.snapPoint != null, "SlidingUpPanel snapPoint property must not be null");
return _panelState!._animatePanelToSnapPoint(duration: duration, curve: curve);
}
/// Sets the panel position (without animation).
/// The value must between 0.0 and 1.0
/// where 0.0 is fully collapsed and 1.0 is completely open.
set panelPosition(double value) {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
assert(0.0 <= value && value <= 1.0);
_panelState!._panelPosition = value;
}
/// Gets the current panel position.
/// Returns the % offset from collapsed state
/// to the open state
/// as a decimal between 0.0 and 1.0
/// where 0.0 is fully collapsed and
/// 1.0 is full open.
double get panelPosition {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._panelPosition;
}
/// Returns whether or not the panel is
/// currently animating.
bool get isPanelAnimating {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._isPanelAnimating;
}
/// Returns whether or not the
/// panel is open.
bool get isPanelOpen {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._isPanelOpen;
}
/// Returns whether or not the
/// panel is closed.
bool get isPanelClosed {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._isPanelClosed;
}
/// Returns whether or not the
/// panel is shown/hidden.
bool get isPanelShown {
assert(isAttached, "PanelController must be attached to a SlidingUpPanel");
return _panelState!._isPanelShown;
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/components/planet_card.dart | import 'package:flutter/material.dart';
import 'package:solar_system/models/planet.dart';
class PlanetCard extends StatelessWidget {
final double width;
final double height;
final Planet planet;
const PlanetCard({required this.width, required this.height, required this.planet, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Card(
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(60.0),
),
shadowColor: const Color(0xff151056),
child: Container(
clipBehavior: Clip.hardEdge,
width: width,
height: height,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(60.0),
color: Colors.white,
),
child: Stack(
children: [
Positioned(
right: -2,
top: 120,
child: Text(
planet.id,
style: TextStyle(
fontFamily: 'Poppins',
fontSize: 200,
fontWeight: FontWeight.bold,
color: const Color(0xff020632).withOpacity(0.04),
),
),
),
Positioned(
left: 30,
bottom: 30,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
planet.name,
style: Theme.of(context).textTheme.headline1,
),
const SizedBox(width: 6),
Container(
width: 50,
height: 50,
decoration: BoxDecoration(
color: const Color(0xffF48635),
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
offset: const Offset(-4, 0),
blurRadius: 15,
color: const Color(0xffC1580B).withOpacity(0.4),
),
],
),
child: Image.asset(
'assets/images/others/arrow-right.png',
),
),
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/components/navigation_drawer.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/colors.dart' as color;
class NavigationDrawer extends StatelessWidget {
const NavigationDrawer({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
SizedBox(
height: MediaQuery.of(context).size.height * 0.30,
child: const DrawerHeader(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [
color.Colors.purple,
color.Colors.blue,
],
),
image: DecorationImage(
fit: BoxFit.cover,
opacity: .6,
image: AssetImage(
'assets/images/others/Stars2.png',
),
),
boxShadow: [BoxShadow(blurRadius: 15)],
borderRadius: BorderRadius.only(bottomRight: Radius.circular(100)),
),
child: Padding(
padding: EdgeInsets.only(top: 28.0),
child: Text(
'Solar System Exploration',
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
),
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.6,
),
Container(
height: MediaQuery.of(context).size.height * 0.1,
alignment: Alignment.center,
child: ListTile(
leading: const Icon(
Icons.exit_to_app_rounded,
color: color.Colors.darkBlue,
),
title: const Text('Exit'),
onTap: () {
SystemNavigator.pop();
},
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/components/last_exploration_card.dart | import 'package:flutter/material.dart';
import 'package:solar_system/models/planet.dart';
class LastExplorationCard extends StatelessWidget {
final double width;
final double height;
final Planet planet;
const LastExplorationCard({
required this.width,
required this.height,
required this.planet,
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Card(
elevation: 20,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40.0),
),
shadowColor: const Color(0xff151056),
child: Container(
clipBehavior: Clip.hardEdge,
width: width,
height: height,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: planet.colors,
),
borderRadius: BorderRadius.circular(40.0),
),
child: Stack(
children: [
Positioned(
bottom: planet.id == "6" || planet.id == "7" ? 28 : 50,
left: 16,
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
boxShadow: planet.id == "6" || planet.id == "7"
? []
: [
BoxShadow(
color: planet.boxShadow,
blurRadius: 20.0,
offset: const Offset(-8, 10),
)
],
),
child: Image.asset(
planet.image,
height: 163,
width: 163,
),
),
),
Positioned(
left: 30,
bottom: 10,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
planet.name,
style: const TextStyle(
fontFamily: 'Poppins',
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(width: 6),
Image.asset(
'assets/images/others/arrow-right.png',
),
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/components/panel.dart | import 'package:flutter/material.dart';
import 'package:solar_system/components/sliding_up_panel.dart';
import 'package:solar_system/data/planet_data.dart';
import 'package:solar_system/models/planet.dart';
class PanelWidget extends StatelessWidget {
final ScrollController controller;
final PanelController panelController;
final Planet planet;
const PanelWidget({required this.controller, required this.panelController, required this.planet, Key? key})
: super(key: key);
void tooglePanel() => panelController.isPanelOpen ? panelController.close() : panelController.open();
Widget buildGallery() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 97,
height: 100,
// clipBehavior: Clip.hardEdge,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
planet.id == "3" ? planet.imageGallery[0] : planet.image,
),
),
border: Border.all(color: const Color(0xffFFFFFF).withOpacity(0.3), width: 4),
borderRadius: BorderRadius.circular(30),
),
),
Container(
width: 97,
height: 100,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
planet.id == "3" ? planet.imageGallery[1] : planet.image,
),
),
border: Border.all(color: const Color(0xffFFFFFF).withOpacity(0.3), width: 4),
borderRadius: BorderRadius.circular(30),
),
),
Container(
width: 97,
height: 100,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
planet.id == "3" ? planet.imageGallery[2] : planet.image,
),
),
border: Border.all(color: const Color(0xffFFFFFF).withOpacity(0.3), width: 4),
borderRadius: BorderRadius.circular(30),
),
),
],
),
);
}
Widget buildDragHandle() {
return GestureDetector(
onTap: tooglePanel,
child: Center(
child: Container(
width: 41,
height: 8,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(60),
),
),
),
);
}
@override
Widget build(BuildContext context) {
return ListView(
padding: EdgeInsets.zero,
controller: controller,
children: [
const SizedBox(height: 12),
buildDragHandle(),
const SizedBox(height: 18),
buildGallery(),
const SizedBox(height: 36),
Center(
child: Text(
'Coming Soon!',
style: Theme.of(context).textTheme.headline2,
),
),
],
);
}
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/models/planet.dart | import 'package:flutter/material.dart';
class Planet {
final String id;
final String name;
final String image;
final List<String> imageGallery;
final String description;
final Color boxShadow;
final List<Color> colors;
const Planet({
required this.id,
required this.name,
required this.description,
required this.image,
required this.imageGallery,
required this.boxShadow,
required this.colors,
});
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/data/planet_data.dart | import 'package:flutter/cupertino.dart';
import '../models/planet.dart';
const planetData = [
Planet(
id: "1",
name: "Mercury",
description:
"The smallest planet in our solar system and nearest to the Sun, Mercury is only slightly larger than Earth's Moon.",
boxShadow: Color.fromARGB(255, 139, 90, 61),
colors: [Color(0xffCE7744), Color(0xffDEA079)],
image: "assets/images/planets/mercury.png",
imageGallery: [],
),
Planet(
id: "2",
name: "Venus",
description:
"Venus is the second planet from the Sun and is Earth's closest planetary neighbor. It's one of the four inner, terrestrial (or rocky) planets, and it's often called Earth's twin because it's similar in size and density. ",
boxShadow: Color.fromARGB(255, 255, 110, 82),
colors: [Color.fromARGB(255, 255, 151, 103), Color.fromARGB(255, 248, 195, 125)],
image: "assets/images/planets/venus.png",
imageGallery: [],
),
Planet(
id: "3",
name: "Earth",
description:
"Our home planet is the third planet from the Sun, and the only place we know of so far thats inhabited by living things.",
boxShadow: Color.fromARGB(255, 147, 247, 190),
colors: [Color(0xff19C5EB), Color(0xff9BEDB1)],
image: "assets/images/planets/earth.png",
imageGallery: [
"assets/images/gallery/earth/e1.png",
"assets/images/gallery/earth/e2.png",
"assets/images/gallery/earth/e3.png"
],
),
Planet(
id: "4",
name: "Mars",
description:
"Mars is the fourth planet from the Sun – a dusty, cold, desert world with a very thin atmosphere. Mars is also a dynamic planet with seasons, polar ice caps, canyons, extinct volcanoes, and evidence that it was even more active in the past.",
boxShadow: Color(0xffEC2C22),
colors: [Color(0xffF48535), Color(0xffF4A435)],
image: "assets/images/planets/mars.png",
imageGallery: [],
),
Planet(
id: "5",
name: "Jupiter",
description:
"Fifth in line from the Sun, Jupiter is, by far, the largest planet in the solar system – more than twice as massive as all the other planets combined.",
boxShadow: Color(0xffA4776A),
colors: [Color(0xffDD7252), Color(0xffF2BD89)],
image: "assets/images/planets/jupiter.png",
imageGallery: [],
),
Planet(
id: "6",
name: "Saturn",
description: "Saturn is the sixth planet from the Sun and the second-largest planet in our solar system.",
boxShadow: Color(0xffFFDFB0),
colors: [Color(0xffD26D37), Color(0xffDF9974)],
image: "assets/images/planets/saturn.png",
imageGallery: [],
),
Planet(
id: "7",
name: "Uranus",
description:
"Uranus is the seventh planet from the Sun, and has the third-largest diameter in our solar system. It was the first planet found with the aid of a telescope, Uranus was discovered in 1781 by astronomer William Herschel, although he originally thought it was either a comet or a star.",
boxShadow: Color.fromARGB(255, 210, 244, 250),
colors: [Color(0xff06A1CC), Color(0xff18C4DB)],
image: "assets/images/planets/uranus.png",
imageGallery: [],
),
Planet(
id: "8",
name: "Neptune",
description:
"Dark, cold, and whipped by supersonic winds, ice giant Neptune is the eighth and most distant planet in our solar system.",
boxShadow: Color.fromARGB(255, 2, 103, 180),
colors: [Color(0xff0073CD), Color.fromARGB(255, 6, 131, 233)],
image: 'assets/images/planets/neptune.png',
imageGallery: [],
),
];
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/utils/routes.dart | class Routes {
static const String getStarted = '/get-started';
static const String home = '/';
static const String planetDetails = '/planet-details';
}
| 0 |
mirrored_repositories/solar-system-exploration/lib | mirrored_repositories/solar-system-exploration/lib/utils/colors.dart | import 'package:flutter/material.dart';
class Colors {
static const Color blue = Color(0xff0D6FCA);
static const Color darkBlue = Color(0xff26006F);
static const Color purple = Color(0xff4B0384);
}
| 0 |
mirrored_repositories/tests_in_flutter | mirrored_repositories/tests_in_flutter/lib/main.dart | import 'package:flutter/material.dart';
import 'pages/pages.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Test in Flutter',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.purple,
),
home: const HomePage(),
);
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/pages/home_page.dart | import 'package:flutter/material.dart';
import 'package:tests_in_flutter/models/models.dart';
import 'pages.dart';
import 'widgets/widgets.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
User _user = User(
balance: 0,
history: [],
);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
HeaderWidget(
user: _user,
onDeposit: () => _toOperationPage(OperationType.deposit),
onWithdraw: () => _toOperationPage(OperationType.withdraw),
),
HistoryListWidget(user: _user),
],
),
),
);
}
// Go to the operation page according to the type of operation
Future<void> _toOperationPage(OperationType type) async {
final response = await showModalBottomSheet<User>(
context: context,
isScrollControlled: true,
useRootNavigator: true,
enableDrag: false,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
builder: (context) {
return SizedBox(
height: MediaQuery.of(context).size.height - 48,
child: OperationPage(
operationType: type,
user: _user,
// Shows the successful snackbar if the operation is completed
onSuccess: (message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
),
);
},
// Displays an error dialog if validation fails to
// perform the operation
onError: (error) {
showDialog(
barrierDismissible: true,
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Ops...'),
content: Text(
error.message,
key: const Key('ErrorMessage'),
),
actions: [
TextButton(
key: const Key('OkButton'),
onPressed: () => Navigator.pop(context),
child: const Text(
'Ok',
key: Key('TextButton'),
),
),
],
);
},
);
},
),
);
},
);
// If everything works out, the new data is returned
if (response != null) {
setState(() {
// User receives the user with the new data and the screen is updated
_user = response;
});
}
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/pages/pages.dart | export 'home_page.dart';
export 'operation_page.dart';
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/pages/operation_page.dart | import 'package:flutter/material.dart';
import 'package:extended_masked_text/extended_masked_text.dart';
import 'package:tests_in_flutter/error/failure.dart';
import 'package:tests_in_flutter/models/models.dart';
class OperationPage extends StatefulWidget {
const OperationPage({
super.key,
required this.user,
required this.operationType,
required this.onError,
required this.onSuccess,
});
final User user;
final OperationType operationType;
final Function(Failure) onError;
final Function(String) onSuccess;
@override
State<OperationPage> createState() => _OperationPageState();
}
class _OperationPageState extends State<OperationPage> {
final controller = MoneyMaskedTextController(
leftSymbol: 'R\$ ',
initialValue: 0.0,
);
@override
Widget build(BuildContext context) {
final textStyle = Theme.of(context).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 32,
);
return Scaffold(
backgroundColor: Colors.transparent,
floatingActionButton: FloatingActionButton(
key: const Key('OperationContinue'),
disabledElevation: 0,
child: const Icon(Icons.chevron_right),
onPressed: () {
try {
// Create the operation object
final Operation operation = Operation(
balance: widget.user.balance,
value: controller.numberValue,
type: widget.operationType,
);
// Do the operation
final response = operation.doOperation();
widget.onSuccess(response.message);
// Closes the modal returning the user with their new data
Navigator.pop(
context,
widget.user.update(
balance: response.result,
history: response.history,
),
);
} on Failure catch (e) {
// Error handling if validation fails
widget.onError(e);
}
},
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () => Navigator.pop(context),
child: SizedBox(
height: 54,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Align(
alignment: Alignment.centerLeft,
child: Icon(
Icons.close,
key: const Key('CloseOperation'),
color: Colors.grey[500],
),
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
children: [
Text(
'Qual o valor do ${widget.operationType == OperationType.deposit ? 'depósito' : 'saque'}?',
style: Theme.of(context).textTheme.titleLarge,
)
],
),
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
key: const Key('OperationValueKey'),
controller: controller,
autofocus: true,
keyboardType: TextInputType.number,
style: textStyle,
decoration: InputDecoration(
border: InputBorder.none,
hintStyle: textStyle,
hintText: 'R\$ 0,00',
),
),
Text(
'Digite um valor maior que R\$ 0,01',
style: Theme.of(context).textTheme.bodySmall,
)
],
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib/pages | mirrored_repositories/tests_in_flutter/lib/pages/widgets/history_item_widget.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:tests_in_flutter/models/models.dart';
class HistoryItemWidget extends StatelessWidget {
HistoryItemWidget({
super.key,
required this.history,
required this.index,
});
final History history;
final int index;
final DateFormat _dateFormatter = DateFormat('d/M/y');
final NumberFormat _formatter = NumberFormat.currency(
locale: 'pt_br',
symbol: 'R\$',
);
@override
Widget build(BuildContext context) {
return ListTile(
key: Key('HistoryItem${index.toString()}'),
contentPadding: const EdgeInsets.symmetric(horizontal: 32),
onTap: () {},
title: Text(
history.description,
key: Key('HistoryTitle${index.toString()}'),
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14,
),
),
trailing: Text(
_dateFormatter.format(history.dateTime),
key: Key('HistoryDate${index.toString()}'),
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 12,
color: Colors.grey[600],
),
),
subtitle: Text(
key: Key('HistorySubtitle${index.toString()}'),
_formatter.format((history.value)),
),
leading: Container(
height: 32,
width: 32,
decoration: BoxDecoration(
color: Colors.grey[200],
shape: BoxShape.circle,
),
child: history.type == OperationType.deposit
? Icon(
Icons.add,
key: Key('IconDeposit${index.toString()}'),
color: Colors.black,
size: 18,
)
: Icon(
Icons.remove,
key: Key('IconWithdraw${index.toString()}'),
color: Colors.black,
size: 18,
),
),
);
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib/pages | mirrored_repositories/tests_in_flutter/lib/pages/widgets/header_widget.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:tests_in_flutter/models/models.dart';
class HeaderWidget extends StatelessWidget {
HeaderWidget({
super.key,
required this.user,
required this.onDeposit,
required this.onWithdraw,
});
final NumberFormat _formatter = NumberFormat.currency(
locale: 'pt_br',
symbol: 'R\$',
);
final User user;
final Function() onDeposit;
final Function() onWithdraw;
@override
Widget build(BuildContext context) {
final value = _formatter.format(user.balance);
return Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 32,
width: double.infinity,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(
'Saldo disponível',
style: TextStyle(
color: Colors.grey[700],
fontWeight: FontWeight.w500,
fontSize: 14,
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
value,
key: const Key('BalanceKey'),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 38,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(height: 16),
const SizedBox(
height: 16,
width: double.infinity,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Row(
children: [
GestureDetector(
key: const Key('DepositButton'),
onTap: onDeposit,
child: Chip(
backgroundColor: Colors.grey[200],
label: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: const [
Icon(
Icons.add,
color: Colors.black,
size: 18,
),
SizedBox(width: 8),
Text(
'Depositar',
style: TextStyle(
fontSize: 12,
color: Colors.black,
),
),
],
),
),
),
),
const SizedBox(width: 8),
GestureDetector(
key: const Key('WithdrawButton'),
onTap: onWithdraw,
child: Chip(
backgroundColor: Colors.grey[200],
label: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: const [
Icon(
Icons.remove,
color: Colors.black,
size: 18,
),
SizedBox(width: 8),
Text(
'Sacar',
style: TextStyle(
fontSize: 12,
color: Colors.black,
),
),
],
),
),
),
),
],
),
),
const SizedBox(height: 16),
Divider(
height: 1,
color: Colors.grey[300],
),
const SizedBox(
height: 16,
width: double.infinity,
),
],
);
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib/pages | mirrored_repositories/tests_in_flutter/lib/pages/widgets/widgets.dart | export 'header_widget.dart';
export 'history_item_widget.dart';
export 'history_list_widget.dart';
| 0 |
mirrored_repositories/tests_in_flutter/lib/pages | mirrored_repositories/tests_in_flutter/lib/pages/widgets/history_list_widget.dart | import 'package:flutter/material.dart';
import 'package:tests_in_flutter/models/models.dart';
import 'widgets.dart';
class HistoryListWidget extends StatelessWidget {
const HistoryListWidget({
super.key,
required this.user,
});
final User user;
@override
Widget build(BuildContext context) {
return Expanded(
child: Column(
children: [
user.history.isNotEmpty
? const Padding(
padding: EdgeInsets.symmetric(horizontal: 32),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'Histórico',
style: TextStyle(
color: Colors.black,
),
),
),
)
: Container(),
const SizedBox(
height: 16,
width: double.infinity,
),
Expanded(
child: user.history.isNotEmpty
? ListView.separated(
separatorBuilder: (context, index) {
return const Divider(height: 1);
},
itemCount: user.history.length,
itemBuilder: (_, index) {
return HistoryItemWidget(
history: user.history[index],
index: index,
);
},
)
: const Text(
'Nenhuma operação recente.',
key: Key('HistoryEmpty'),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/models/operation.dart | import 'package:tests_in_flutter/classes/validate_factory.dart';
import 'operation_result.dart';
// Operation Class
enum OperationType {
deposit,
withdraw,
}
class Operation {
Operation({
required this.balance,
required this.value,
required this.type,
});
final double balance;
final double value;
final OperationType type;
// Validate and operate
OperationResult doOperation() {
return ValidationFactory(this).validate();
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/models/operation_result.dart | import 'history.dart';
// Class that results in the operation, the message and the story
class OperationResult {
OperationResult({
required this.message,
required this.result,
required this.history,
});
final String message;
final double result;
final History history;
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/models/models.dart | export 'history.dart';
export 'operation.dart';
export 'operation_result.dart';
export 'user.dart';
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/models/user.dart | import 'history.dart';
// User Class
class User {
User({
required this.balance,
this.history = const <History>[],
});
final double balance;
final List<History> history;
User update({
double? balance,
History? history,
}) {
// Get the current list
final list = this.history;
if (history != null) {
// Add new operation to list
list.add(history);
}
// Sorts the list from newest to oldest
this.history.sort(
(a, b) => b.dateTime.compareTo(a.dateTime),
);
// Create a new user with updated data
return User(
balance: balance ?? this.balance,
history: list,
);
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/models/history.dart | import 'operation.dart';
// Class that records user operations
class History {
History({
required this.type,
required this.dateTime,
required this.value,
});
final OperationType type;
final DateTime dateTime;
final double value;
// Defines the title of the operation by its type
String get description =>
type == OperationType.deposit ? 'Depósito' : 'Saque';
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/classes/validate_factory.dart | import 'package:tests_in_flutter/classes/withdraw_validation.dart';
import 'package:tests_in_flutter/models/operation.dart';
import 'deposit_validation.dart';
import '../models/operation_result.dart';
// Factory created to validate according to operation
class ValidationFactory {
ValidationFactory(this.operation);
final Operation operation;
OperationResult validate() {
switch (operation.type) {
case OperationType.deposit:
return DepositValidation().validate(
balance: operation.balance,
value: operation.value,
);
case OperationType.withdraw:
return WithdrawValidation().validate(
balance: operation.balance,
value: operation.value,
);
}
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/classes/classes.dart | export 'deposit_validation.dart';
export 'validate_factory.dart';
export 'withdraw_validation.dart';
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/classes/withdraw_validation.dart | import 'package:tests_in_flutter/models/history.dart';
import 'package:tests_in_flutter/models/operation.dart';
import '../error/failure.dart';
import '../models/operation_result.dart';
// Validate the withdrawal operation
class WithdrawValidation {
OperationResult validate({required double balance, required double value}) {
if (value == 0.0 || value < 0.0) {
throw Failure(message: 'Não é posssível sacar esse valor.');
}
if (value > balance) {
throw Failure(message: 'Saldo insuficiente.');
}
return OperationResult(
message: 'Saque realizado com sucesso',
result: balance - value,
history: History(
type: OperationType.withdraw,
dateTime: DateTime.now(),
value: value,
),
);
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/classes/deposit_validation.dart | import 'package:tests_in_flutter/models/history.dart';
import 'package:tests_in_flutter/models/operation.dart';
import 'package:tests_in_flutter/models/operation_result.dart';
import '../error/failure.dart';
// Validate the deposit operation
class DepositValidation {
OperationResult validate({required double balance, required double value}) {
if (value == 0.0 || value < 0.0) {
throw Failure(message: 'Não é posssível depositar esse valor.');
}
return OperationResult(
message: 'Depósito realizado com sucesso',
result: balance + value,
history: History(
type: OperationType.deposit,
dateTime: DateTime.now(),
value: value,
),
);
}
}
| 0 |
mirrored_repositories/tests_in_flutter/lib | mirrored_repositories/tests_in_flutter/lib/error/failure.dart | // Error Handling Class
class Failure implements Exception {
Failure({this.message = ''});
final String message;
}
| 0 |
mirrored_repositories/tests_in_flutter/test | mirrored_repositories/tests_in_flutter/test/pages/home_page_test.dart | import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tests_in_flutter/pages/pages.dart';
void main() {
testWidgets('Test initial state', (tester) async {
await _createWidget(
tester: tester,
widget: const HomePage(),
);
expect(find.text('Saldo disponível'), findsOneWidget);
expect(
find.byKey(
const Key('BalanceKey'),
),
findsOneWidget,
);
expect(find.text('Depositar'), findsOneWidget);
expect(find.text('Sacar'), findsOneWidget);
expect(find.text('Nenhuma operação recente.'), findsOneWidget);
});
testWidgets('Test deposit action', (tester) async {
// render widget
await _createWidget(
tester: tester,
widget: const HomePage(),
);
// found the deposit button
final depositButton = find.text('Depositar');
// tap action
await tester.tap(depositButton);
await tester.pumpAndSettle();
// showed bottomSheet
expect(find.byType(OperationPage), findsOneWidget);
// sound text box
final operationValue = find.byKey(
const Key('OperationValueKey'),
);
// typed 100
await tester.enterText(operationValue, '100');
// waited animation
await tester.pumpAndSettle();
final operationContinue = find.byKey(
const Key('OperationContinue'),
);
// clicked on 'Continue'
await tester.tap(operationContinue);
// waited animation
await tester.pumpAndSettle();
// success confirm with snackBar
expect(find.text('Depósito realizado com sucesso'), findsOneWidget);
});
}
// widget renderized in test with pump
Future<void> _createWidget({
required WidgetTester tester,
required Widget widget,
}) async {
await tester.pumpWidget(
MaterialApp(
home: widget,
),
);
await tester.pump();
}
| 0 |
mirrored_repositories/tests_in_flutter/test | mirrored_repositories/tests_in_flutter/test/classes/validate_factory_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:tests_in_flutter/classes/classes.dart';
import 'package:tests_in_flutter/models/models.dart';
void main() {
test('Validate when type is Deposity', () {
final validationFactory = ValidationFactory(
Operation(
balance: 100.0,
value: 150.0,
type: OperationType.deposit,
),
);
final response = validationFactory.validate();
expect(response.history.type, OperationType.deposit);
});
test('Validate when type is Withdraw', () {
final validationFactory = ValidationFactory(
Operation(
balance: 150.0,
value: 50.0,
type: OperationType.withdraw,
),
);
final response = validationFactory.validate();
expect(
response.history.type,
OperationType.withdraw,
);
});
}
| 0 |
mirrored_repositories/tests_in_flutter/test | mirrored_repositories/tests_in_flutter/test/classes/deposit_validation_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:tests_in_flutter/classes/classes.dart';
import 'package:tests_in_flutter/error/failure.dart';
import 'package:tests_in_flutter/models/models.dart';
void main() {
test('Test validation with value zero', () {
final depositValidation = DepositValidation();
expect(
() => depositValidation.validate(
balance: 0.0,
value: 0.0,
),
throwsA(
isA<Failure>(),
),
);
});
test('Test validation with value is Negative', () {
final depositValidation = DepositValidation();
expect(
() => depositValidation.validate(
balance: 0.0,
value: -100.0,
),
throwsA(
isA<Failure>(),
),
);
});
test('Test when result is ok', () {
final depositValidation = DepositValidation();
OperationResult response = depositValidation.validate(
balance: 0.0,
value: 100.0,
);
expect(
response.result,
100.0,
);
expect(
response.history.type,
OperationType.deposit,
);
expect(
response.message,
'Depósito realizado com sucesso',
);
});
}
| 0 |
mirrored_repositories/tests_in_flutter/test | mirrored_repositories/tests_in_flutter/test/classes/withdraw_validation_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:tests_in_flutter/classes/classes.dart';
import 'package:tests_in_flutter/error/failure.dart';
import 'package:tests_in_flutter/models/models.dart';
void main() {
test('Test validation with value zero', () {
final withdrawValidation = WithdrawValidation();
expect(
() => withdrawValidation.validate(
balance: 0.0,
value: 0.0,
),
throwsA(
isA<Failure>(),
),
);
});
test('Test validation with value is Negative', () {
final withdrawValidation = WithdrawValidation();
expect(
() => withdrawValidation.validate(
balance: 0.0,
value: -100.0,
),
throwsA(
isA<Failure>(),
),
);
});
test('Test validation when balance is zero', () {
final withdrawValidation = WithdrawValidation();
expect(
() => withdrawValidation.validate(
balance: 0.0,
value: 10.0,
),
throwsA(
isA<Failure>(),
),
);
});
test('Test when result is ok', () {
final withdrawValidation = WithdrawValidation();
OperationResult response = withdrawValidation.validate(
balance: 150.0,
value: 100.0,
);
expect(
response.result,
50.0,
);
expect(
response.history.type,
OperationType.withdraw,
);
expect(
response.message,
'Saque realizado com sucesso',
);
});
}
| 0 |
mirrored_repositories/tests_in_flutter/test | mirrored_repositories/tests_in_flutter/test/errors/failure_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:tests_in_flutter/error/failure.dart';
void main() {
group('Test throw', () {
test('Exception Failure with message', () {
void function() {
throw Failure(message: 'Falha executada');
}
expect(
function,
throwsA(
isA<Failure>(),
),
);
});
test('Exception Failure without message', () {
void function() {
throw Failure();
}
expect(
function,
throwsA(
isA<Failure>(),
),
);
});
test('Failure message', () {
final failure = Failure(message: 'Falha Executada');
expect(
failure.message,
'Falha Executada',
);
});
});
test('Failure without message', () {
final failure = Failure();
expect(
failure.message,
'',
);
});
}
| 0 |
mirrored_repositories/tests_in_flutter | mirrored_repositories/tests_in_flutter/test_driver/app.dart | import 'package:flutter_driver/driver_extension.dart';
import 'package:tests_in_flutter/main.dart' as app;
void main() {
enableFlutterDriverExtension();
app.main();
}
| 0 |
mirrored_repositories/tests_in_flutter | mirrored_repositories/tests_in_flutter/test_driver/app_test.dart | import 'package:flutter_driver/flutter_driver.dart' as dr;
import 'package:flutter_test/flutter_test.dart';
import 'package:intl/intl.dart';
void main() {
final DateFormat dateFormatter = DateFormat('d/M/y');
group('Should test the deposit operation', () {
late dr.FlutterDriver driver;
setUpAll(() async {
driver = await dr.FlutterDriver.connect();
});
tearDownAll(() {
driver.close();
});
test('Should deposit value with success', () async {
final depositButton = dr.find.byValueKey('DepositButton');
final balance = dr.find.byValueKey('BalanceKey');
final historyEmpty = dr.find.byValueKey('HistoryEmpty');
expect(await driver.getText(balance), 'R\$ 0,00');
expect(await driver.getText(historyEmpty), 'Nenhuma operação recente.');
await driver.tap(depositButton);
await driver.waitFor(
dr.find.byType('OperationPage'),
);
final operationTextField = dr.find.byValueKey('OperationValueKey');
await driver.tap(operationTextField);
await driver.enterText('5000');
final continueButton = dr.find.byValueKey('OperationContinue');
await driver.tap(continueButton);
await driver.waitFor(
dr.find.byType('HomePage'),
);
expect(await driver.getText(balance), 'R\$ 50,00');
final historyTitle = dr.find.byValueKey('HistoryTitle0');
expect(await driver.getText(historyTitle), 'Depósito');
final historySubtitle = dr.find.byValueKey('HistorySubtitle0');
expect(await driver.getText(historySubtitle), 'R\$ 50,00');
final date = dateFormatter.format(
DateTime.now(),
);
final historyDate = dr.find.byValueKey('HistoryDate0');
expect(await driver.getText(historyDate), date);
});
test('Should deposit value with error', () async {
final depositButton = dr.find.byValueKey('DepositButton');
final balance = dr.find.byValueKey('BalanceKey');
expect(await driver.getText(balance), 'R\$ 50,00');
await driver.tap(depositButton);
await driver.waitFor(
dr.find.byType('OperationPage'),
);
final operationTextField = dr.find.byValueKey('OperationValueKey');
await driver.tap(operationTextField);
await driver.enterText('0');
final continueButton = dr.find.byValueKey('OperationContinue');
await driver.tap(continueButton);
await driver.waitFor(
dr.find.byType('AlertDialog'),
);
final errorMessage = dr.find.byValueKey('ErrorMessage');
expect(
await driver.getText(errorMessage),
'Não é posssível depositar esse valor.',
);
final okButton = dr.find.byValueKey('OkButton');
await driver.tap(okButton);
await driver.waitFor(
dr.find.byType('OperationPage'),
);
final close = dr.find.byValueKey('CloseOperation');
await driver.tap(close);
await driver.waitFor(
dr.find.byType('HomePage'),
);
expect(await driver.getText(balance), 'R\$ 50,00');
});
});
group('Should test the withdraw operation', () {
late dr.FlutterDriver driver;
setUpAll(() async {
driver = await dr.FlutterDriver.connect();
});
tearDownAll(() {
driver.close();
});
test('Should withdraw value with success', () async {
final depositButton = dr.find.byValueKey('WithdrawButton');
final balance = dr.find.byValueKey('BalanceKey');
expect(await driver.getText(balance), 'R\$ 50,00');
await driver.tap(depositButton);
await driver.waitFor(
dr.find.byType('OperationPage'),
);
final operationTextField = dr.find.byValueKey('OperationValueKey');
await driver.tap(operationTextField);
await driver.enterText('1000');
final continueButton = dr.find.byValueKey('OperationContinue');
await driver.tap(continueButton);
await driver.waitFor(
dr.find.byType('HomePage'),
);
expect(await driver.getText(balance), 'R\$ 40,00');
final historyTitle = dr.find.byValueKey('HistoryTitle0');
expect(await driver.getText(historyTitle), 'Saque');
final historySubtitle = dr.find.byValueKey('HistorySubtitle0');
expect(await driver.getText(historySubtitle), 'R\$ 10,00');
final date = dateFormatter.format(
DateTime.now(),
);
final historyDate = dr.find.byValueKey('HistoryDate0');
expect(await driver.getText(historyDate), date);
});
test('Should withdraw value with error 0', () async {
final depositButton = dr.find.byValueKey('WithdrawButton');
final balance = dr.find.byValueKey('BalanceKey');
expect(await driver.getText(balance), 'R\$ 40,00');
await driver.tap(depositButton);
await driver.waitFor(
dr.find.byType('OperationPage'),
);
final operationTextField = dr.find.byValueKey('OperationValueKey');
await driver.tap(operationTextField);
await driver.enterText('0');
final continueButton = dr.find.byValueKey('OperationContinue');
await driver.tap(continueButton);
await driver.waitFor(
dr.find.byType('AlertDialog'),
);
final errorMessage = dr.find.byValueKey('ErrorMessage');
expect(
await driver.getText(errorMessage),
'Não é posssível sacar esse valor.',
);
final okButton = dr.find.byValueKey('OkButton');
await driver.tap(okButton);
await driver.waitFor(
dr.find.byType('OperationPage'),
);
final close = dr.find.byValueKey('CloseOperation');
await driver.tap(close);
await driver.waitFor(
dr.find.byType('HomePage'),
);
expect(await driver.getText(balance), 'R\$ 40,00');
});
test('Should withdraw value with error balance', () async {
final depositButton = dr.find.byValueKey('WithdrawButton');
final balance = dr.find.byValueKey('BalanceKey');
expect(await driver.getText(balance), 'R\$ 40,00');
await driver.tap(depositButton);
await driver.waitFor(
dr.find.byType('OperationPage'),
);
final operationTextField = dr.find.byValueKey('OperationValueKey');
await driver.tap(operationTextField);
await driver.enterText('5000');
final continueButton = dr.find.byValueKey('OperationContinue');
await driver.tap(continueButton);
await driver.waitFor(
dr.find.byType('AlertDialog'),
);
final errorMessage = dr.find.byValueKey('ErrorMessage');
expect(await driver.getText(errorMessage), 'Saldo insuficiente.');
final okButton = dr.find.byValueKey('OkButton');
await driver.tap(okButton);
await driver.waitFor(
dr.find.byType('OperationPage'),
);
final close = dr.find.byValueKey('CloseOperation');
await driver.tap(close);
await driver.waitFor(
dr.find.byType('HomePage'),
);
expect(await driver.getText(balance), 'R\$ 40,00');
});
});
}
| 0 |
mirrored_repositories/phone_authentication | mirrored_repositories/phone_authentication/lib/Login.dart | import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class LoginInPage extends StatefulWidget {
@override
_LoginInPageState createState() => _LoginInPageState();
}
class _LoginInPageState extends State<LoginInPage> {
String phoneNo;
String smsSent;
String verificationID;
// TODO Create Verify Phone Function
Future<void> verifyPhone() async {
final PhoneCodeAutoRetrievalTimeout autoRetrievalTimeout = (String verID) {
this.verificationID = verID;
};
final PhoneCodeSent smsCodeSent = (String verID, [int forceCodeResend]) {
this.verificationID = verID;
// after code sent, we call smsCodeDialog() method
smsCodeDialog(context).then((value) {
print('Code Sent');
});
};
final PhoneVerificationCompleted verificationCompleted =
(AuthCredential auth) {
print('Verification Complete');
};
final PhoneVerificationFailed verificationFailed =
(FirebaseAuthException e) {
print('Verification Failed');
print('${e.message}');
};
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: this.phoneNo,
timeout: const Duration(seconds: 5),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: smsCodeSent,
codeAutoRetrievalTimeout: autoRetrievalTimeout,
);
}
// TODO Create SMS Code Dialog Function
Future<bool> smsCodeDialog(BuildContext context) async {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Enter SMS Code'),
content: TextField(
onChanged: (value) {
this.smsSent = value;
},
),
contentPadding: EdgeInsets.all(10.0),
actions: [
RaisedButton(
onPressed: () {
var user = FirebaseAuth.instance.currentUser;
if (user != null) {
Navigator.of(context).pop();
Navigator.pushReplacementNamed(context, '/Logout');
} else {
Navigator.of(context).pop();
// here signIn() method will be called
signIn(smsSent);
}
},
child: Text('Done'),
),
],
);
},
);
}
//TODO Create Sign In Function
Future<void> signIn(String smsCode) async {
// FirebaseAuth.instance.signInWithPhoneNumber(phoneNo).then((user) {
// Navigator.pushReplacementNamed(context, '/LoginPage');
// }).catchError((e) {
// print(e);
// });
final AuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationID,
smsCode: smsCode,
);
await FirebaseAuth.instance.signInWithCredential(credential).then((user) {
Navigator.pushReplacementNamed(context, '/LogoutPage');
}).catchError((e) {
print(e);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Login Page'),
),
body: Padding(
padding: EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Phone Authentication',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
),
SizedBox(height: 40.0),
Text('Format: [+][country code][subscriber number]'),
SizedBox(height: 40.0),
TextField(
cursorColor: Colors.black,
style: TextStyle(fontSize: 18.0, color: Colors.black),
maxLength: 13,
onChanged: (value) {
this.phoneNo = value;
},
decoration: InputDecoration(
fillColor: Colors.orange.withOpacity(0.1),
filled: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
labelText: 'Phone Number',
labelStyle: TextStyle(
fontSize: 16.0,
),
prefixIcon: Icon(Icons.phone),
),
),
SizedBox(height: 20.0),
RaisedButton(
onPressed: verifyPhone,
color: Colors.orangeAccent,
child: Text('Verify', style: TextStyle(fontSize: 17.0)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/phone_authentication | mirrored_repositories/phone_authentication/lib/Logout.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class LogoutPage extends StatefulWidget {
@override
_LogoutPageState createState() => _LogoutPageState();
}
class _LogoutPageState extends State<LogoutPage> {
String uid = '';
getUid() {}
@override
void initState() {
this.uid = '';
try {
var user = FirebaseAuth.instance.currentUser;
setState(() {
this.uid = user.uid;
});
} catch (e) {
print(e);
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('Logout Page'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(child: Text('You are now Logged In as:\n\n$uid')),
SizedBox(height: 20.0),
OutlineButton(
borderSide: BorderSide(
color: Colors.red,
style: BorderStyle.solid,
width: 3.0,
),
child: Text('Logout'),
onPressed: () {
FirebaseAuth.instance.signOut().then((action) {
Navigator.pushReplacementNamed(context, '/Login');
}).catchError((e) {
print(e);
});
},
)
],
),
);
}
}
| 0 |
mirrored_repositories/phone_authentication | mirrored_repositories/phone_authentication/lib/main.dart | import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'Login.dart';
import 'Logout.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primaryColor: Colors.orange),
home: LoginInPage(),
routes: {
'/Login': (_) => LoginInPage(),
'/Logout': (_) => LogoutPage(),
},
);
}
}
| 0 |
mirrored_repositories/phone_authentication | mirrored_repositories/phone_authentication/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:phone_authentication/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 | mirrored_repositories/FlutterExampleApps/main.dart | void main() {
print("Flutter is amazing");
print(
"Flutter Example apps repo is the collections of awesome apps built with flutter");
}
| 0 |
mirrored_repositories/Flutter-Theme-Changer | mirrored_repositories/Flutter-Theme-Changer/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_theme_changer/models/ThemeNotifier.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'screens/Home.dart';
void main() async {
WidgetsFlutterBinding
.ensureInitialized(); //required to use platform channels to call native code.
SharedPreferences prefs = await SharedPreferences.getInstance();
bool themeBool = prefs.getBool("isDark") ?? false; //null check
runApp(
ChangeNotifierProvider(
create: (BuildContext context) => ThemeProvider(isDark: themeBool),
child: MainWidget(),
),
);
}
class MainWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Wrapping MaterialApp with Consumer makes the ThemeProvider available throughout the app.
return Consumer<ThemeProvider>(builder: (context, themeProvider, child) {
return MaterialApp(
title: 'Flutter Theme',
home: HomeScreen(),
theme: themeProvider.getTheme,
debugShowCheckedModeBanner: false,
);
});
}
}
| 0 |
mirrored_repositories/Flutter-Theme-Changer/lib | mirrored_repositories/Flutter-Theme-Changer/lib/models/ThemeNotifier.dart | import 'package:flutter/material.dart';
import 'package:flutter_theme_changer/themes/Themes.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ThemeProvider extends ChangeNotifier {
late ThemeData _selectedTheme;
late SharedPreferences prefs;
ThemeProvider({bool isDark: false}) {
this._selectedTheme = isDark ? darkTheme : lightTheme;
}
ThemeData get getTheme => _selectedTheme;
Future<void> changeTheme() async {
prefs = await SharedPreferences.getInstance();
if (_selectedTheme == darkTheme) {
_selectedTheme = lightTheme;
await prefs.setBool("isDark", false);
} else {
_selectedTheme = darkTheme;
await prefs.setBool("isDark", true);
}
//notifying all the listeners(consumers) about the change.
notifyListeners();
}
}
| 0 |
mirrored_repositories/Flutter-Theme-Changer/lib | mirrored_repositories/Flutter-Theme-Changer/lib/themes/Themes.dart | import 'package:flutter/material.dart';
//LightTheme
ThemeData lightTheme = ThemeData(
brightness: Brightness.light,
primaryColor: Colors.white,
textTheme: lightTextTheme,
);
TextStyle lightTextStyle = TextStyle(
fontSize: 20,
color: Colors.black,
);
TextTheme lightTextTheme = TextTheme(
bodyText1: lightTextStyle,
);
//DarkTheme
ThemeData darkTheme = ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.black,
);
TextStyle darkTextStyle = TextStyle(
fontSize: 20,
color: Colors.white,
);
TextTheme darkTextTheme = TextTheme(
bodyText1: lightTextStyle,
);
| 0 |
mirrored_repositories/Flutter-Theme-Changer/lib | mirrored_repositories/Flutter-Theme-Changer/lib/screens/Home.dart | import 'package:flutter/material.dart';
import 'package:flutter_theme_changer/models/ThemeNotifier.dart';
import 'package:flutter_theme_changer/themes/Themes.dart';
import 'package:provider/provider.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
ThemeProvider themeProvider =
Provider.of<ThemeProvider>(context, listen: false);
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: Image.asset(themeProvider.getTheme == darkTheme
? 'assets/moon.png'
: 'assets/sun.png'),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.2,
),
Switch(
value: themeProvider.getTheme == darkTheme,
activeColor: themeProvider.getTheme == darkTheme
? Colors.white
: Colors.black,
onChanged: (d) {
themeProvider.changeTheme();
})
],
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Theme-Changer | mirrored_repositories/Flutter-Theme-Changer/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:flutter_theme_changer/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/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/map_page.dart | import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_location_marker/flutter_map_location_marker.dart';
import 'package:latlong2/latlong.dart';
import 'package:vasttrafik_nara/common.dart';
import 'package:vasttrafik_nara/env.dart';
import 'package:vasttrafik_nara/models.dart';
import 'package:vasttrafik_nara/stop_page.dart';
class MapPage extends StatefulWidget {
final Line line;
final JourneyDetail detail;
final String lineDirection;
const MapPage(
{super.key,
required this.line,
required this.lineDirection,
required this.detail});
@override
State<MapPage> createState() => _MapPageState();
}
class _MapPageState extends State<MapPage> {
DateTime? lastUpdated;
LivePosition? vehiclePosition;
var mapController = MapController();
Timer? timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
this.setState(() {
// To change bus indicator even if no new data is available
this.lastUpdated = DateTime.now();
});
fetchData();
});
trackEvent('Page Shown', {
'Page Name': 'Map',
});
}
@override
dispose() {
super.dispose();
timer?.cancel();
}
fetchData() async {
// final lowerLeft = Coordinate(
// widget.stops.map((e) => e.stop.lat).reduce((a, b) => a < b ? a : b),
// widget.stops.map((e) => e.stop.lon).reduce((a, b) => a < b ? a : b),
// );
// final upperRight = Coordinate(
// widget.stops.map((e) => e.stop.lat).reduce((a, b) => a > b ? a : b),
// widget.stops.map((e) => e.stop.lon).reduce((a, b) => a > b ? a : b),
// );
if (Env.useAltCredentials) {
final pos = await vasttrafikApi
.getRealtimeVehiclePosition(widget.detail.journeyGid);
if (this.mounted) {
this.setState(() {
this.vehiclePosition = pos;
});
}
} else {
final res =
await vasttrafikApi.getVehiclePosition(widget.detail.journeyRef);
if (this.mounted) {
this.setState(() {
this.vehiclePosition = res;
});
}
}
}
Widget buildOpenStreetMap() {
final stopCoords = widget.detail.stops
.map((e) => LatLng(e.stopArea.lat, e.stopArea.lon))
.toList();
final journeyCoords = widget.detail.coordinates
.map((e) => LatLng(e.latitude, e.longitude))
.toList();
final isRecent = this.vehiclePosition != null &&
this
.vehiclePosition!
.updatedAt
.isAfter(DateTime.now().subtract(Duration(minutes: 2)));
var initial = CameraFit.coordinates(
coordinates: stopCoords,
padding: EdgeInsets.only(top: 20, bottom: 50, left: 20, right: 20));
return FlutterMap(
mapController: mapController,
options: MapOptions(initialCameraFit: initial),
children: [
TileLayer(
urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
userAgentPackageName: 'vasttrafik_nara.flown.io',
),
PolylineLayer(
polylines: [
Polyline(
strokeWidth: 7,
points: journeyCoords,
color: convertHexToColor(widget.line.bgColor),
),
],
),
MarkerLayer(
markers: [
...stopCoords.asMap().entries.map((it) {
final stop = widget.detail.stops[it.key];
return Marker(
point: it.value,
height: 12,
width: 12,
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StopPage(stop: stop.stopArea),
),
);
},
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: convertHexToColor(widget.line.bgColor),
width: 2,
),
color: convertHexToColor(widget.line.fgColor),
borderRadius: BorderRadius.circular(12),
),
),
),
);
}),
],
),
CurrentLocationLayer(),
if (this.vehiclePosition != null)
AnimatedLocationMarkerLayer(
style: LocationMarkerStyle(
markerSize: Size(30, 30),
marker: Container(
decoration: BoxDecoration(
color: convertHexToColor(widget.line.bgColor),
borderRadius: BorderRadius.circular(100),
),
child: isRecent
? Icon(
Icons.train,
color: convertHexToColor(widget.line.fgColor),
)
: CupertinoActivityIndicator(
color: convertHexToColor(widget.line.fgColor),
),
),
),
position: LocationMarkerPosition(
latitude: vehiclePosition!.lat,
longitude: vehiclePosition!.lon,
accuracy: 0,
)),
SafeArea(
child: Stack(
children: [
Positioned(
left: 20,
bottom: 20,
child: Wrap(
spacing: 10,
children: [
ElevatedButton(
onPressed: () async {
try {
final position = await getCurrentLocation(context)
.timeout(Duration(seconds: 5));
mapController.move(
LatLng(position.latitude, position.longitude),
16);
} catch (err) {
print('Location error');
}
},
child: const Icon(
Icons.my_location,
),
),
ElevatedButton(
onPressed: () async {
mapController.fitCamera(initial);
},
child: const Icon(
Icons.polyline,
),
),
if (vehiclePosition != null)
ElevatedButton(
onPressed: () async {
mapController.move(
LatLng(
vehiclePosition!.lat, vehiclePosition!.lon),
16);
},
child: const Icon(
Icons.train,
),
),
],
),
),
],
),
),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.line.name + ' ' + widget.lineDirection,
),
),
body: buildOpenStreetMap(),
);
}
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/home_page.dart | import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:geolocator/geolocator.dart';
import 'package:vasttrafik_nara/common.dart';
import 'package:vasttrafik_nara/models.dart';
import 'package:vasttrafik_nara/stop_page.dart';
var gothenburgLocation = Coordinate(57.7068421, 11.9704796);
var lindholmenLocation = Coordinate(57.7063737, 11.9401539);
var defaultLocation = gothenburgLocation;
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var fetchComplete = false;
List<StopArea> nearbyStops = [];
var isSearching = false;
Position? currentLocation;
@override
initState() {
super.initState();
fetchData().then((item) {
trackEvent('Page Shown', {
'Page Name': 'Home',
'Shown Stop Count': item.$1?.length ?? 0,
'Uses Device Location': item.$2 != null ? 'Yes' : 'No',
'Distance Away': item.$3 ?? null,
});
});
}
Future<(List<StopArea>?, Position?, double?)> fetchData() async {
Future? authPromise;
if (vasttrafikApi.authToken == null) {
authPromise = Future.wait(
[vasttrafikApi.authorize(true), vasttrafikApi.authorize(false)]);
}
double? distanceAway;
try {
var position =
await getCurrentLocation(context).timeout(Duration(seconds: 5));
distanceAway = Geolocator.distanceBetween(
position.latitude,
position.longitude,
defaultLocation.latitude,
defaultLocation.longitude);
if (distanceAway < 200 * 1000) {
this.currentLocation = position;
} else {
print(
"Far from Gothenburg (${distanceAway.round()}, not using current location");
}
} catch (error, stack) {
var details = FlutterErrorDetails(exception: error, stack: stack);
FlutterError.presentError(details);
print('Error getting location. Details above');
trackEvent('Error Triggered', {
'Error Message': 'Could not get location',
'Thrown Error': error.toString(),
'Thrown Stack': stack.toString(),
});
}
List<StopArea>? stops;
try {
var currentLocation = this.currentLocation == null
? defaultLocation
: Coordinate(
this.currentLocation!.latitude, this.currentLocation!.longitude);
if (authPromise != null) {
await authPromise;
}
stops = await vasttrafikApi.getNearby(currentLocation);
this.setState(() {
this.nearbyStops = stops!;
this.fetchComplete = true;
});
} catch (error, stack) {
var details = FlutterErrorDetails(exception: error, stack: stack);
FlutterError.presentError(details);
trackEvent('Error Triggered', {
'Error Message': 'Could not get stops',
'Thrown Error': error.toString(),
'Thrown Stack': stack.toString(),
});
print('Error getting vasttrafik stops');
}
return (stops, this.currentLocation, distanceAway);
}
final _controller = TextEditingController();
hexColor(hexStr) {
var hex = 'FF' + hexStr.substring(1);
var numColor = int.parse(hex, radix: 16);
return Color(numColor);
}
@override
Widget build(BuildContext context) {
var items = <StopHeadingItem>[];
nearbyStops.forEach((stop) {
items.add(StopHeadingItem(stop, currentLocation, context));
});
var listView = ListView.builder(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return item.build();
});
var loader = Padding(
padding: EdgeInsets.all(20.0),
child: Center(
child: Column(children: <Widget>[
CupertinoActivityIndicator(animating: true, radius: 15.0)
])));
var mainCmp;
if (!this.fetchComplete) {
mainCmp = loader;
} else if (this.nearbyStops.length == 0) {
mainCmp = Padding(
padding: EdgeInsets.all(20.0),
child: Center(
child: Column(children: <Widget>[
Text(
"No stops nearby",
style: TextStyle(fontSize: 16),
)
])));
} else {
mainCmp = listView;
}
var typeAhead = TypeAheadField(
hideKeyboardOnDrag: true,
hideOnLoading: true,
controller: _controller,
hideOnEmpty: true,
builder: (context, controller, focusNode) {
return TextField(
controller: controller,
focusNode: focusNode,
decoration: InputDecoration(
hintText: 'Search',
border: InputBorder.none,
prefixIcon: Icon(Icons.search),
),
);
},
suggestionsCallback: (pattern) async {
pattern = pattern.trim();
var stops =
pattern.isNotEmpty ? await vasttrafikApi.search(pattern) : null;
return stops;
},
itemBuilder: (context, stop) {
return ListTile(
title: Text(stop.name),
);
},
onSelected: (stop) {
_controller.clear();
FocusScope.of(context).unfocus();
trackEvent('Stop Search Result Tapped', {
'Stop Name': stop.name,
'Stop Id': stop.id,
'Search Query': _controller.text
});
Navigator.push(
context,
MaterialPageRoute(builder: (context) => StopPage(stop: stop)),
);
},
);
return Scaffold(
appBar: AppBar(
title: SizedBox(height: 50, child: typeAhead),
actions: <Widget>[
IconButton(
icon: Icon(Icons.refresh),
color: Theme.of(context).colorScheme.onBackground,
tooltip: 'Refresh',
onPressed: () {
_onRefresh();
},
),
],
),
body: mainCmp);
}
_onRefresh() async {
this.setState(() {
this.nearbyStops = [];
this.fetchComplete = false;
});
await fetchData();
}
}
class Choice {
const Choice({this.title, this.icon});
final String? title;
final IconData? icon;
}
const List<Choice> choices = const <Choice>[
const Choice(title: 'Car', icon: Icons.directions_car),
const Choice(title: 'Bicycle', icon: Icons.directions_bike),
const Choice(title: 'Boat', icon: Icons.directions_boat),
const Choice(title: 'Bus', icon: Icons.directions_bus),
const Choice(title: 'Train', icon: Icons.directions_railway),
const Choice(title: 'Walk', icon: Icons.directions_walk),
];
class StopHeadingItem {
final StopArea stop;
final BuildContext context;
final Position? currentLocation;
StopHeadingItem(this.stop, this.currentLocation, this.context);
Widget build() {
var name = stop.name;
var offset = currentLocation == null && !kDebugMode
? null
: Geolocator.distanceBetween(
stop.lat,
stop.lon,
this.currentLocation?.latitude ?? defaultLocation.latitude,
this.currentLocation?.longitude ?? defaultLocation.longitude);
return ListTile(
onTap: () {
FocusScope.of(context).unfocus();
Navigator.push(
context,
MaterialPageRoute(builder: (context) => StopPage(stop: this.stop)),
);
},
trailing: Text(offset != null ? "${offset.round()} m" : ''),
title: Padding(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(
child: AutoSizeText(
name,
overflow: TextOverflow.ellipsis,
maxLines: 1,
minFontSize: 16.0,
style: Theme.of(context).textTheme.titleLarge!,
),
),
]),
),
);
}
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/vasttrafik.dart | import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:vasttrafik_nara/env.dart';
import 'package:vasttrafik_nara/models.dart';
class VasttrafikApi {
String? authToken;
String? authTokenAlt;
String basePlaneraResaApi = "https://ext-api.vasttrafik.se/pr/v4";
String basePlaneraResaApiInternal =
"https://ext-api.vasttrafik.se/pr/v4-int'";
String baseGeoApi = "https://ext-api.vasttrafik.se/geo/v2";
String baseInformationApi = "https://ext-api.vasttrafik.se/ts/v1";
String baseFposApi =
"https://ext-api.vasttrafik.se/fpos/v1"; // Only supported with alt credentials
Future<List<StopArea>> search(query) async {
String path = "/locations/by-text";
String queryString = "?q=$query&types=stoparea";
String url = basePlaneraResaApi + path + queryString;
var res = await _callApi(url);
var json = res.body;
var map = jsonDecode(json);
return List<StopArea>.from(
map['results'].map((it) => StopArea(it)).toList());
}
Future<StopAreaDetail> stopAreaDetail(String stopAreaId) async {
String path =
"/StopAreas/$stopAreaId?includeStopPoints=true&includeGeometry=true&srid=4326";
String url = baseGeoApi + path;
var res = await _callApi(url);
var json = res.body;
var map = jsonDecode(json);
return StopAreaDetail(map['stopArea']);
}
Future<LivePositionInternal?> getRealtimeVehiclePosition(
String journeyId) async {
// Realtime. Not available unless used with internal credentials found in
// togo app.
String url = "${baseFposApi}/positions/${journeyId}";
var res = await _callApi(url, true);
var json = res.body;
var map = jsonDecode(json);
if (map['status'] == 404) {
return null;
}
return LivePositionInternal(map);
}
Future<List<LivePosition>> getAllVehicles(
Coordinate lowerLeft, Coordinate upperRight) async {
String url =
'$basePlaneraResaApi/positions?lowerLeftLat=${lowerLeft.latitude}&lowerLeftLong=${lowerLeft.longitude}&upperRightLat=${upperRight.latitude}&upperRightLong=${upperRight.longitude}&limit=200';
var res = await _callApi(url);
var json = res.body;
var map = jsonDecode(json);
return List<LivePosition>.from(map.map((it) => LivePosition(it)));
}
Future<LivePosition?> getVehiclePosition(String journeyRefId) async {
if (authTokenAlt != null) {
return await getRealtimeVehiclePosition(journeyRefId);
}
final highestValidLatitude = 90;
final lowestValidLatitude = -90;
final highestValidLongitude = 180;
final lowestValidLongitude = -180;
String url =
'$basePlaneraResaApi/positions?lowerLeftLat=${lowestValidLatitude}&lowerLeftLong=${lowestValidLongitude}&upperRightLat=${highestValidLatitude}&upperRightLong=${highestValidLongitude}&detailsReferences=${journeyRefId}&limit=1';
var res = await _callApi(url);
var json = res.body;
var map = jsonDecode(json);
return map.isEmpty ? null : LivePosition(map[0]);
}
Future<List<StopArea>> getNearby(Coordinate latLng) async {
String path = "/locations/by-coordinates";
String queryString =
"?latitude=${latLng.latitude}&longitude=${latLng.longitude}&radiusInMeters=50000&limit=20&types=stoparea";
String url = basePlaneraResaApi + path + queryString;
var res = await _callApi(url);
var json = res.body;
var map = jsonDecode(json);
return List<StopArea>.from(
map['results'].map((it) => StopArea(it)).toList());
}
Future<JourneyDetail> getJourneyDetails2(
String stopAreaId, String ref) async {
String url =
basePlaneraResaApi + '/stop-areas/$stopAreaId/departures/$ref/details';
//String url = basePlaneraResaApi + '/journeys/${ref}/details';
var res = await _callApi(url);
var json = res.body;
var map = jsonDecode(json);
return JourneyDetail(map);
}
Future<JourneyDetail> getJourneyDetails(String ref) async {
//String url2 = basePlaneraResaApi + '/stop-areas/$stopAreaId/departures/$ref/details';
String url = basePlaneraResaApi +
'/journeys/${ref}/details?includes=servicejourneycoordinates';
var res = await _callApi(url);
var json = res.body;
var map = jsonDecode(json);
return JourneyDetail(map);
}
Future<List<Deparature>> getDepartures(String stopId) async {
String path = "/stop-areas/${stopId}/departures";
String queryString = "?maxDeparturesPerLineAndDirection=10&limit=20";
String url = basePlaneraResaApi + path + queryString;
var res = await _callApi(url);
var json = res.body;
var map = jsonDecode(json);
return List<Deparature>.from(map['results'].map((it) => Deparature(it)));
}
_callApi(String url, [bool altInternal = false]) async {
Uri uri = Uri.parse(url);
var token = altInternal ? authTokenAlt : authToken;
var result = http.get(uri, headers: {'Authorization': "Bearer ${token!}"});
return result;
}
Future authorizeAll() async {
await authorize(false);
await authorize(true);
}
Future authorize(bool alt) async {
var clientId = alt ? Env.vasttrafikClientIdAlt : Env.vasttrafikClientId;
var clientSecret =
alt ? Env.vasttrafikClientSecretAlt : Env.vasttrafikClientSecret;
Uri uri = Uri.parse('https://ext-api.vasttrafik.se/token');
var res = await http.post(
uri,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body:
'grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}',
);
if (res.statusCode != 200) {
print(res);
throw Exception('Failed to authorize. Internal? ${alt}');
}
var json = jsonDecode(res.body);
if (alt) {
authTokenAlt = json['access_token'];
} else {
authToken = json['access_token'];
}
}
Future<List<Information>> getStopInformation(String stopId) async {
var path = '/traffic-situations/stoparea/${stopId}';
var url = baseInformationApi + path;
var res = await _callApi(url);
var json = jsonDecode(res.body);
return List<Information>.from(json.map((it) => Information(it)));
}
Future<List<Information>> getJourneyInformation(String lineId) async {
var path = '/traffic-situations/line/${lineId}';
//path = '/traffic-situations';
var url = baseInformationApi + path;
var res = await _callApi(url);
var json = jsonDecode(res.body);
return List<Information>.from(json.map((it) => Information(it)));
}
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/stop_page.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vasttrafik_nara/common.dart';
import 'package:vasttrafik_nara/information_page.dart';
import 'package:vasttrafik_nara/journey_page.dart';
import 'package:vasttrafik_nara/models.dart';
import 'package:vasttrafik_nara/stop_map_page.dart';
class StopPage extends StatefulWidget {
StopPage({Key? key, required this.stop}) : super(key: key);
final StopArea stop;
@override
_StopPageState createState() => _StopPageState();
}
class _StopPageState extends State<StopPage> {
List<Information> informationItems = [];
List<Deparature> journeys = [];
@override
initState() {
super.initState();
fetchInformation();
fetchData().then((list) {
trackEvent('Page Shown', {
'Page Name': 'Stop',
'Stop Name': widget.stop.name,
'Stop Id': widget.stop.id,
'Shown Journey Count': list.length,
});
});
}
Future<void> fetchInformation() async {
var stopId = this.widget.stop.id;
var info = await vasttrafikApi.getStopInformation(stopId);
if (mounted) {
this.setState(() {
this.informationItems = info;
});
}
}
Future<List<Deparature>> fetchData() async {
var stopId = this.widget.stop.id;
var journeys = await vasttrafikApi.getDepartures(stopId);
journeys.sort((a, b) {
return a.estimatedTime.compareTo(b.estimatedTime);
});
if (mounted) {
this.setState(() {
this.journeys = journeys;
});
}
return journeys;
}
Widget buildItem(Deparature departure) {
List<Widget> subtitleComponents = [];
var directionName = departure.direction;
final viaIndex = directionName.indexOf(' via ');
var textStyle = TextStyle(
color: convertHexToColor(departure.fgColor),
fontSize: 18.0,
fontWeight: FontWeight.bold);
final subTextStyle = TextStyle(color: textStyle.color);
if (departure.track != null) {
subtitleComponents.add(Text(departure.track!, style: subTextStyle));
}
final isDelayed =
!departure.estimatedTime.isAtSameMomentAs(departure.plannedTime);
if (isDelayed) {
subtitleComponents.add(Text(
formatDepartureTime(departure.plannedTime, false),
style: subTextStyle.copyWith(
decoration: TextDecoration.lineThrough,
decorationColor: subTextStyle.color!.withOpacity(0.8),
decorationThickness: 2)));
}
subtitleComponents.add(Text(
formatDepartureTime(departure.estimatedTime, false),
style: subTextStyle));
if (departure.isCancelled) {
subtitleComponents.add(Text('Cancelled',
style: subTextStyle.copyWith(
color: Colors.red, backgroundColor: Colors.white)));
}
if (viaIndex > 0) {
final via =
directionName.substring(viaIndex, directionName.length).trim();
subtitleComponents.add(Text(via, style: subTextStyle));
directionName = directionName.substring(0, viaIndex).trim();
}
return Container(
decoration: BoxDecoration(
color: convertHexToColor(departure.bgColor),
),
child: ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => JourneyPage(departure.line,
departure.direction, departure.journeyRefId)),
);
},
leading: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [Text(departure.shortName, style: textStyle)],
),
minLeadingWidth: 60,
title: Text(directionName, style: textStyle),
subtitle: Wrap(spacing: 5, children: [
for (var it in subtitleComponents) it,
]),
trailing: Text(formatDepartureTime(departure.estimatedTime, true),
style: textStyle),
));
}
@override
Widget build(BuildContext context) {
var loader = Padding(
padding: EdgeInsets.all(20.0),
child: Center(
child: Column(children: <Widget>[
CupertinoActivityIndicator(animating: true, radius: 15.0)
])));
return Scaffold(
appBar: AppBar(
title: Text(this.widget.stop.name),
actions: [
if (informationItems.isNotEmpty)
IconButton(
icon: const Icon(Icons.info_rounded),
tooltip: 'Info',
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => InformationPage(
informations: informationItems,
),
),
);
},
),
IconButton(
icon: const Icon(Icons.map),
tooltip: 'Map',
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StopMapPage(
stop: widget.stop,
),
),
);
},
),
],
),
body: this.journeys.length == 0
? loader
: ListView.builder(
itemCount: journeys.length,
itemBuilder: (context, index) {
final item = journeys[index];
return buildItem(item);
}),
);
}
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/generated_plugin_registrant.dart | //
// Generated file. Do not edit.
//
// ignore_for_file: lines_longer_than_80_chars
import 'package:flutter_keyboard_visibility_web/flutter_keyboard_visibility_web.dart';
import 'package:shared_preferences_web/shared_preferences_web.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
// ignore: public_member_api_docs
void registerPlugins(Registrar registrar) {
FlutterKeyboardVisibilityPlugin.registerWith(registrar);
SharedPreferencesPlugin.registerWith(registrar);
registrar.registerMessageHandler();
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/information_page.dart | import 'package:flutter/material.dart';
import 'package:vasttrafik_nara/common.dart';
import 'package:vasttrafik_nara/models.dart';
class InformationPage extends StatefulWidget {
final List<Information> informations;
const InformationPage({super.key, required this.informations});
@override
State<InformationPage> createState() => _InformationPageState();
}
class _InformationPageState extends State<InformationPage> {
@override
void initState() {
super.initState();
trackEvent('Page Shown', {
'Page Name': 'Information',
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Information'),
actions: [],
),
body: ListView(
children: widget.informations.map((it) {
return ListTile(
title: Text(it.title),
subtitle: Text(it.description),
);
}).toList(),
),
);
}
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/stop_map_page.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_location_marker/flutter_map_location_marker.dart';
import 'package:latlong2/latlong.dart';
import 'package:vasttrafik_nara/common.dart';
import 'package:vasttrafik_nara/home_page.dart';
import 'package:vasttrafik_nara/journey_page.dart';
import 'package:vasttrafik_nara/models.dart';
class StopMapPage extends StatefulWidget {
final StopArea stop;
const StopMapPage({super.key, required this.stop});
@override
State<StopMapPage> createState() => _MapPageState();
}
class _MapPageState extends State<StopMapPage> {
StopAreaDetail? stopDetail;
List<LivePosition> vehiclePositions = [];
var mapController = MapController();
Timer? timer;
var mostRecentTimer = DateTime.now();
@override
void initState() {
super.initState();
fetch();
timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
fetchData();
});
trackEvent('Page Shown', {
'Page Name': 'Stop Map',
});
}
@override
dispose() {
super.dispose();
timer?.cancel();
}
fetch() async {
var res = await vasttrafikApi.stopAreaDetail(widget.stop.id);
if (mounted) {
setState(() {
stopDetail = res;
});
mapController.move(LatLng(res.lat, res.lon), 17);
}
}
fetchData() async {
var before = DateTime.now();
final lowerLeft = Coordinate(
mapController.camera.visibleBounds.southWest.latitude,
mapController.camera.visibleBounds.southWest.longitude,
);
final upperRight = Coordinate(
mapController.camera.visibleBounds.northWest.latitude,
mapController.camera.visibleBounds.northEast.longitude,
);
final pos = await vasttrafikApi.getAllVehicles(lowerLeft, upperRight);
if (this.mounted && before.isAfter(mostRecentTimer)) {
mostRecentTimer = before;
this.setState(() {
this.vehiclePositions = pos;
});
}
}
Widget buildOpenStreetMap() {
final stopPoints = stopDetail?.stopPoints ?? [];
return FlutterMap(
mapController: mapController,
options: MapOptions(
initialCenter:
LatLng(defaultLocation.latitude, defaultLocation.longitude),
initialZoom: 13),
children: [
TileLayer(
urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
userAgentPackageName: 'vasttrafik_nara.flown.io',
),
MarkerLayer(
markers: [
...stopPoints.asMap().entries.map((point) {
return Marker(
rotate: true,
point: LatLng(point.value.lat, point.value.lon),
child: Container(
child: Center(
child: Text(
point.value.name,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Theme.of(context).colorScheme.onSurface,
),
)),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(20),
),
),
);
}),
],
),
CurrentLocationLayer(),
for (var vehiclePosition in vehiclePositions)
AnimatedLocationMarkerLayer(
key: ValueKey(vehiclePosition.journeyRef),
style: LocationMarkerStyle(
markerSize: Size(30, 30),
marker: InkWell(
onTap: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => JourneyPage(
vehiclePosition.line,
vehiclePosition.lineDirection,
vehiclePosition.journeyRef)),
);
},
child: Container(
decoration: BoxDecoration(
color: convertHexToColor(vehiclePosition.bgColor),
borderRadius: BorderRadius.circular(100),
),
child: Center(
child: Text(vehiclePosition.lineName,
style: TextStyle(
color:
convertHexToColor(vehiclePosition.fbColor)))),
),
),
),
position: LocationMarkerPosition(
latitude: vehiclePosition.lat,
longitude: vehiclePosition.lon,
accuracy: 0,
),
),
SafeArea(
child: Stack(
children: [
Positioned(
left: 20,
bottom: 20,
child: Wrap(
spacing: 10,
children: [
ElevatedButton(
onPressed: () async {
try {
final position = await getCurrentLocation(context)
.timeout(Duration(seconds: 5));
mapController.move(
LatLng(position.latitude, position.longitude),
16);
} catch (err) {
print('Location error');
}
},
child: const Icon(
Icons.my_location,
),
),
ElevatedButton(
onPressed: () async {
if (stopPoints.isNotEmpty) {
final coords = stopPoints
.map((e) => LatLng(e.lat, e.lon))
.toList();
mapController.fitCamera(
CameraFit.coordinates(
padding: EdgeInsets.all(40),
coordinates: coords,
minZoom: 16),
);
} else {
mapController.move(
LatLng(widget.stop.lat, widget.stop.lon), 16);
}
},
child: const Icon(
Icons.location_on,
),
),
],
),
),
],
),
),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
this.widget.stop.name,
),
),
body: buildOpenStreetMap(),
);
}
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/journey_page.dart | import 'package:vasttrafik_nara/common.dart';
import 'package:vasttrafik_nara/information_page.dart';
import 'package:vasttrafik_nara/map_page.dart';
import 'package:vasttrafik_nara/models.dart';
import 'package:vasttrafik_nara/stop_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class JourneyPage extends StatefulWidget {
final Line line;
final String lineDirection;
final String journeyRef;
JourneyPage(this.line, this.lineDirection, this.journeyRef);
@override
createState() => _JourneyPageState();
}
class _JourneyPageState extends State<JourneyPage> {
List<Information> informationItems = [];
JourneyDetail? journeyDetail;
ScrollController? _scrollController;
bool loading = true;
StopArea? nextStop;
_JourneyPageState();
@override
initState() {
super.initState();
fetchData().then((item) {
trackEvent('Page Shown', {
'Page Name': 'Journey',
'Journey Name': widget.line.name,
//'Journey Direction': widget.line.direction,
'Journey Id': widget.journeyRef,
'Shown Stop Count': item.length
});
}).catchError((error) {
print('Error fetching data $error');
});
}
fetchInformationItems(JourneyDetail detail) async {
if (widget.line.id != null) {
final info = await vasttrafikApi.getJourneyInformation(widget.line.id!);
if (this.mounted) {
this.setState(() {
this.informationItems = info;
});
}
}
}
Future<List<JourneyStop>> fetchData() async {
// Page opened from clicking a vehicle on map etc so we
// find the next stop instead of using the one
var detail = await vasttrafikApi.getJourneyDetails(widget.journeyRef);
fetchInformationItems(detail).catchError((error) {
print('Error fetching information: $error');
});
var stops = detail.stops
.where((it) => it.departureTime.isAfter(DateTime.now()))
.toList();
stops.sort((a, b) => a.departureTime.compareTo(b.departureTime));
var nextStop = stops.firstOrNull?.stopArea ?? detail.stops.last.stopArea;
if (this.mounted) {
this.setState(() {
this.journeyDetail = detail;
this.nextStop = nextStop;
this.loading = false;
});
}
return detail.stops;
}
hexColor(hexStr) {
var hex = 'FF' + hexStr.substring(1);
var numColor = int.parse(hex, radix: 16);
return Color(numColor);
}
@override
Widget build(BuildContext context) {
Color bgColor = convertHexToColor(widget.line.bgColor);
var lum = bgColor.computeLuminance();
final stops = this.journeyDetail?.stops ?? [];
var nextStopIndex = stops
.indexWhere((element) => element.departureTime.isAfter(DateTime.now()));
if (_scrollController == null) {
if (nextStopIndex != -1) {
_scrollController =
ScrollController(initialScrollOffset: nextStopIndex * 56.0);
}
}
var loader = Padding(
padding: EdgeInsets.all(20.0),
child: Center(
child: Column(children: <Widget>[
CupertinoActivityIndicator(animating: true, radius: 15.0)
])));
var listView = loading || this.journeyDetail == null
? loader
: ListView.builder(
itemCount: stops.length,
controller: this._scrollController,
itemBuilder: (context, index) {
final stop = stops[index];
var isRemainingStop = stop.departureTime.isAfter(DateTime.now());
var time = '';
var depTime = stop.departureTime;
time = formatDepartureTime(depTime, false);
var style = TextStyle(
fontSize: 18.0,
color: isRemainingStop
? Theme.of(context).colorScheme.onBackground
: Theme.of(context)
.colorScheme
.onBackground
.withOpacity(0.3),
fontWeight:
index == nextStopIndex ? FontWeight.w900 : FontWeight.w500,
);
return Container(
child: ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StopPage(stop: stop.stopArea),
),
);
},
selected: isRemainingStop,
title: Text(stop.stopArea.name, style: style),
trailing: Text(time, style: style),
));
});
return Scaffold(
appBar: AppBar(
title: Text(widget.line.name + ' ' + widget.lineDirection,
style: TextStyle(color: convertHexToColor(widget.line.fgColor))),
backgroundColor: bgColor,
systemOverlayStyle: lum < 0.7
? SystemUiOverlayStyle.light
: SystemUiOverlayStyle.dark,
iconTheme:
IconThemeData(color: convertHexToColor(widget.line.fgColor)),
actions: [
if (informationItems.isNotEmpty)
IconButton(
icon: const Icon(Icons.info_rounded),
tooltip: 'Info',
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => InformationPage(
informations: informationItems,
),
),
);
},
),
IconButton(
icon: const Icon(Icons.map),
tooltip: 'Map',
onPressed: stops.isEmpty
? null
: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MapPage(
line: widget.line,
lineDirection: widget.lineDirection,
detail: this.journeyDetail!),
),
);
},
),
],
),
body: listView);
}
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/common.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:mixpanel_flutter/mixpanel_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vasttrafik_nara/vasttrafik.dart';
final vasttrafikApi = VasttrafikApi();
late Mixpanel mixpanelInstance;
initMixpanel() async {
mixpanelInstance = await Mixpanel.init(
"563842b985116f25ac9bfdea7b799cf8",
trackAutomaticEvents: true,
);
}
trackEvent(String eventName, [Map<String, dynamic>? props]) {
if (!kDebugMode) {
mixpanelInstance.track(eventName, properties: props);
}
print('Logged: ${eventName}');
}
Future<void> openMap(
BuildContext context, double latitude, double longitude) async {
final googleUrl = Uri.parse(
'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude');
if (await canLaunchUrl(googleUrl)) {
await launchUrl(googleUrl);
} else {
showAlertDialog(context,
title: 'Oops',
message: 'Could not open Google Maps. Make sure it is installed.');
}
}
showAlertDialog(BuildContext context,
{required String title, required String message, Function? action}) {
final actionButton = TextButton(
child: Text('Ok'),
onPressed: () {
action?.call();
},
);
final alert = AlertDialog(
title: Text(title),
content: Text(message),
actions: [
actionButton,
],
);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
Future<Position> getCurrentLocation(BuildContext context) async {
final serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
showAlertDialog(
context,
title: 'Location Services Disabled',
message: 'Enable location services to show stops nearby',
action: () async {
await Geolocator.openLocationSettings();
},
);
return Future.error('Location services are disabled.');
}
var permission = await Geolocator.checkPermission();
if (LocationPermission.denied == permission) {
permission = await Geolocator.requestPermission();
}
if ([LocationPermission.denied, LocationPermission.deniedForever]
.contains(permission)) {
showAlertDialog(
context,
title: 'Location Permission Denied',
message:
'Go to phone settings and allow location permission to show nearby stops.',
action: () async {
await Geolocator.openAppSettings();
},
);
return Future.error('Location permissions are denied');
}
return Geolocator.getCurrentPosition(timeLimit: Duration(seconds: 5));
}
distanceBetween(Position a, Position b) {
return Geolocator.distanceBetween(
a.latitude, a.longitude, b.latitude, b.longitude);
}
String formatDepartureTime(DateTime date, bool relative) {
if (relative) {
var timeDiff = date.difference(DateTime.now());
if (timeDiff.inMinutes < 1) {
return 'Now';
} else if (timeDiff.inMinutes < 60) {
return '${timeDiff.inMinutes}';
}
}
String formattedDate = DateFormat('HH:mm').format(date);
return formattedDate;
}
Color convertHexToColor(String hexStr) {
var hex = 'FF' + hexStr.substring(1);
var numColor = int.parse(hex, radix: 16);
return Color(numColor);
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/models.dart | class Information {
late Map data;
String get situationNumber {
return data['situationNumber'];
}
DateTime get startTime {
return parseVasttrafikDate(data['startTime']);
}
DateTime get endTime {
return parseVasttrafikDate(data['endTime']);
}
String get title {
return data['title'];
}
String get description {
String message = data['description'];
if (message
.startsWith('Sök din resa i appen To Go eller Reseplaneraren. ')) {
message = message.replaceAll(
'Sök din resa i appen To Go eller Reseplaneraren. ', '');
}
return message;
}
String get severity {
return data['severity'];
}
Information(Map data) {
this.data = data;
}
}
class Deparature {
late Map data;
late String name;
late String shortName;
late String direction;
String? track;
late DateTime plannedTime;
late DateTime estimatedTime;
late String bgColor;
late String fgColor;
late StopArea nextStop;
late String stopId;
late String journeyRefId;
Line get line {
return Line(data['serviceJourney']['line']);
}
bool get isCancelled {
return data['isCancelled'] ?? false;
}
String get journeyGid {
return data['serviceJourney']['gid'];
}
Deparature(Map data) {
var service = data['serviceJourney'];
direction = service['direction'];
if (direction.contains(', Påstigning fram')) {
direction = direction.replaceAll(', Påstigning fram', '');
}
var line = service['line'];
name = line['name'];
shortName = line['shortName'];
bgColor = line['backgroundColor'];
fgColor = line['foregroundColor'];
var planned = data['plannedTime'];
var estimated = data['estimatedTime'] ?? planned;
plannedTime = parseVasttrafikDate(planned);
estimatedTime = parseVasttrafikDate(estimated);
journeyRefId = data['detailsReference'];
var stopPoint = data['stopPoint'];
stopId = stopPoint['gid'];
track = stopPoint['platform'];
this.data = data;
}
}
class StopArea {
late Map data;
late String id;
late double lat;
late double lon;
late String name;
StopArea(Map data) {
name = data['name'];
if (name.contains(', Göteborg')) {
name = name.replaceAll(', Göteborg', '');
}
id = data['gid'];
lat = data['latitude'];
lon = data['longitude'] ?? 0;
this.data = data;
}
}
class JourneyDetail {
Map data;
List<JourneyStop> get stops {
final calls = data['tripLegs'][0]['callsOnTripLeg'].where((it) {
// There was some duplicate stops without time and platform etc
var time = it['plannedDepartureTime'] ??
it['estimatedArrivalTime'] ??
it['plannedArrivalTime'] ??
it['estimatedArrivalTime'];
if (time == null) {
print('No time ${it['stopPoint']['name']}');
}
return time != null;
});
return List<JourneyStop>.from(calls.map((it) => JourneyStop(it)));
}
String get journeyRef {
return data['tripLegs'][0]['serviceJourneys'][0]['ref'];
}
String get journeyGid {
return data['tripLegs'][0]['serviceJourneys'][0]['gid'];
}
List<Coordinate> get coordinates {
final coords = data['tripLegs'][0]['serviceJourneys'][0]
['serviceJourneyCoordinates'] ??
[];
return List<Coordinate>.from(
coords.map((it) => Coordinate(it['latitude'], it['longitude'])));
}
JourneyDetail(this.data);
}
class JourneyStop {
late DateTime departureTime;
late String platform;
late String stopPointId;
late StopArea stopArea;
JourneyStop(Map data) {
// Arrival time useful if last stop on journey since there is no departure times for those
var time = data['estimatedDepartureTime'] ??
data['plannedDepartureTime'] ??
data['estimatedArrivalTime'] ??
data['plannedArrivalTime'];
departureTime = time != null ? parseVasttrafikDate(time) : null;
platform = data['plannedPlatform'] ?? null;
stopPointId = data['stopPoint']['gid'];
stopArea = StopArea(data['stopPoint']['stopArea']);
}
}
class StopPoint {
late Map data;
late String id;
late double lat;
late double lon;
late String name;
StopPoint(Map data) {
name = data['designation'];
id = data['gid'];
lat = data['geometry']['northingCoordinate'];
lon = data['geometry']['eastingCoordinate'];
this.data = data;
}
}
class StopAreaDetail {
late Map data;
late String name;
late String id;
late double lat;
late double lon;
late List<StopPoint> stopPoints;
StopAreaDetail(Map data) {
name = data['name'];
id = data['gid'];
lat = data['geometry']['northingCoordinate'];
lon = data['geometry']['eastingCoordinate'];
stopPoints =
List<StopPoint>.from(data['stopPoints'].map((it) => StopPoint(it)));
this.data = data;
}
}
parseVasttrafikDate(String dateStr) {
return DateTime.parse(dateStr).toLocal();
}
class Coordinate {
double latitude;
double longitude;
Coordinate(this.latitude, this.longitude);
}
class Line {
late Map data;
late String name;
late String shortName;
late String bgColor;
late String fgColor;
late String transportMode;
Line(Map data) {
name = data['shortName'] ?? data['name'];
bgColor = data['backgroundColor'];
fgColor = data['foregroundColor'];
transportMode = data['transportMode'];
this.data = data;
}
String? get id {
// Gid not returned when line obtained from geo api
return data['gid'];
}
}
class LivePosition {
late Map data;
late double lat;
late double lon;
late DateTime updatedAt;
Line get line {
return Line(data['line']);
}
String get journeyRef {
return data['detailsReference'];
}
String get bgColor {
return data['line']['backgroundColor'];
}
String get fbColor {
return data['line']['foregroundColor'];
}
String get lineName {
return data['line']['name'] ?? '-';
}
LivePosition(Map data) {
lat = data['latitude'] ?? data['lat'];
lon = data['longitude'] ?? data['long'];
updatedAt = DateTime.now();
this.data = data;
}
String get lineDirection {
return data['direction'];
}
}
class LivePositionInternal extends LivePosition {
late bool atStop;
late double lat;
late double lon;
late double speed;
late DateTime updatedAt;
LivePositionInternal(Map data) : super(data) {
atStop = data['atStop'];
lat = data['lat'];
lon = data['long'];
speed = data['speed'];
updatedAt = parseVasttrafikDate(data['updatedAt']);
}
}
| 0 |
mirrored_repositories/vasttrafik-nara | mirrored_repositories/vasttrafik-nara/lib/main.dart | import 'package:vasttrafik_nara/common.dart';
import 'package:vasttrafik_nara/home_page.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await initMixpanel();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Västtrafik Nära',
theme: ThemeData(),
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.system,
home: MyHomePage(),
);
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example | mirrored_repositories/flutter-objectbox-example/lib/theme.dart | import 'package:flutter/material.dart';
ThemeData createAppTheme(BuildContext context) {
return ThemeData(
appBarTheme: AppBarTheme(
color: const Color(0xFFFAFAFA),
titleTextStyle: Theme.of(context).textTheme.headline6?.copyWith(
color: const Color(0xDD000000),
),
iconTheme: Theme.of(context).iconTheme.copyWith(
color: const Color(0xDD000000),
),
actionsIconTheme: Theme.of(context).iconTheme.copyWith(
color: const Color(0xDD000000),
),
elevation: 0,
),
colorScheme: ColorScheme.fromSwatch(
accentColor: const Color(0xDD000000),
),
);
}
| 0 |
mirrored_repositories/flutter-objectbox-example | mirrored_repositories/flutter-objectbox-example/lib/main.dart | import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_objectbox_example/app/app.dart';
import 'package:flutter_objectbox_example/repository/repository.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
Bloc.observer = AppBlocObserver();
StoreRepository storeRepository = StoreRepository();
await storeRepository.initStore();
runApp(App(storeRepository: storeRepository));
}
| 0 |
mirrored_repositories/flutter-objectbox-example | mirrored_repositories/flutter-objectbox-example/lib/objectbox.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
// This code was generated by ObjectBox. To update it run the generator again:
// With a Flutter package, run `flutter pub run build_runner build`.
// With a Dart package, run `dart run build_runner build`.
// See also https://docs.objectbox.io/getting-started#generate-objectbox-code
// ignore_for_file: camel_case_types
import 'dart:typed_data';
import 'package:flat_buffers/flat_buffers.dart' as fb;
import 'package:objectbox/internal.dart'; // generated code can access "internal" functionality
import 'package:objectbox/objectbox.dart';
import 'entities/expense.dart';
import 'entities/expense_type.dart';
export 'package:objectbox/objectbox.dart'; // so that callers only have to import this file
final _entities = <ModelEntity>[
ModelEntity(
id: const IdUid(1, 7217190552277395867),
name: 'Expense',
lastPropertyId: const IdUid(5, 2663765814440690905),
flags: 0,
properties: <ModelProperty>[
ModelProperty(
id: const IdUid(1, 1527225490299843563),
name: 'id',
type: 6,
flags: 1),
ModelProperty(
id: const IdUid(2, 259747063648648230),
name: 'amount',
type: 8,
flags: 0),
ModelProperty(
id: const IdUid(3, 6298206329088241903),
name: 'note',
type: 9,
flags: 0),
ModelProperty(
id: const IdUid(4, 6041035703793031442),
name: 'date',
type: 12,
flags: 0),
ModelProperty(
id: const IdUid(5, 2663765814440690905),
name: 'expenseTypeId',
type: 11,
flags: 520,
indexId: const IdUid(1, 1723235740853294332),
relationTarget: 'ExpenseType')
],
relations: <ModelRelation>[],
backlinks: <ModelBacklink>[]),
ModelEntity(
id: const IdUid(3, 687153607940665596),
name: 'ExpenseType',
lastPropertyId: const IdUid(3, 7116122762776967856),
flags: 0,
properties: <ModelProperty>[
ModelProperty(
id: const IdUid(1, 3927516500936406884),
name: 'id',
type: 6,
flags: 1),
ModelProperty(
id: const IdUid(2, 6521466187271375061),
name: 'identifier',
type: 9,
flags: 0),
ModelProperty(
id: const IdUid(3, 7116122762776967856),
name: 'name',
type: 9,
flags: 2080,
indexId: const IdUid(2, 4340554622386498839))
],
relations: <ModelRelation>[],
backlinks: <ModelBacklink>[
ModelBacklink(name: 'expenses', srcEntity: 'Expense', srcField: '')
])
];
/// Open an ObjectBox store with the model declared in this file.
Store openStore(
{String? directory,
int? maxDBSizeInKB,
int? fileMode,
int? maxReaders,
bool queriesCaseSensitiveDefault = true,
String? macosApplicationGroup}) =>
Store(getObjectBoxModel(),
directory: directory,
maxDBSizeInKB: maxDBSizeInKB,
fileMode: fileMode,
maxReaders: maxReaders,
queriesCaseSensitiveDefault: queriesCaseSensitiveDefault,
macosApplicationGroup: macosApplicationGroup);
/// ObjectBox model definition, pass it to [Store] - Store(getObjectBoxModel())
ModelDefinition getObjectBoxModel() {
final model = ModelInfo(
entities: _entities,
lastEntityId: const IdUid(3, 687153607940665596),
lastIndexId: const IdUid(2, 4340554622386498839),
lastRelationId: const IdUid(0, 0),
lastSequenceId: const IdUid(0, 0),
retiredEntityUids: const [7620952543243995255],
retiredIndexUids: const [],
retiredPropertyUids: const [
3845386833114662251,
4882907920823481202,
1850253826698914775
],
retiredRelationUids: const [],
modelVersion: 5,
modelVersionParserMinimum: 5,
version: 1);
final bindings = <Type, EntityDefinition>{
Expense: EntityDefinition<Expense>(
model: _entities[0],
toOneRelations: (Expense object) => [object.expenseType],
toManyRelations: (Expense object) => {},
getId: (Expense object) => object.id,
setId: (Expense object, int id) {
object.id = id;
},
objectToFB: (Expense object, fb.Builder fbb) {
final noteOffset = fbb.writeString(object.note);
fbb.startTable(6);
fbb.addInt64(0, object.id);
fbb.addFloat64(1, object.amount);
fbb.addOffset(2, noteOffset);
fbb.addInt64(3, object.date.microsecondsSinceEpoch * 1000);
fbb.addInt64(4, object.expenseType.targetId);
fbb.finish(fbb.endTable());
return object.id;
},
objectFromFB: (Store store, ByteData fbData) {
final buffer = fb.BufferContext(fbData);
final rootOffset = buffer.derefObject(0);
final object = Expense(
id: const fb.Int64Reader().vTableGet(buffer, rootOffset, 4, 0),
amount:
const fb.Float64Reader().vTableGet(buffer, rootOffset, 6, 0),
note: const fb.StringReader(asciiOptimization: true)
.vTableGet(buffer, rootOffset, 8, ''),
date: DateTime.fromMicrosecondsSinceEpoch(
(const fb.Int64Reader().vTableGet(buffer, rootOffset, 10, 0) /
1000)
.round()));
object.expenseType.targetId =
const fb.Int64Reader().vTableGet(buffer, rootOffset, 12, 0);
object.expenseType.attach(store);
return object;
}),
ExpenseType: EntityDefinition<ExpenseType>(
model: _entities[1],
toOneRelations: (ExpenseType object) => [],
toManyRelations: (ExpenseType object) => {
RelInfo<Expense>.toOneBacklink(5, object.id,
(Expense srcObject) => srcObject.expenseType): object.expenses
},
getId: (ExpenseType object) => object.id,
setId: (ExpenseType object, int id) {
object.id = id;
},
objectToFB: (ExpenseType object, fb.Builder fbb) {
final identifierOffset = fbb.writeString(object.identifier);
final nameOffset = fbb.writeString(object.name);
fbb.startTable(4);
fbb.addInt64(0, object.id);
fbb.addOffset(1, identifierOffset);
fbb.addOffset(2, nameOffset);
fbb.finish(fbb.endTable());
return object.id;
},
objectFromFB: (Store store, ByteData fbData) {
final buffer = fb.BufferContext(fbData);
final rootOffset = buffer.derefObject(0);
final object = ExpenseType(
id: const fb.Int64Reader().vTableGet(buffer, rootOffset, 4, 0),
identifier: const fb.StringReader(asciiOptimization: true)
.vTableGet(buffer, rootOffset, 6, ''),
name: const fb.StringReader(asciiOptimization: true)
.vTableGet(buffer, rootOffset, 8, ''));
InternalToManyAccess.setRelInfo(
object.expenses,
store,
RelInfo<Expense>.toOneBacklink(
5, object.id, (Expense srcObject) => srcObject.expenseType),
store.box<ExpenseType>());
return object;
})
};
return ModelDefinition(model, bindings);
}
/// [Expense] entity fields to define ObjectBox queries.
class Expense_ {
/// see [Expense.id]
static final id = QueryIntegerProperty<Expense>(_entities[0].properties[0]);
/// see [Expense.amount]
static final amount =
QueryDoubleProperty<Expense>(_entities[0].properties[1]);
/// see [Expense.note]
static final note = QueryStringProperty<Expense>(_entities[0].properties[2]);
/// see [Expense.date]
static final date = QueryIntegerProperty<Expense>(_entities[0].properties[3]);
/// see [Expense.expenseType]
static final expenseType =
QueryRelationToOne<Expense, ExpenseType>(_entities[0].properties[4]);
}
/// [ExpenseType] entity fields to define ObjectBox queries.
class ExpenseType_ {
/// see [ExpenseType.id]
static final id =
QueryIntegerProperty<ExpenseType>(_entities[1].properties[0]);
/// see [ExpenseType.identifier]
static final identifier =
QueryStringProperty<ExpenseType>(_entities[1].properties[1]);
/// see [ExpenseType.name]
static final name =
QueryStringProperty<ExpenseType>(_entities[1].properties[2]);
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/expense_type/expense_type.dart | export 'bloc/expense_type_bloc.dart';
export 'view/expense_type_view.dart';
export 'view/expense_type_page.dart';
export 'widgets/expense_type_card.dart';
| 0 |
mirrored_repositories/flutter-objectbox-example/lib/expense_type | mirrored_repositories/flutter-objectbox-example/lib/expense_type/view/expense_type_view.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_objectbox_example/expense_type/expense_type.dart';
import 'package:flutter_objectbox_example/form_inputs/form_inputs.dart';
import 'package:formz/formz.dart';
class ExpenseTypeView extends StatelessWidget {
const ExpenseTypeView({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocListener(
listeners: [
BlocListener<ExpenseTypeFormBloc, ExpenseTypeFormState>(
listenWhen: (previous, current) => previous.status != current.status,
listener: (context, state) {
if (state.status.isSubmissionFailure) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content:
Text(state.errorMessage ?? 'Something went wrong!'),
),
);
}
},
),
BlocListener<ExpenseTypeBloc, ExpenseTypeState>(
listenWhen: (previous, current) => previous.status != current.status,
listener: (context, state) {
if (state.status == ExpenseTypeStatus.failure) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
const SnackBar(
content: Text('Something went wrong while loading types!'),
),
);
}
},
),
],
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text('Add an identifier', style: TextStyle(fontSize: 18)),
_IdentifierTextField(),
const SizedBox(height: 16.0),
const Text('Add a name', style: TextStyle(fontSize: 18)),
_NameTextField(),
const SizedBox(height: 16.0),
_SubmitButton(),
const SizedBox(height: 16.0),
const Divider(),
const SizedBox(height: 16.0),
const Text(
'AVAILABLE EXPENSE TYPES',
style: TextStyle(fontSize: 18),
),
const SizedBox(height: 24.0),
_ExpenseTypesList(),
],
),
),
);
}
}
class _IdentifierTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<ExpenseTypeFormBloc, ExpenseTypeFormState>(
buildWhen: (previous, current) =>
previous.identifier != current.identifier,
builder: (context, state) {
return TextField(
key: const Key('expenseTypeForm_identifier_textField'),
onChanged: (value) =>
context.read<ExpenseTypeFormBloc>().add(IdentifierChanged(value)),
decoration: InputDecoration(
hintText: 'Identifier',
errorText:
state.identifier.invalid ? 'Must be within 5 characters' : null,
),
);
},
);
}
}
class _NameTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<ExpenseTypeFormBloc, ExpenseTypeFormState>(
buildWhen: (previous, current) => previous.name != current.name,
builder: (context, state) {
return TextField(
key: const Key('expenseTypeForm_name_textField'),
onChanged: (value) =>
context.read<ExpenseTypeFormBloc>().add(NameChanged(value)),
decoration: InputDecoration(
hintText: 'Name',
errorText:
state.name.invalid ? 'Must be within 10 characters' : null,
),
);
},
);
}
}
class _SubmitButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<ExpenseTypeFormBloc, ExpenseTypeFormState>(
buildWhen: (previous, current) => previous.status != current.status,
builder: (context, state) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
primary: const Color(0xFF252525),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
onPressed: state.status.isValidated
? () => context
.read<ExpenseTypeFormBloc>()
.add(ExpenseTypeFormSubmitted())
: null,
child: state.status.isSubmissionInProgress
? const CircularProgressIndicator()
: const Text(
'SAVE',
style: TextStyle(fontSize: 18),
),
);
},
);
}
}
class _ExpenseTypesList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<ExpenseTypeBloc, ExpenseTypeState>(
builder: (context, state) {
if (state.expenseTypes.isEmpty) {
if (state.status == ExpenseTypeStatus.loading) {
return const Center(
child: CircularProgressIndicator(),
);
} else if (state.status != ExpenseTypeStatus.success) {
return const SizedBox();
} else {
return const SizedBox(
height: 150,
child: Center(
child: Text(
'No Expense Type available',
style: TextStyle(fontSize: 16),
),
),
);
}
}
return GridView.builder(
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
),
itemCount: state.expenseTypes.length,
itemBuilder: (context, index) {
final expenseType = state.expenseTypes.elementAt(index);
return ExpenseTypeCard(expenseType: expenseType);
},
);
},
);
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib/expense_type | mirrored_repositories/flutter-objectbox-example/lib/expense_type/view/expense_type_page.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_objectbox_example/expense_type/expense_type.dart';
import 'package:flutter_objectbox_example/form_inputs/form_inputs.dart';
import 'package:flutter_objectbox_example/repository/repository.dart';
class ExpenseTypePage extends StatelessWidget {
const ExpenseTypePage({super.key});
static Route<void> route() => MaterialPageRoute<void>(
builder: (_) => const ExpenseTypePage(),
fullscreenDialog: true,
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('EXPENSE TYPES'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: MultiBlocProvider(
providers: [
BlocProvider<ExpenseTypeFormBloc>(
create: (context) => ExpenseTypeFormBloc(
expenseTypeRepository: context.read<ExpenseTypeRepository>(),
),
),
BlocProvider<ExpenseTypeBloc>(
create: (context) => ExpenseTypeBloc(
expenseTypeRepository: context.read<ExpenseTypeRepository>(),
)..add(ExpenseTypeSubscriptionRequested()),
),
],
child: const ExpenseTypeView(),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib/expense_type | mirrored_repositories/flutter-objectbox-example/lib/expense_type/widgets/expense_type_card.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_objectbox_example/entities/entities.dart';
import 'package:flutter_objectbox_example/expense_type/expense_type.dart';
class ExpenseTypeCard extends StatelessWidget {
const ExpenseTypeCard({super.key, required this.expenseType});
final ExpenseType expenseType;
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
top: 0,
right: 0,
child: InkWell(
onTap: () => context
.read<ExpenseTypeBloc>()
.add(ExpenseTypeDeleted(expenseType.id)),
child: const CircleAvatar(
radius: 10,
backgroundColor: Color(0xFFDEDEDE),
child: Icon(
Icons.close,
size: 12,
color: Colors.black,
),
),
),
),
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
expenseType.identifier,
style: const TextStyle(fontSize: 30),
),
const SizedBox(height: 12),
Text(
expenseType.name,
style: const TextStyle(
fontSize: 15,
color: Color(0xDD232323),
overflow: TextOverflow.ellipsis,
),
),
],
),
),
],
);
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib/expense_type | mirrored_repositories/flutter-objectbox-example/lib/expense_type/bloc/expense_type_state.dart | part of 'expense_type_bloc.dart';
enum ExpenseTypeStatus { initial, loading, success, failure }
class ExpenseTypeState extends Equatable {
const ExpenseTypeState({
this.status = ExpenseTypeStatus.initial,
this.expenseTypes = const [],
});
final ExpenseTypeStatus status;
final List<ExpenseType> expenseTypes;
@override
List<Object> get props => [status, expenseTypes];
ExpenseTypeState copyWith({
ExpenseTypeStatus? status,
List<ExpenseType>? expenseTypes,
}) {
return ExpenseTypeState(
status: status ?? this.status,
expenseTypes: expenseTypes ?? this.expenseTypes,
);
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib/expense_type | mirrored_repositories/flutter-objectbox-example/lib/expense_type/bloc/expense_type_bloc.dart | import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter_objectbox_example/entities/entities.dart';
import 'package:flutter_objectbox_example/repository/repository.dart';
part 'expense_type_event.dart';
part 'expense_type_state.dart';
class ExpenseTypeBloc extends Bloc<ExpenseTypeEvent, ExpenseTypeState> {
ExpenseTypeBloc({
required ExpenseTypeRepository expenseTypeRepository,
}) : _expenseTypeRepository = expenseTypeRepository,
super(const ExpenseTypeState()) {
on<ExpenseTypeSubscriptionRequested>(_onSubscriptionRequested);
on<ExpenseTypeDeleted>(_onExpenseTypeDeleted);
}
final ExpenseTypeRepository _expenseTypeRepository;
Future<void> _onSubscriptionRequested(
ExpenseTypeSubscriptionRequested event,
Emitter<ExpenseTypeState> emit,
) async {
emit(state.copyWith(status: ExpenseTypeStatus.loading));
await emit.forEach<List<ExpenseType>>(
_expenseTypeRepository.getAllExpenseTypeStream(),
onData: (expenseTypes) => state.copyWith(
status: ExpenseTypeStatus.success,
expenseTypes: expenseTypes,
),
onError: (_, __) => state.copyWith(
status: ExpenseTypeStatus.failure,
),
);
}
void _onExpenseTypeDeleted(
ExpenseTypeDeleted event,
Emitter<ExpenseTypeState> emit,
) {
_expenseTypeRepository.deleteExpenseType(event.id);
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib/expense_type | mirrored_repositories/flutter-objectbox-example/lib/expense_type/bloc/expense_type_event.dart | part of 'expense_type_bloc.dart';
abstract class ExpenseTypeEvent extends Equatable {
const ExpenseTypeEvent();
@override
List<Object> get props => [];
}
class ExpenseTypeSubscriptionRequested extends ExpenseTypeEvent {}
class ExpenseTypeDeleted extends ExpenseTypeEvent {
const ExpenseTypeDeleted(this.id);
final int id;
@override
List<Object> get props => [id];
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/app/app.dart | export 'app_bloc_observer.dart';
export 'view/app.dart';
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/app/app_bloc_observer.dart | // ignore_for_file: avoid_print
import 'package:bloc/bloc.dart';
class AppBlocObserver extends BlocObserver {
@override
void onCreate(BlocBase bloc) {
super.onCreate(bloc);
print('onCreate -- ${bloc.runtimeType}');
}
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
print('onChange -- ${bloc.runtimeType}, $change');
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
print('onError -- ${bloc.runtimeType}, $error, $stackTrace');
super.onError(bloc, error, stackTrace);
}
@override
void onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
print('onTransition -- ${bloc.runtimeType}, $transition');
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib/app | mirrored_repositories/flutter-objectbox-example/lib/app/view/app.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_objectbox_example/expense/expense.dart';
import 'package:flutter_objectbox_example/repository/repository.dart';
import 'package:flutter_objectbox_example/theme.dart';
class App extends StatelessWidget {
const App({super.key, required StoreRepository storeRepository})
: _storeRepository = storeRepository;
final StoreRepository _storeRepository;
@override
Widget build(BuildContext context) {
return RepositoryProvider<StoreRepository>.value(
value: _storeRepository,
child: MultiRepositoryProvider(
providers: [
RepositoryProvider<ExpenseRepository>(
create: (_) => ExpenseRepository(store: _storeRepository.store),
),
RepositoryProvider<ExpenseTypeRepository>(
create: (_) => ExpenseTypeRepository(store: _storeRepository.store),
),
],
child: MaterialApp(
title: 'Flutter Objectbox Example',
debugShowCheckedModeBanner: false,
theme: createAppTheme(context),
home: const ExpensePage(),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/repository/expense_repository.dart | import 'package:flutter_objectbox_example/entities/entities.dart';
import 'package:flutter_objectbox_example/objectbox.g.dart' as objectbox_g;
import 'package:objectbox/objectbox.dart';
/// Repository to perform different operations with [Expense].
class ExpenseRepository {
ExpenseRepository({required this.store});
final Store store;
/// Persists the given [Expense] in the store.
void addExpense(Expense expense, ExpenseType expenseType) {
expense.expenseType.target = expenseType;
store.box<Expense>().put(expense);
}
/// Deletes the [Expense] with the given [id].
void removeExpense(int id) {
store.box<Expense>().remove(id);
}
/// Provides a [Stream] of all expenses.
Stream<List<Expense>> getAllExpenseStream() {
final query = store.box<Expense>().query();
return query
.watch(triggerImmediately: true)
.map<List<Expense>>((query) => query.find());
}
/// Provides a [Stream] of total expense in last 7 days.
Stream<double> expenseInLast7Days() {
final query = store
.box<Expense>()
.query(objectbox_g.Expense_.date.greaterThan(
DateTime.now()
.subtract(const Duration(days: 7))
.microsecondsSinceEpoch *
1000,
))
.watch(triggerImmediately: true);
return query.map<double>((query) => query
.find()
.map<double>((e) => e.amount)
.reduce((value, element) => value + element));
}
/// Provides a [Stream] of all expenses ordered by time.
Stream<List<Expense>> getExpenseSortByTime() {
final query = store.box<Expense>().query()
..order(objectbox_g.Expense_.date, flags: Order.descending);
return query
.watch(triggerImmediately: true)
.map<List<Expense>>((query) => query.find());
}
/// Provides a [Stream] of all expenses ordered by amount.
Stream<List<Expense>> getExpenseSortByAmount() {
final query = store.box<Expense>().query()
..order(objectbox_g.Expense_.amount, flags: Order.descending);
return query
.watch(triggerImmediately: true)
.map<List<Expense>>((query) => query.find());
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/repository/expense_type_repository.dart | import 'package:flutter_objectbox_example/entities/entities.dart';
import 'package:objectbox/objectbox.dart';
/// Repository to perform different operations with [ExpenseType].
class ExpenseTypeRepository {
ExpenseTypeRepository({required this.store});
final Store store;
/// Persists the given [ExpenseType] in the store.
void addExpenseType(ExpenseType expenseType) {
store.box<ExpenseType>().put(expenseType);
}
/// Returns all stored [ExpenseType]s in this Box.
List<ExpenseType> getAllExpenseTypes() {
return store.box<ExpenseType>().getAll();
}
/// Provides a [Stream] of all expense types.
Stream<List<ExpenseType>> getAllExpenseTypeStream() {
final query = store.box<ExpenseType>().query();
return query
.watch(triggerImmediately: true)
.map<List<ExpenseType>>((query) => query.find());
}
/// Deletes the [ExpenseType] with the given [id].
bool deleteExpenseType(int id) {
return store.box<ExpenseType>().remove(id);
}
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/repository/repository.dart | export 'expense_repository.dart';
export 'expense_type_repository.dart';
export 'store_repository.dart';
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/repository/store_repository.dart | import 'package:objectbox/objectbox.dart' as objectbox;
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:flutter_objectbox_example/objectbox.g.dart';
/// Repository to initilialize the ObjectBox Store object
class StoreRepository {
late final objectbox.Store _store;
/// Initializes the ObjectBox Store object.
Future<void> initStore() async {
final appDocumentsDirextory =
await path_provider.getApplicationDocumentsDirectory();
_store = Store(
getObjectBoxModel(),
directory: path.join(appDocumentsDirextory.path, 'expense-db'),
);
return;
}
/// Getter for the store object.
objectbox.Store get store => _store;
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/entities/expense_type.dart | import 'package:flutter_objectbox_example/entities/entities.dart';
import 'package:objectbox/objectbox.dart';
/// {@template expense_type}
/// Expense type entity.
/// {@endtemplate}
@Entity()
class ExpenseType {
/// {@macro expense_type}
ExpenseType({
this.id = 0,
required this.identifier,
required this.name,
});
/// Id of the entity, managed by the Objectbox.
int id;
/// Identifier for the [ExpenseType], generally an emoji.
String identifier;
/// Name for the [ExpenseType], must be unique.
@Unique()
String name;
/// All the expenses linked to this [ExpenseType]
@Backlink()
final expenses = ToMany<Expense>();
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/entities/expense.dart | import 'package:flutter_objectbox_example/entities/entities.dart';
import 'package:objectbox/objectbox.dart';
/// {@template expense}
/// Expense entity.
/// {@endtemplate}
@Entity()
class Expense {
/// {@macro expense}
Expense({
this.id = 0,
required this.amount,
this.note = '',
required this.date,
});
/// Id of the expense entity, managed by Objectbox.
int id;
/// Amount that has been expensed.
double amount;
/// Optional note for the expense.
String note;
/// Date and time when the expense has been noted.
@Property(type: PropertyType.dateNano)
DateTime date;
/// [ExpenseType] of the expense.
final expenseType = ToOne<ExpenseType>();
}
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/entities/entities.dart | export 'expense.dart';
export 'expense_type.dart';
| 0 |
mirrored_repositories/flutter-objectbox-example/lib | mirrored_repositories/flutter-objectbox-example/lib/expense/expense.dart | export 'bloc/expense_bloc.dart';
export 'helpers/date_time_ext.dart';
export 'view/expense_form_page.dart';
export 'view/expense_page.dart';
export 'widgets/expense_tile.dart';
export 'widgets/type_selection_card.dart';
| 0 |
mirrored_repositories/flutter-objectbox-example/lib/expense | mirrored_repositories/flutter-objectbox-example/lib/expense/view/expense_page.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_objectbox_example/expense/expense.dart';
import 'package:flutter_objectbox_example/expense_type/expense_type.dart';
import 'package:flutter_objectbox_example/repository/repository.dart';
class ExpensePage extends StatelessWidget {
const ExpensePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Expense Tracker'),
centerTitle: true,
actions: [
IconButton(
onPressed: () => Navigator.push(context, ExpenseTypePage.route()),
icon: const Icon(Icons.app_registration),
),
],
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: BlocProvider<ExpenseBloc>(
create: (_) =>
ExpenseBloc(expenseRepository: context.read<ExpenseRepository>())
..add(ExpenseListRequested())
..add(ExpenseInLast7DaysRequested()),
child: const ExpenseView(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.push(context, ExpenseFormPage.route()),
child: const Icon(Icons.add),
),
);
}
}
class ExpenseView extends StatelessWidget {
const ExpenseView({super.key});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_LastWeekSpentWidget(),
const SizedBox(height: 16.0),
const Divider(),
const SizedBox(height: 16.0),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'ALL EXPENSES',
style: TextStyle(fontSize: 18),
),
_ExpenseSortToggleWidget(),
],
),
const SizedBox(height: 24.0),
Expanded(
child: BlocBuilder<ExpenseBloc, ExpenseState>(
buildWhen: (previous, current) =>
previous.expenses != current.expenses,
builder: (context, state) {
return ListView.builder(
itemCount: state.expenses.length,
itemBuilder: (context, index) {
final expense = state.expenses.elementAt(index);
return ExpenseTile(expense: expense);
},
);
},
),
),
],
);
}
}
class _LastWeekSpentWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<ExpenseBloc, ExpenseState>(
buildWhen: (previous, current) =>
previous.expenseInLast7Days != current.expenseInLast7Days,
builder: (context, state) {
return SizedBox(
height: 120,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Spent last 7 days',
style: TextStyle(fontSize: 18, color: Colors.black45),
),
const SizedBox(height: 8),
Text(
'₹ ${state.expenseInLast7Days.toStringAsFixed(2)}',
style: const TextStyle(
fontSize: 40,
fontWeight: FontWeight.w500,
),
),
],
),
),
);
},
);
}
}
class _ExpenseSortToggleWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<ExpenseBloc, ExpenseState>(
buildWhen: (previous, current) =>
previous.expenseSort != current.expenseSort,
builder: (context, state) {
return Row(
children: [
const Text(
'Sort by',
style: TextStyle(fontSize: 18),
),
TextButton(
onPressed: () =>
context.read<ExpenseBloc>().add(ToggleExpenseSort()),
child: Row(
children: [
Text(
state.expenseSort.name.toUpperCase(),
style: const TextStyle(fontSize: 17),
),
const SizedBox(width: 4),
const Icon(Icons.code, size: 18),
],
),
),
],
);
},
);
}
}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.