repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/stories-app/lib/core/session
|
mirrored_repositories/stories-app/lib/core/session/manager/session_manager_impl.dart
|
import 'package:encrypt_shared_preferences/provider.dart';
import 'package:jokes_app/core/session/manager/session_manager.dart';
import '../../../common/resource/keys.dart';
class SessionManagerImpl extends SessionManager {
final EncryptedSharedPreferences _preferences;
SessionManagerImpl({
required EncryptedSharedPreferences preferences,
}) : _preferences = preferences;
@override
Future<void> endRemoteSession() async {
//end remote session
}
@override
Future<void> endLocalSession() async {
await _preferences.clear();
}
@override
String get authorization => "Authorization";
@override
int get timeout => 30000;
@override
bool validate(int code) {
if (code >= 200 && code <= 400) {
return true;
} else {
return false;
}
}
@override
String? get accessToken => _preferences.getString(Keys.token) != null
? "Bearer ${_preferences.getString(Keys.token)}"
: null;
}
| 0
|
mirrored_repositories/stories-app/lib/core/session
|
mirrored_repositories/stories-app/lib/core/session/manager/session_manager.dart
|
import '../session.dart';
abstract class SessionManager extends Session {
Future<void> endRemoteSession();
Future<void> endLocalSession();
}
| 0
|
mirrored_repositories/stories-app/lib
|
mirrored_repositories/stories-app/lib/generated/locale_keys.g.dart
|
import 'package:modified_localization/easy_localization.dart';
// This is code generated via package:modified_localization/generate.dart
// Modified by @xaldarof
// See https://github.com/xaldarof/modified-easy-localization
abstract class Strings {
static String get viewMore => 'view_more'.tr();
static String get username => 'username'.tr();
static String get password => 'password'.tr();
static String get dontHaveAccountRegister => 'dont_have_account_register'.tr();
static String get login => 'login'.tr();
static String get stories => 'stories'.tr();
static String get register => 'register'.tr();
static String get publish => 'publish'.tr();
static String get profile => 'profile'.tr();
static String get readCount => 'read_count'.tr();
static String get published => 'published'.tr();
static String get viewReachCount => 'view_reach_count'.tr();
static String get share => 'share'.tr();
static String get about => 'about'.tr();
static String get language => 'language'.tr();
static String get yourStories => 'your_stories'.tr();
static String get somethingWentWrong => 'something_went_wrong'.tr();
static String get title => 'title'.tr();
static String get body => 'body'.tr();
static String get selectLanguage => 'select_language'.tr();
static String get frozen => 'frozen'.tr();
static String get aboutContent => 'about_content'.tr();
static String get yes => 'yes'.tr();
static String get no => 'no'.tr();
static String get doYouWantLogout => 'do_you_want_logout'.tr();
static String get quotes => 'quotes'.tr();
static String get addToQuotes => 'add_to_quotes'.tr();
static String get global => 'global'.tr();
static String get notifications => 'notifications'.tr();
static String get tapToMarkAsRead => 'tap_to_mark_as_read'.tr();
static String get congratulations => 'congratulations'.tr();
static String youReachMoreThanView(String arg0) {
return 'you_reach_more_than_view'.tr(args: [arg0]);
}
static String get reportSent => 'report_sent'.tr();
}
| 0
|
mirrored_repositories/stories-app/lib
|
mirrored_repositories/stories-app/lib/di/app_di.dart
|
import 'package:encrypt_shared_preferences/provider.dart';
import 'package:get_it/get_it.dart';
import 'package:jokes_app/core/session/manager/session_manager.dart';
import 'package:jokes_app/core/session/manager/session_manager_impl.dart';
import 'package:jokes_app/data/api/api_client.dart';
import 'package:jokes_app/data/data_sources/network/auth_network_data_source_impl.dart';
import 'package:jokes_app/data/data_sources/network/global_network_data_source_impl.dart';
import 'package:jokes_app/data/data_sources/cache/profile_cache_data_source_impl.dart';
import 'package:jokes_app/data/data_sources/network/profile_network_data_source_impl.dart';
import 'package:jokes_app/data/data_sources/network/publish_network_data_source_impl.dart';
import 'package:jokes_app/data/data_sources/network/stories_network_data_source_impl.dart';
import 'package:jokes_app/data/data_sources/network/view_story_network_data_source_impl.dart';
import 'package:jokes_app/data/repositories/auth_repository_impl.dart';
import 'package:jokes_app/data/repositories/global_repository_impl.dart';
import 'package:jokes_app/data/repositories/profile_repository_impl.dart';
import 'package:jokes_app/data/repositories/publish_repository_impl.dart';
import 'package:jokes_app/data/repositories/stories_repository_impl.dart';
import 'package:jokes_app/data/repositories/view_story_repository_impl.dart';
import 'package:jokes_app/domain/data_sources/network/auth_network_data_source.dart';
import 'package:jokes_app/domain/data_sources/network/global_network_data_source.dart';
import 'package:jokes_app/domain/data_sources/network/main_network_data_source.dart';
import 'package:jokes_app/domain/data_sources/cache/profile_cache_data_source.dart';
import 'package:jokes_app/domain/data_sources/network/profile_network_data_source.dart';
import 'package:jokes_app/domain/data_sources/network/publish_network_data_source.dart';
import 'package:jokes_app/domain/data_sources/network/story_quotes_network_data_source.dart';
import 'package:jokes_app/domain/data_sources/network/view_story_network_data_source.dart';
import 'package:jokes_app/domain/mappers/category_mapper.dart';
import 'package:jokes_app/domain/mappers/notification_mapper.dart';
import 'package:jokes_app/domain/mappers/profile_mapper.dart';
import 'package:jokes_app/domain/mappers/profile_stats_mapper.dart';
import 'package:jokes_app/domain/mappers/story_mapper.dart';
import 'package:jokes_app/domain/mappers/story_quote_mapper.dart';
import 'package:jokes_app/domain/repositories/auth_repository.dart';
import 'package:jokes_app/domain/repositories/global_repository.dart';
import 'package:jokes_app/domain/repositories/main_repository.dart';
import 'package:jokes_app/domain/repositories/profile_repository.dart';
import 'package:jokes_app/domain/repositories/publish_repository.dart';
import 'package:jokes_app/domain/repositories/story_quotes_repository.dart';
import 'package:jokes_app/domain/repositories/view_story_repository.dart';
import '../data/api/interceptors.dart';
import '../data/data_sources/cache/main_data_source_impl.dart';
import '../data/data_sources/network/main_network_data_source_impl.dart';
import '../data/data_sources/network/story_quotes_network_data_source_impl.dart';
import '../data/repositories/main_repository_impl.dart';
import '../data/repositories/story_quotes_repository_impl.dart';
import '../domain/data_sources/cache/main_data_source.dart';
import '../domain/data_sources/network/stories_network_data_source.dart';
import '../domain/repositories/stories_repository.dart';
final injector = GetIt.instance;
Future<void> setUpDependencies() async {
injector.registerSingleton<EncryptedSharedPreferences>(
await EncryptedSharedPreferences.getInstance());
injector.registerSingleton<SessionManager>(
SessionManagerImpl(preferences: injector.get()));
injector.registerSingleton<AuthInterceptor>(
AuthInterceptor(sessionManager: injector.get()));
injector.registerSingleton<DioClient>(DioClient(injector.get()));
_setUpDataSources();
_setUpRepos();
}
void _setUpRepos() {
injector.registerSingleton<StoriesRepository>(StoriesRepositoryImpl(
networkDataSource: injector.get(),
storyMapper: StoryResponseToUiMapper(),
categoryMapper: CategoryMapper()));
injector.registerSingleton<PublishRepository>(PublishRepositoryImpl(
networkDataSource: injector.get(), categoryMapper: CategoryMapper()));
injector.registerSingleton<AuthRepository>(AuthRepositoryImpl(
networkDataSource: injector.get(), preferences: injector.get()));
injector.registerSingleton<MainRepository>(MainRepositoryImpl(
dataSource: injector.get(),
preferences: injector.get(),
networkDataSource: injector.get()));
injector.registerSingleton<ViewStoryRepository>(
ViewStoryRepositoryImpl(networkDataSource: injector.get()));
injector.registerSingleton<StoryQuotesRepository>(StoryQuotesRepositoryImpl(
networkDataSource: injector.get(), storyQuoteMapper: StoryQuoteMapper()));
injector.registerSingleton<ProfileRepository>(
ProfileRepositoryImpl(
networkDataSource: injector.get(),
profileMapper: UserMapper(),
profileStatsMapper: ProfileStatsMapper(),
storyMapper: StoryResponseToUiMapper(),
categoryMapper: CategoryMapper(),
cacheDataSource: injector.get(),
notificationMapper: NotificationMapper(),
),
);
injector.registerSingleton<GlobalRepository>(GlobalRepositoryImpl(
networkDataSource: injector.get(), userMapper: UserMapper()));
}
void _setUpDataSources() {
injector.registerSingleton<StoriesNetworkDataSource>(
StoriesNetworkDataSourceImpl(client: injector.get()));
injector.registerSingleton<PublishNetworkDataSource>(
PublishNetworkDataSourceImpl(client: injector.get()));
injector.registerSingleton<AuthNetworkDataSource>(
AuthNetworkDataSourceImpl(client: injector.get()));
injector.registerSingleton<MainDataSource>(
MainDataSourceImpl(preferences: injector.get()));
injector.registerSingleton<ProfileNetworkDataSource>(
ProfileNetworkDataSourceImpl(client: injector.get()));
injector.registerSingleton<ViewStoryNetworkDataSource>(
ViewStoryNetworkDataSourceImpl(client: injector.get()));
injector.registerSingleton<ProfileCacheDataSource>(
ProfileCacheDataSourceImpl(preferences: injector.get()));
injector.registerSingleton<StoryQuotesNetworkDataSource>(
StoryQuotesNetworkDataSourceImpl(client: injector.get()));
injector.registerSingleton<GlobalNetworkDataSource>(
GlobalNetworkDataSourceImpl(client: injector.get()));
injector.registerSingleton<MainNetworkDataSource>(
MainNetworkDataSourceImpl(client: injector.get()));
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/story_type_.dart
|
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
class StoryTypeIcon extends StatelessWidget {
final String value;
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
padding: const EdgeInsets.only(left: 0, right: 12),
height: 20,
// decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(24),
// color: Colors.brown,
// ),
child: Text(
value.toLowerCase(),
style: primaryTextStyle(
color: AppColors.white.withAlpha(152), fontSize: 12),
),
);
}
const StoryTypeIcon({
super.key,
required this.value,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/icon_text.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/widgets/story_owner.dart';
import '../resource/colors.dart';
import '../resource/fonts.dart';
class IconText extends StatelessWidget {
final IconData icon;
final String text;
final bool? hasAction;
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
margin: const EdgeInsets.all(14),
child: CircleIcon(
width: 48,
height: 48,
icon: icon,
),
),
Text(
text,
style: primaryTextStyle(
color: AppColors.white,
fontWeight: FontWeight.bold,
fontSize: 16),
),
const Spacer(),
if (hasAction == true)
Icon(
Icons.chevron_right,
color: AppColors.white,
),
if (hasAction == true)
const Padding(
padding: EdgeInsets.only(right: 24),
),
],
);
}
const IconText({
super.key,
required this.icon,
this.hasAction = false,
required this.text,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/story_item.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/utils/size.dart';
import 'package:jokes_app/common/utils/strings.dart';
import 'package:jokes_app/common/widgets/button.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
import 'package:jokes_app/common/widgets/story_owner.dart';
import 'package:jokes_app/common/widgets/story_type_.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
import '../../domain/models/ui/story.dart';
import '../resource/colors.dart';
class StoryItem extends StatelessWidget {
final Function() onTap;
final Story story;
final Function() onTapOwner;
@override
Widget build(BuildContext context) {
return Container(
height: 280,
margin: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: AppColors.primaryDark,
border: Border.all(color: AppColors.whiteAlpha52),
borderRadius: BorderRadius.circular(24),
),
child: Stack(
children: [
Align(
alignment: Alignment.topRight,
child: ScaleTap(
onPressed: () {
onTapOwner.call();
},
child: Container(
padding: const EdgeInsets.only(left: 12, right: 12),
height: 20,
margin: const EdgeInsets.only(right: 12, top: 12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: AppColors.whiteAlpha52,
),
child: Text(
story.authorName,
style: primaryTextStyle(color: AppColors.white, fontSize: 12),
),
),
),
),
Align(
alignment: Alignment.topCenter,
child: Row(
children: [
Container(
margin: const EdgeInsets.only(
left: 24, top: 24, bottom: 12, right: 16),
child: ScaleTap(
onPressed: () {
onTapOwner.call();
},
child: CircleIcon(
animate: story.isPremium,
iconColor: story.isEnabled ? null : AppColors.blue,
borderColor: story.isPremium ? AppColors.gold : null,
icon: story.isEnabled
? Icons.public
: Icons.ac_unit_rounded,
),
),
),
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.only(top: 12),
child: Text(
story.title.cut(20),
overflow: TextOverflow.ellipsis,
style: primaryTextStyle(
fontWeight: FontWeight.bold, fontSize: 14),
),
),
Container(
margin: const EdgeInsets.only(top: 4),
child: StoryTypeIcon(
value: story.timeCreate,
),
),
],
)
],
),
),
Align(
alignment: Alignment.center,
child: Container(
alignment: Alignment.topLeft,
margin: const EdgeInsets.only(left: 24, right: 24, top: 92),
child: Text(
textAlign: TextAlign.start,
story.body,
style: primaryTextStyle(),
overflow: TextOverflow.ellipsis,
maxLines: 5,
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Button(
enabled: story.isEnabled,
margin: const EdgeInsets.only(
left: 24, right: 24, top: 24, bottom: 24),
height: 48,
width: context.width,
text: story.isEnabled
? '${Strings.viewMore}(${story.viewCount})'
: Strings.frozen,
onTap: () {
onTap.call();
},
),
)
],
),
);
}
const StoryItem({
super.key,
required this.onTap,
required this.story,
required this.onTapOwner,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/scale_tap.dart
|
library flutter_scale_tap;
import 'package:flutter/physics.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
const double _DEFAULT_SCALE_MIN_VALUE = 0.95;
const double _DEFAULT_OPACITY_MIN_VALUE = 0.90;
final Curve _DEFAULT_SCALE_CURVE =
CurveSpring(); // ignore: non_constant_identifier_names
const Curve _DEFAULT_OPACITY_CURVE = Curves.ease;
const Duration _DEFAULT_DURATION = Duration(milliseconds: 300);
class ScaleTapConfig {
static double? scaleMinValue;
static Curve? scaleCurve;
static double? opacityMinValue;
static Curve? opacityCurve;
static Duration? duration;
}
class ScaleTap extends StatefulWidget {
final Function()? onPressed;
final Function()? onLongPress;
final Widget? child;
final Duration? duration;
final double? scaleMinValue;
final Curve? scaleCurve;
final Curve? opacityCurve;
final double? opacityMinValue;
final bool enableFeedback;
ScaleTap({
this.enableFeedback = true,
this.onPressed,
this.onLongPress,
required this.child,
this.duration,
this.scaleMinValue,
this.opacityMinValue,
this.scaleCurve,
this.opacityCurve,
});
@override
_ScaleTapState createState() => _ScaleTapState();
}
class _ScaleTapState extends State<ScaleTap>
with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _scale;
late Animation<double> _opacity;
@override
void initState() {
super.initState();
_animationController = AnimationController(vsync: this);
_scale = Tween<double>(begin: 1.0, end: 1.0).animate(_animationController);
_opacity =
Tween<double>(begin: 1.0, end: 1.0).animate(_animationController);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
Future<void> anim({double? scale, double? opacity, Duration? duration}) {
_animationController.stop();
_animationController.duration = duration ?? Duration.zero;
_scale = Tween<double>(
begin: _scale.value,
end: scale,
).animate(CurvedAnimation(
curve: widget.scaleCurve ??
ScaleTapConfig.scaleCurve ??
_DEFAULT_SCALE_CURVE,
parent: _animationController,
));
_opacity = Tween<double>(
begin: _opacity.value,
end: opacity,
).animate(CurvedAnimation(
curve: widget.opacityCurve ??
ScaleTapConfig.opacityCurve ??
_DEFAULT_OPACITY_CURVE,
parent: _animationController,
));
_animationController.reset();
return _animationController.forward();
}
Future<void> _onTapDown(_) {
return anim(
scale: widget.scaleMinValue ??
ScaleTapConfig.scaleMinValue ??
_DEFAULT_SCALE_MIN_VALUE,
opacity: widget.opacityMinValue ??
ScaleTapConfig.opacityMinValue ??
_DEFAULT_OPACITY_MIN_VALUE,
duration: widget.duration ?? ScaleTapConfig.duration ?? _DEFAULT_DURATION,
);
}
Future<void> _onTapUp(_) {
return anim(
scale: 1.0,
opacity: 1.0,
duration: widget.duration ?? ScaleTapConfig.duration ?? _DEFAULT_DURATION,
);
}
Future<void> _onTapCancel(_) {
return _onTapUp(_);
}
@override
Widget build(BuildContext context) {
final bool isTapEnabled =
widget.onPressed != null || widget.onLongPress != null;
return AnimatedBuilder(
animation: _animationController,
builder: (_, Widget? child) {
return Opacity(
opacity: _opacity.value,
child: Transform.scale(
alignment: Alignment.center,
scale: _scale.value,
child: child,
),
);
},
child: Listener(
onPointerDown: isTapEnabled ? _onTapDown : null,
onPointerCancel: _onTapCancel,
onPointerUp: _onTapUp,
child: GestureDetector(
onTap: isTapEnabled
? () {
if (widget.enableFeedback) {
SystemSound.play(SystemSoundType.click);
}
widget.onPressed?.call();
}
: null,
onLongPress: isTapEnabled ? widget.onLongPress : null,
child: widget.child,
),
),
);
}
}
class CurveSpring extends Curve {
final SpringSimulation sim;
CurveSpring() : this.sim = _sim(70, 20);
@override
double transform(double t) => sim.x(t) + t * (1 - sim.x(1.0));
}
_sim(double stiffness, double damping) => SpringSimulation(
SpringDescription.withDampingRatio(
mass: 1,
stiffness: stiffness,
ratio: 0.7,
),
0.0,
1.0,
0.0,
);
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/button.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/colors.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
class Button extends StatelessWidget {
final EdgeInsets? margin;
final double? width;
final double? height;
final String text;
final bool? enabled;
final bool? animate;
final Function() onTap;
@override
Widget build(BuildContext context) {
return Opacity(
opacity: enabled == false ? 0.5 : 1,
child: ScaleTap(
scaleMinValue: enabled == false ? 1 : null,
enableFeedback: enabled == true,
child: Container(
alignment: Alignment.center,
height: height,
width: width,
margin: margin,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: AppColors.darkGreen),
child: enabled == true
? animate == true
? SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
color: AppColors.darkSpringGreen,
strokeWidth: 2,
),
)
: Text(
text,
style: primaryTextStyle(
color: AppColors.darkSpringGreen,
fontWeight: FontWeight.bold,
fontSize: 16),
)
: Text(
text,
style: primaryTextStyle(
color: AppColors.darkSpringGreen,
fontWeight: FontWeight.bold,
fontSize: 16),
),
),
onPressed: () {
if (enabled == true) {
onTap.call();
}
},
),
);
}
const Button({
super.key,
this.margin,
this.width,
this.enabled = true,
this.animate = false,
required this.onTap,
this.height,
required this.text,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/story_owner.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/colors.dart';
class CircleIcon extends StatefulWidget {
final IconData icon;
final double? width;
final double? height;
final bool? animate;
final Color? iconColor;
final Color? borderColor;
@override
State<CircleIcon> createState() => _CircleIconState();
const CircleIcon({
super.key,
required this.icon,
this.width,
this.borderColor,
this.iconColor,
this.animate = false,
this.height,
});
}
class _CircleIconState extends State<CircleIcon>
with TickerProviderStateMixin {
late AnimationController _resizableController;
@override
void initState() {
_resizableController = AnimationController(
vsync: this,
duration: const Duration(
milliseconds: 3000,
),
);
_resizableController.addStatusListener((animationStatus) {
switch (animationStatus) {
case AnimationStatus.completed:
_resizableController.reverse();
break;
case AnimationStatus.dismissed:
_resizableController.forward();
break;
case AnimationStatus.forward:
break;
case AnimationStatus.reverse:
break;
}
});
_resizableController.forward();
super.initState();
}
@override
void dispose() {
_resizableController.dispose();
super.dispose();
}
Widget _buildContainer(BuildContext context) {
return Container(
height: widget.height ?? 52,
width: widget.width ?? 52,
decoration: BoxDecoration(
color: AppColors.whiteAlpha52,
border: Border.all(
color: widget.borderColor ?? Colors.transparent,
width: _resizableController.value * 5),
borderRadius: BorderRadius.circular(100),
),
child: Icon(
widget.icon,
color: widget.iconColor ?? AppColors.darkSpringGreen,
),
);
}
@override
Widget build(BuildContext context) {
return widget.animate == true
? AnimatedBuilder(
animation: _resizableController,
builder: (context, child) {
return _buildContainer(context);
},
)
: _buildContainer(context);
}
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/loading.dart
|
import 'package:flutter/cupertino.dart';
import 'package:jokes_app/assets.dart';
import 'package:lottie/lottie.dart';
class Loading extends StatelessWidget {
const Loading({super.key});
@override
Widget build(BuildContext context) {
return SizedBox(
width: 24,
height: 24,
child: Center(
child: Lottie.asset(
Assets.loadingJson,
frameRate: FrameRate.max,
width: 152,
height: 152,
),
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/input_widget.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import '../resource/colors.dart';
class Input extends StatelessWidget {
final String hint;
final EdgeInsets margin;
bool multiLine = false;
final FocusNode? focusNode;
double verticalPadding = 0.0;
double blur;
double spread;
final int? maxLength;
final TextEditingController? controller;
final Function(String)? onSubmit;
final Function(String)? onChange;
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
color: AppColors.primaryDark,
boxShadow: [
BoxShadow(
color: Colors.black12.withOpacity(0.05),
blurRadius: blur,
spreadRadius: spread,
offset: const Offset(0, 0), // shadow direction: bottom right
)
],
),
margin: margin,
child: TextField(
maxLength: maxLength,
style: primaryTextStyle(),
cursorColor: AppColors.darkSpringGreen,
onSubmitted: (str) {
onSubmit?.call(str);
},
onChanged: (text) {
onChange?.call(text);
},
focusNode: focusNode,
keyboardType: multiLine ? TextInputType.multiline : TextInputType.name,
maxLines: multiLine ? null : 1,
textAlign: TextAlign.start,
controller: controller,
decoration: InputDecoration(
counterText: "",
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
borderSide: BorderSide(
color: AppColors.darkSpringGreen.withAlpha(180), width: 2),
),
hintText: hint,
hintStyle: primaryTextStyle(color: AppColors.whiteAlpha52),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24),
borderSide: const BorderSide(
width: 0,
style: BorderStyle.none,
),
),
filled: true,
contentPadding: EdgeInsets.only(
left: 20,
bottom: verticalPadding,
top: verticalPadding,
right: 20),
fillColor: AppColors.primaryColor,
),
),
);
}
Input({
super.key,
required this.hint,
this.multiLine = false,
this.verticalPadding = 20,
this.focusNode,
this.controller,
this.blur = 200.0,
this.onSubmit,
this.onChange,
this.maxLength,
this.spread = 12.0,
required this.margin,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/story_quote_item.dart
|
import 'package:flutter/material.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
import 'package:jokes_app/domain/models/ui/story_quote.dart';
import '../resource/colors.dart';
import '../resource/fonts.dart';
class StoryQuoteItem extends StatelessWidget {
final StoryQuote item;
final Function() onTap;
final Function() onTapOwner;
@override
Widget build(BuildContext context) {
return ListTile(
onTap: () {
onTap.call();
},
title: Row(
children: [
ScaleTap(
onPressed: () {
onTapOwner.call();
},
child: Container(
padding: const EdgeInsets.only(left: 12, right: 12, top: 2),
height: 20,
margin: const EdgeInsets.only(right: 12, top: 16, bottom: 12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color:
item.isOwner ? AppColors.darkGreen : AppColors.whiteAlpha52,
),
child: Text(
item.username,
style: primaryTextStyle(color: AppColors.white, fontSize: 12),
),
),
),
],
),
trailing: Icon(
Icons.touch_app,
color: AppColors.whiteAlpha52,
),
subtitle: Text(
item.body,
style: primaryTextStyle(),
),
);
}
const StoryQuoteItem({
super.key,
required this.item,
required this.onTap,
required this.onTapOwner,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/settings_item.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
import 'package:jokes_app/common/widgets/story_owner.dart';
import 'package:jokes_app/common/widgets/story_type_.dart';
import '../resource/colors.dart';
import '../resource/fonts.dart';
class SettingsItem extends StatelessWidget {
final EdgeInsets? margin;
final double? width;
final double? height;
final String text;
final String? subText;
final Function() onTap;
final IconData icon;
@override
Widget build(BuildContext context) {
return ScaleTap(
child: Container(
alignment: Alignment.centerLeft,
height: height,
width: width,
margin: margin,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
color: AppColors.primaryDark),
child: Row(
children: [
Container(
margin: const EdgeInsets.all(14),
child: CircleIcon(
width: 48,
height: 48,
icon: icon,
),
),
Flexible(
child: ListTile(
title: Text(
text,
style: primaryTextStyle(
color: AppColors.white,
fontWeight: FontWeight.bold,
fontSize: 16),
),
subtitle: subText != null
? Text(
subText!,
style: primaryTextStyle(
color: AppColors.whiteAlpha52,
fontWeight: FontWeight.bold,
fontSize: 14),
)
: null,
),
),
],
),
),
onPressed: () {
onTap.call();
},
);
}
const SettingsItem({
super.key,
this.margin,
this.width,
this.height,
this.subText,
required this.icon,
required this.text,
required this.onTap,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/widgets/not_found.dart
|
import 'package:flutter/cupertino.dart';
import 'package:lottie/lottie.dart';
import '../../assets.dart';
class NotFound extends StatelessWidget {
const NotFound({super.key});
@override
Widget build(BuildContext context) {
return Opacity(
opacity: 0.5,
child: Center(
child: Lottie.asset(Assets.emptyJson, width: 152, height: 152),
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/animated_text_kit.dart
|
/// _Animated Text Kit_ is a library of some cool and awesome text animations.
library animated_text_kit;
export 'src/animated_text.dart';
export 'src/typer.dart';
export 'src/rotate.dart';
export 'src/typewriter.dart';
export 'src/fade.dart';
export 'src/colorize.dart';
export 'src/scale.dart';
export 'src/text_liquid_fill.dart';
export 'src/wavy.dart';
export 'src/flicker.dart';
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/colorize.dart
|
import 'package:flutter/material.dart';
import 'animated_text.dart';
/// Animated Text that shows text shimmering between [colors].
///
/// 
class ColorizeAnimatedText extends AnimatedText {
/// The [Duration] of the delay between the apparition of each characters
///
/// By default it is set to 200 milliseconds.
final Duration speed;
/// Set the colors for the gradient animation of the text.
///
/// The [List] should contain at least two values of [Color] in it.
final List<Color> colors;
/// Specifies the [TextDirection] for animation direction.
///
/// By default it is set to [TextDirection.ltr]
final TextDirection textDirection;
ColorizeAnimatedText(
String text, {
TextAlign textAlign = TextAlign.start,
required TextStyle textStyle,
this.speed = const Duration(milliseconds: 200),
required this.colors,
this.textDirection = TextDirection.ltr,
}) : assert(null != textStyle.fontSize),
assert(colors.length > 1),
super(
text: text,
textAlign: textAlign,
textStyle: textStyle,
duration: speed * text.characters.length,
);
late Animation<double> _colorShifter, _fadeIn, _fadeOut;
// Copy of colors that may be reversed when RTL.
late List<Color> _colors;
@override
void initAnimation(AnimationController controller) {
// Note: This calculation is the only reason why [textStyle] is required
final tuning = (300.0 * colors.length) *
(textStyle!.fontSize! / 24.0) *
0.75 *
(textCharacters.length / 15.0);
_fadeIn = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.0, 0.1, curve: Curves.easeOut),
),
);
_fadeOut = Tween<double>(begin: 1.0, end: 1.0).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.9, 1.0, curve: Curves.easeIn),
),
);
final colorShift = colors.length * tuning;
final colorTween = textDirection == TextDirection.ltr
? Tween<double>(
begin: 0.0,
end: colorShift,
)
: Tween<double>(
begin: colorShift,
end: 0.0,
);
_colorShifter = colorTween.animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.0, 1.0, curve: Curves.easeIn),
),
);
// With RTL, colors need to be reversed to compensate for colorTween
// counting down instead of up.
_colors = textDirection == TextDirection.ltr
? colors
: colors.reversed.toList(growable: false);
}
@override
Widget completeText(BuildContext context) {
final linearGradient = LinearGradient(colors: _colors).createShader(
Rect.fromLTWH(0.0, 0.0, _colorShifter.value, 0.0),
);
return DefaultTextStyle.merge(
style: textStyle,
child: Text(
text,
style: TextStyle(foreground: Paint()..shader = linearGradient),
textAlign: textAlign,
),
);
}
@override
Widget animatedBuilder(BuildContext context, Widget? child) {
return Opacity(
opacity: _fadeIn.value != 1.0 ? _fadeIn.value : _fadeOut.value,
child: completeText(context),
);
}
}
/// Animation that displays [text] elements, shimmering transition between [_colors].
///
/// 
@Deprecated('Use AnimatedTextKit with ColorizeAnimatedText instead.')
class ColorizeAnimatedTextKit extends AnimatedTextKit {
ColorizeAnimatedTextKit({
Key? key,
required List<String> text,
TextAlign textAlign = TextAlign.start,
TextDirection textDirection = TextDirection.ltr,
required TextStyle textStyle,
required List<Color> colors,
Duration speed = const Duration(milliseconds: 200),
Duration pause = const Duration(milliseconds: 1000),
VoidCallback? onTap,
void Function(int, bool)? onNext,
void Function(int, bool)? onNextBeforePause,
VoidCallback? onFinished,
bool isRepeatingAnimation = true,
int totalRepeatCount = 3,
bool repeatForever = false,
bool displayFullTextOnTap = false,
bool stopPauseOnTap = false,
}) : super(
key: key,
animatedTexts: _animatedTexts(
text,
textAlign,
textStyle,
speed,
colors,
textDirection,
),
pause: pause,
displayFullTextOnTap: displayFullTextOnTap,
stopPauseOnTap: stopPauseOnTap,
onTap: onTap,
onNext: onNext,
onNextBeforePause: onNextBeforePause,
onFinished: onFinished,
isRepeatingAnimation: isRepeatingAnimation,
totalRepeatCount: totalRepeatCount,
repeatForever: repeatForever,
);
static List<AnimatedText> _animatedTexts(
List<String> text,
TextAlign textAlign,
TextStyle textStyle,
Duration speed,
List<Color> colors,
TextDirection textDirection,
) =>
text
.map((_) => ColorizeAnimatedText(
_,
textAlign: textAlign,
textStyle: textStyle,
speed: speed,
colors: colors,
textDirection: textDirection,
))
.toList();
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/text_liquid_fill.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
/// Animation that displays a [text] element, coloring it to look like sloshing
/// water is filling it up.
///
/// 
class TextLiquidFill extends StatefulWidget {
/// Gives [TextStyle] to the text string.
///
/// By default it is `TextStyle(fontSize: 140, fontWeight: FontWeight.bold)`
final TextStyle textStyle;
/// Gives [TextAlign] to the text string.
///
/// By default it is [TextAlign.left].
final TextAlign textAlign;
/// Specifies the duration the text should fill with liquid.
///
/// By default it is set to 6 seconds.
final Duration loadDuration;
/// Specifies the duration that one wave takes to pass the screen.
///
/// By default it is set to 2 seconds.
final Duration waveDuration;
/// Specifies the height of the box around text
///
/// By default it is set to 250
final double boxHeight;
/// Specifies the width of the box around text
///
/// By default it is set to 400
final double boxWidth;
/// String which would be filled by liquid animation
final String text;
/// Specifies the backgroundColor of the box
///
/// By default it is set to black color
final Color boxBackgroundColor;
/// Specifies the color of the wave
///
/// By default it is set to blueAccent color
final Color waveColor;
/// Specifies the load limit: (0, 1.0]. This may be used to limit the liquid
/// fill effect to less than 100%.
///
/// By default, the animation will load to 1.0 (100%).
final double loadUntil;
TextLiquidFill({
Key? key,
required this.text,
this.textStyle =
const TextStyle(fontSize: 140, fontWeight: FontWeight.bold),
this.textAlign = TextAlign.left,
this.loadDuration = const Duration(seconds: 6),
this.waveDuration = const Duration(seconds: 2),
this.boxHeight = 250,
this.boxWidth = 400,
this.boxBackgroundColor = Colors.black,
this.waveColor = Colors.blueAccent,
this.loadUntil = 1.0,
}) : assert(loadUntil > 0 && loadUntil <= 1.0),
super(key: key);
/// Creates the mutable state for this widget. See [StatefulWidget.createState].
@override
_TextLiquidFillState createState() => _TextLiquidFillState();
}
class _TextLiquidFillState extends State<TextLiquidFill>
with TickerProviderStateMixin {
final _textKey = GlobalKey();
late AnimationController _waveController, _loadController;
late Animation<double> _loadValue;
@override
void initState() {
super.initState();
_waveController = AnimationController(
vsync: this,
duration: widget.waveDuration,
);
_loadController = AnimationController(
vsync: this,
duration: widget.loadDuration,
);
_loadValue = Tween<double>(
begin: 0.0,
end: widget.loadUntil,
).animate(_loadController);
if (1.0 == widget.loadUntil) {
_loadValue.addStatusListener((status) {
if (AnimationStatus.completed == status) {
// Stop the repeating wave when the load has completed to 100%
_waveController.stop();
}
});
}
_waveController.repeat();
_loadController.forward();
}
@override
void dispose() {
_waveController.dispose();
_loadController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
SizedBox(
height: widget.boxHeight,
width: widget.boxWidth,
child: AnimatedBuilder(
animation: _waveController,
builder: (BuildContext context, Widget? child) {
return CustomPaint(
painter: _WavePainter(
textKey: _textKey,
waveValue: _waveController.value,
loadValue: _loadValue.value,
boxHeight: widget.boxHeight,
waveColor: widget.waveColor,
),
);
},
),
),
SizedBox(
height: widget.boxHeight,
width: widget.boxWidth,
child: ShaderMask(
blendMode: BlendMode.srcOut,
shaderCallback: (bounds) => LinearGradient(
colors: [widget.boxBackgroundColor],
stops: [0.0],
).createShader(bounds),
child: Container(
color: Colors.transparent,
child: Center(
child: Text(
widget.text,
key: _textKey,
style: widget.textStyle,
textAlign: widget.textAlign,
),
),
),
),
)
],
);
}
}
class _WavePainter extends CustomPainter {
static const _pi2 = 2 * pi;
final GlobalKey textKey;
final double waveValue;
final double loadValue;
final double boxHeight;
final Color waveColor;
_WavePainter({
required this.textKey,
required this.waveValue,
required this.loadValue,
required this.boxHeight,
required this.waveColor,
});
@override
void paint(Canvas canvas, Size size) {
final RenderBox? textBox =
textKey.currentContext!.findRenderObject() as RenderBox;
if (textBox == null) return;
final textHeight = textBox.size.height;
final baseHeight =
(boxHeight / 2) + (textHeight / 2) - (loadValue * textHeight);
final width = size.width;
final height = size.height;
final path = Path();
path.moveTo(0.0, baseHeight);
for (var i = 0.0; i < width; i++) {
path.lineTo(i, baseHeight + sin(_pi2 * (i / width + waveValue)) * 8);
}
path.lineTo(width, height);
path.lineTo(0.0, height);
path.close();
final wavePaint = Paint()..color = waveColor;
canvas.drawPath(path, wavePaint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/typer.dart
|
import 'package:flutter/material.dart';
import 'animated_text.dart';
/// Animated Text that displays a [Text] element as if it is being typed one
/// character at a time.
///
/// 
class TyperAnimatedText extends AnimatedText {
/// The [Duration] of the delay between the apparition of each characters
///
/// By default it is set to 40 milliseconds.
final Duration speed;
/// The [Curve] of the rate of change of animation over time.
///
/// By default it is set to Curves.linear.
final Curve curve;
TyperAnimatedText(
String text, {
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
this.speed = const Duration(milliseconds: 40),
this.curve = Curves.linear,
}) : super(
text: text,
textAlign: textAlign,
textStyle: textStyle,
duration: speed * text.characters.length,
);
late Animation<double> _typingText;
@override
Duration get remaining => speed * (textCharacters.length - _typingText.value);
@override
void initAnimation(AnimationController controller) {
_typingText = CurveTween(
curve: curve,
).animate(controller);
}
/// Widget showing partial text, up to [count] characters
@override
Widget animatedBuilder(BuildContext context, Widget? child) {
/// Output of CurveTween is in the range [0, 1] for majority of the curves.
/// It is converted to [0, textCharacters.length].
final count =
(_typingText.value.clamp(0, 1) * textCharacters.length).round();
assert(count <= textCharacters.length);
return textWidget(textCharacters.take(count).toString());
}
}
/// Animation that displays [text] elements, as if they are being typed one
/// character at a time.
///
/// 
@Deprecated('Use AnimatedTextKit with TyperAnimatedText instead.')
class TyperAnimatedTextKit extends AnimatedTextKit {
TyperAnimatedTextKit({
Key? key,
required List<String> text,
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
Duration speed = const Duration(milliseconds: 40),
Duration pause = const Duration(milliseconds: 1000),
bool displayFullTextOnTap = false,
bool stopPauseOnTap = false,
VoidCallback? onTap,
void Function(int, bool)? onNext,
void Function(int, bool)? onNextBeforePause,
VoidCallback? onFinished,
bool isRepeatingAnimation = true,
bool repeatForever = true,
int totalRepeatCount = 3,
Curve curve = Curves.linear,
}) : super(
key: key,
animatedTexts:
_animatedTexts(text, textAlign, textStyle, speed, curve),
pause: pause,
displayFullTextOnTap: displayFullTextOnTap,
stopPauseOnTap: stopPauseOnTap,
onTap: onTap,
onNext: onNext,
onNextBeforePause: onNextBeforePause,
onFinished: onFinished,
isRepeatingAnimation: isRepeatingAnimation,
repeatForever: repeatForever,
totalRepeatCount: totalRepeatCount,
);
static List<AnimatedText> _animatedTexts(
List<String> text,
TextAlign textAlign,
TextStyle? textStyle,
Duration speed,
Curve curve,
) =>
text
.map((_) => TyperAnimatedText(
_,
textAlign: textAlign,
textStyle: textStyle,
speed: speed,
curve: curve,
))
.toList();
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/animated_text.dart
|
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
/// Abstract base class for text animations.
abstract class AnimatedText {
/// Text for [Text] widget.
final String text;
/// [TextAlign] property for [Text] widget.
///
/// By default it is set to [TextAlign.start]
final TextAlign textAlign;
/// [TextStyle] property for [Text] widget.
final TextStyle? textStyle;
/// The Duration for the Animation Controller.
///
/// This will set the total duration for the animated widget.
/// For example, if you want the text animation to take 3 seconds,
/// then you have to set [duration] to 3 seconds.
final Duration duration;
/// Same as [text] but as [Characters].
///
/// Need to use character length, not String length, to propertly support
/// Unicode and Emojis.
final Characters textCharacters;
AnimatedText({
required this.text,
this.textAlign = TextAlign.start,
this.textStyle,
required this.duration,
}) : textCharacters = text.characters;
/// Return the remaining Duration for the Animation (when applicable).
Duration? get remaining => null;
/// Initialize the Animation.
void initAnimation(AnimationController controller);
/// Utility method to create a styled [Text] widget using the [textAlign] and
/// [textStyle], but you can specify the [data].
Widget textWidget(String data) => Text(
data,
textAlign: textAlign,
style: textStyle,
);
/// Widget showing the complete text (when animation is complete or paused).
/// By default, it shows a Text widget, but this may be overridden.
Widget completeText(BuildContext context) => textWidget(text);
/// Widget showing animated text, based on animation value(s).
Widget animatedBuilder(BuildContext context, Widget? child);
}
/// Base class for Animated Text widgets.
class AnimatedTextKit extends StatefulWidget {
/// List of [AnimatedText] to display subsequently in the animation.
final List<AnimatedText> animatedTexts;
/// Define the [Duration] of the pause between texts
///
/// By default it is set to 1000 milliseconds.
final Duration pause;
/// Should the animation ends up early and display full text if you tap on it?
///
/// By default it is set to false.
final bool displayFullTextOnTap;
/// If on pause, should a tap remove the remaining pause time ?
///
/// By default it is set to false.
final bool stopPauseOnTap;
/// Adds the onTap [VoidCallback] to the animated widget.
final VoidCallback? onTap;
/// Adds the onFinished [VoidCallback] to the animated widget.
///
/// This method will run only if [isRepeatingAnimation] is set to false.
final VoidCallback? onFinished;
/// Adds the onNext callback to the animated widget.
///
/// Will be called right before the next text, after the pause parameter
final void Function(int, bool)? onNext;
/// Adds the onNextBeforePause callback to the animated widget.
///
/// Will be called at the end of n-1 animation, before the pause parameter
final void Function(int, bool)? onNextBeforePause;
/// Set if the animation should not repeat by changing the value of it to false.
///
/// By default it is set to true.
final bool isRepeatingAnimation;
/// Sets if the animation should repeat forever. [isRepeatingAnimation] also
/// needs to be set to true if you want to repeat forever.
///
/// By default it is set to false, if set to true, [totalRepeatCount] is ignored.
final bool repeatForever;
/// Sets the number of times animation should repeat
///
/// By default it is set to 3
final int totalRepeatCount;
const AnimatedTextKit({
Key? key,
required this.animatedTexts,
this.pause = const Duration(milliseconds: 1000),
this.displayFullTextOnTap = false,
this.stopPauseOnTap = false,
this.onTap,
this.onNext,
this.onNextBeforePause,
this.onFinished,
this.isRepeatingAnimation = true,
this.totalRepeatCount = 3,
this.repeatForever = false,
}) : assert(animatedTexts.length > 0),
assert(!isRepeatingAnimation || totalRepeatCount > 0 || repeatForever),
assert(null == onFinished || !repeatForever),
super(key: key);
/// Creates the mutable state for this widget. See [StatefulWidget.createState].
@override
_AnimatedTextKitState createState() => _AnimatedTextKitState();
}
class _AnimatedTextKitState extends State<AnimatedTextKit>
with TickerProviderStateMixin {
late AnimationController _controller;
late AnimatedText _currentAnimatedText;
int _currentRepeatCount = 0;
int _index = 0;
bool _isCurrentlyPausing = false;
Timer? _timer;
@override
void initState() {
super.initState();
_initAnimation();
}
@override
void dispose() {
_timer?.cancel();
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final completeText = _currentAnimatedText.completeText(context);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _onTap,
child: _isCurrentlyPausing || !_controller.isAnimating
? completeText
: AnimatedBuilder(
animation: _controller,
builder: _currentAnimatedText.animatedBuilder,
child: completeText,
),
);
}
bool get _isLast => _index == widget.animatedTexts.length - 1;
void _nextAnimation() {
final isLast = _isLast;
_isCurrentlyPausing = false;
// Handling onNext callback
widget.onNext?.call(_index, isLast);
if (isLast) {
if (widget.isRepeatingAnimation &&
(widget.repeatForever ||
_currentRepeatCount != (widget.totalRepeatCount - 1))) {
_index = 0;
if (!widget.repeatForever) {
_currentRepeatCount++;
}
} else {
widget.onFinished?.call();
return;
}
} else {
_index++;
}
if (mounted) setState(() {});
_controller.dispose();
// Re-initialize animation
_initAnimation();
}
void _initAnimation() {
_currentAnimatedText = widget.animatedTexts[_index];
_controller = AnimationController(
duration: _currentAnimatedText.duration,
vsync: this,
);
_currentAnimatedText.initAnimation(_controller);
_controller
..addStatusListener(_animationEndCallback)
..forward();
}
void _setPause() {
final isLast = _isLast;
_isCurrentlyPausing = true;
if (mounted) setState(() {});
// Handle onNextBeforePause callback
widget.onNextBeforePause?.call(_index, isLast);
}
void _animationEndCallback(AnimationStatus state) {
if (state == AnimationStatus.completed) {
_setPause();
assert(null == _timer || !_timer!.isActive);
_timer = Timer(widget.pause, _nextAnimation);
}
}
void _onTap() {
if (widget.displayFullTextOnTap) {
if (_isCurrentlyPausing) {
if (widget.stopPauseOnTap) {
_timer?.cancel();
_nextAnimation();
}
} else {
final left =
(_currentAnimatedText.remaining ?? _currentAnimatedText.duration)
.inMilliseconds;
_controller.stop();
_setPause();
assert(null == _timer || !_timer!.isActive);
_timer = Timer(
Duration(
milliseconds: max(
widget.pause.inMilliseconds,
left,
),
),
_nextAnimation,
);
}
}
widget.onTap?.call();
}
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/wavy.dart
|
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'animated_text.dart';
/// Animated Text that displays a [Text] element with each character popping
/// like a stadium wave.
///
/// 
class WavyAnimatedText extends AnimatedText {
/// The [Duration] of the motion of each character
///
/// By default it is set to 300 milliseconds.
final Duration speed;
WavyAnimatedText(
String text, {
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
this.speed = const Duration(milliseconds: 300),
}) : super(
text: text,
textAlign: textAlign,
textStyle: textStyle,
duration: speed * text.characters.length,
);
late Animation<double> _waveAnim;
@override
void initAnimation(AnimationController controller) {
_waveAnim = Tween<double>(begin: 0, end: textCharacters.length / 2 + 0.52)
.animate(controller);
}
@override
Widget animatedBuilder(BuildContext context, Widget? child) {
final defaultTextStyle = DefaultTextStyle.of(context).style;
final scaleFactor = MediaQuery.of(context).textScaleFactor;
return RepaintBoundary(
child: CustomPaint(
painter: _WTextPainter(
progress: _waveAnim.value,
text: text,
textStyle: defaultTextStyle.merge(textStyle),
scaleFactor: scaleFactor,
),
child: Text(
text,
style: defaultTextStyle
.merge(textStyle)
.merge(TextStyle(color: Colors.transparent)),
textScaleFactor: scaleFactor,
),
),
);
}
}
/// Animation that displays [text] elements, with each text animated with its
/// characters popping like a stadium wave.
///
/// 
@Deprecated('Use AnimatedTextKit with WavyAnimatedText instead.')
class WavyAnimatedTextKit extends AnimatedTextKit {
WavyAnimatedTextKit({
Key? key,
required List<String> text,
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
Duration speed = const Duration(milliseconds: 300),
Duration pause = const Duration(milliseconds: 1000),
VoidCallback? onTap,
void Function(int, bool)? onNext,
void Function(int, bool)? onNextBeforePause,
VoidCallback? onFinished,
bool isRepeatingAnimation = true,
int totalRepeatCount = 3,
bool repeatForever = true,
bool displayFullTextOnTap = false,
bool stopPauseOnTap = false,
}) : super(
key: key,
animatedTexts: _animatedTexts(text, textAlign, textStyle, speed),
pause: pause,
displayFullTextOnTap: displayFullTextOnTap,
stopPauseOnTap: stopPauseOnTap,
onTap: onTap,
onNext: onNext,
onNextBeforePause: onNextBeforePause,
onFinished: onFinished,
isRepeatingAnimation: isRepeatingAnimation,
totalRepeatCount: totalRepeatCount,
repeatForever: repeatForever,
);
static List<AnimatedText> _animatedTexts(
List<String> text,
TextAlign textAlign,
TextStyle? textStyle,
Duration speed,
) =>
text
.map((_) => WavyAnimatedText(
_,
textAlign: textAlign,
textStyle: textStyle,
speed: speed,
))
.toList();
}
class _WTextPainter extends CustomPainter {
_WTextPainter({
required this.progress,
required this.text,
required this.textStyle,
required this.scaleFactor,
});
final double progress, scaleFactor;
final String text;
// Private class to store text information
final _textLayoutInfo = <_TextLayoutInfo>[];
final TextStyle textStyle;
@override
void paint(Canvas canvas, Size size) {
if (_textLayoutInfo.isEmpty) {
// calculate the initial position of each char
calculateLayoutInfo(text, _textLayoutInfo);
}
canvas.save();
for (var textLayout in _textLayoutInfo) {
// offset required to center the characters
final centerOffset =
Offset(size.width / 2, (size.height / 2 - textLayout.height / 2));
if (textLayout.isMoving) {
final p = math.min(progress * 2, 1.0);
// drawing the char if the text is moving
drawText(
canvas,
textLayout.text,
Offset(
textLayout.offsetX,
(textLayout.offsetY -
(textLayout.offsetY - textLayout.riseHeight) * p),
) +
centerOffset,
textLayout);
} else {
// drawing the char if text is not moving
drawText(
canvas,
textLayout.text,
Offset(textLayout.offsetX, textLayout.offsetY) + centerOffset,
textLayout,
);
}
}
canvas.restore();
}
@override
bool shouldRepaint(_WTextPainter oldDelegate) {
if (oldDelegate.progress != progress) {
// calulate layout of text and movement of moving chars
calculateLayoutInfo(text, _textLayoutInfo);
calculateMove();
return true;
}
return false;
}
void calculateMove() {
final height = _textLayoutInfo[0].height;
final txtInMoInd = progress.floor();
final percent = progress - txtInMoInd;
final txtInMoOdd = (progress - .5).floor();
final txtInMoEven = txtInMoInd * 2;
// Calculating movement of the char at odd place
if (txtInMoOdd < (text.length - 1) / 2 && !txtInMoOdd.isNegative) {
_textLayoutInfo[txtInMoOdd + (txtInMoOdd + 1)].isMoving = true;
// percent < .5 creates an phase difference between odd and even chars
_textLayoutInfo[txtInMoOdd + (txtInMoOdd + 1)].riseHeight = progress < .5
? 0
: -1.3 * height * math.sin((progress - .5) * math.pi).abs();
}
// Calculating movement of the char at even place
if (txtInMoEven < text.length) {
_textLayoutInfo[txtInMoEven].isMoving = true;
_textLayoutInfo[txtInMoEven].riseHeight =
-1.3 * height * math.sin(percent * math.pi);
}
}
void drawText(Canvas canvas, String text, Offset offset,
_TextLayoutInfo textLayoutInfo) {
var textPainter = TextPainter(
text: TextSpan(
text: text,
style: textStyle,
),
textDirection: TextDirection.ltr,
textScaleFactor: scaleFactor,
)..layout();
textPainter.paint(
canvas,
Offset(
offset.dx - textLayoutInfo.width / 2,
offset.dy + (textLayoutInfo.height - textPainter.height) / 2,
),
);
}
void calculateLayoutInfo(String text, List<_TextLayoutInfo> list) {
list.clear();
// creating a textPainter to get data about location and offset for chars
final textPainter = TextPainter(
text: TextSpan(
text: text,
style: textStyle,
),
textDirection: TextDirection.ltr,
maxLines: 1,
textScaleFactor: scaleFactor,
);
textPainter.layout();
for (var i = 0; i < text.length; i++) {
var forCaret = textPainter.getOffsetForCaret(
TextPosition(offset: i),
Rect.zero,
);
var offsetX = forCaret.dx;
if (i > 0 && offsetX == 0) {
break;
}
// creating layout for each char
final textLayoutInfo = _TextLayoutInfo(
text: text[i],
offsetX: offsetX,
offsetY: forCaret.dy,
width: textPainter.width,
height: textPainter.height,
baseline: textPainter
.computeDistanceToActualBaseline(TextBaseline.ideographic),
);
list.add(textLayoutInfo);
}
}
}
class _TextLayoutInfo {
final String text;
final double offsetX;
final double offsetY;
final double width;
final double height;
final double baseline;
late double riseHeight;
bool isMoving = false;
_TextLayoutInfo({
required this.text,
required this.offsetX,
required this.offsetY,
required this.width,
required this.height,
required this.baseline,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/scale.dart
|
import 'package:flutter/material.dart';
import 'animated_text.dart';
/// Animated Text that displays a [Text] element, scaling them up and then out.
///
/// 
class ScaleAnimatedText extends AnimatedText {
/// Set the scaling factor of the text for the animation.
///
/// By default it is set to [double] value 0.5
final double scalingFactor;
ScaleAnimatedText(
String text, {
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
Duration duration = const Duration(milliseconds: 2000),
this.scalingFactor = 0.5,
}) : super(
text: text,
textAlign: textAlign,
textStyle: textStyle,
duration: duration,
);
late Animation<double> _fadeIn, _fadeOut, _scaleIn, _scaleOut;
@override
void initAnimation(AnimationController controller) {
_fadeIn = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
),
);
_fadeOut = Tween<double>(begin: 1.0, end: 0.0).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.5, 1.0, curve: Curves.easeOut),
),
);
_scaleIn = Tween<double>(begin: scalingFactor, end: 1.0).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.0, 0.5, curve: Curves.easeOut),
),
);
_scaleOut = Tween<double>(begin: 1.0, end: scalingFactor).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.5, 1.0, curve: Curves.easeIn),
),
);
}
@override
Widget completeText(BuildContext context) => SizedBox.shrink();
@override
Widget animatedBuilder(BuildContext context, Widget? child) {
return ScaleTransition(
scale: _scaleIn.value != 1.0 ? _scaleIn : _scaleOut,
child: Opacity(
opacity: _fadeIn.value != 1.0 ? _fadeIn.value : _fadeOut.value,
child: textWidget(text),
),
);
}
}
/// Animation that displays [text] elements, scaling them up and then out, one at a time.
///
/// 
@Deprecated('Use AnimatedTextKit with ScaleAnimatedText instead.')
class ScaleAnimatedTextKit extends AnimatedTextKit {
ScaleAnimatedTextKit({
Key? key,
required List<String> text,
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
double scalingFactor = 0.5,
Duration duration = const Duration(milliseconds: 2000),
Duration pause = const Duration(milliseconds: 500),
VoidCallback? onTap,
void Function(int, bool)? onNext,
void Function(int, bool)? onNextBeforePause,
VoidCallback? onFinished,
bool isRepeatingAnimation = true,
int totalRepeatCount = 3,
bool repeatForever = false,
bool displayFullTextOnTap = false,
bool stopPauseOnTap = false,
}) : super(
key: key,
animatedTexts: _animatedTexts(
text,
textAlign,
textStyle,
duration,
scalingFactor,
),
pause: pause,
displayFullTextOnTap: displayFullTextOnTap,
stopPauseOnTap: stopPauseOnTap,
onTap: onTap,
onNext: onNext,
onNextBeforePause: onNextBeforePause,
onFinished: onFinished,
isRepeatingAnimation: isRepeatingAnimation,
totalRepeatCount: totalRepeatCount,
repeatForever: repeatForever,
);
static List<AnimatedText> _animatedTexts(
List<String> text,
TextAlign textAlign,
TextStyle? textStyle,
Duration duration,
double scalingFactor,
) =>
text
.map((_) => ScaleAnimatedText(
_,
textAlign: textAlign,
textStyle: textStyle,
duration: duration,
scalingFactor: scalingFactor,
))
.toList();
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/typewriter.dart
|
import 'package:flutter/material.dart';
import 'animated_text.dart';
/// Animated Text that displays a [Text] element as if it is being typed one
/// character at a time. Similar to [TyperAnimatedText], but shows a cursor.
///
/// 
class TypewriterAnimatedText extends AnimatedText {
// The text length is padded to cause extra cursor blinking after typing.
static const extraLengthForBlinks = 8;
/// The [Duration] of the delay between the apparition of each characters
///
/// By default it is set to 30 milliseconds.
final Duration speed;
/// The [Curve] of the rate of change of animation over time.
///
/// By default it is set to Curves.linear.
final Curve curve;
///Action widgets for text selection
final List<Widget> Function(String selectedText)? selectionActions;
/// Cursor text. Defaults to underscore.
final String cursor;
TypewriterAnimatedText(
String text, {
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
this.speed = const Duration(milliseconds: 30),
this.curve = Curves.linear,
this.selectionActions,
this.cursor = '_',
}) : super(
text: text,
textAlign: textAlign,
textStyle: textStyle,
duration: speed * (text.characters.length + extraLengthForBlinks),
);
late Animation<double> _typewriterText;
@override
Duration get remaining =>
speed *
(textCharacters.length + extraLengthForBlinks - _typewriterText.value);
@override
void initAnimation(AnimationController controller) {
_typewriterText = CurveTween(
curve: curve,
).animate(controller);
}
@override
Widget completeText(BuildContext context) => RichText(
text: TextSpan(
children: [
if (selectionActions == null)
TextSpan(text: text, style: textStyle),
if (selectionActions != null)
WidgetSpan(
child: SelectableText(
text,
style: textStyle,
contextMenuBuilder: (context, editableTextState) {
return AdaptiveTextSelectionToolbar(
anchors: editableTextState.contextMenuAnchors,
children: selectionActions?.call(editableTextState
.currentTextEditingValue.text
.substring(
editableTextState
.currentTextEditingValue.selection.start,
editableTextState
.currentTextEditingValue.selection.end)),
);
},
),
),
TextSpan(
text: cursor,
style: const TextStyle(color: Colors.transparent),
)
],
style: textStyle,
),
textAlign: textAlign,
);
/// Widget showing partial text
@override
Widget animatedBuilder(BuildContext context, Widget? child) {
/// Output of CurveTween is in the range [0, 1] for majority of the curves.
/// It is converted to [0, textCharacters.length + extraLengthForBlinks].
final textLen = textCharacters.length;
final typewriterValue = (_typewriterText.value.clamp(0, 1) *
(textCharacters.length + extraLengthForBlinks))
.round();
var showCursor = true;
var visibleString = text;
if (typewriterValue == 0) {
visibleString = '';
showCursor = false;
} else if (typewriterValue > textLen) {
showCursor = (typewriterValue - textLen) % 2 == 0;
} else {
visibleString = textCharacters.take(typewriterValue).toString();
}
return RichText(
text: TextSpan(
children: [
TextSpan(text: visibleString, style: textStyle),
TextSpan(
text: cursor,
style:
showCursor ? null : const TextStyle(color: Colors.transparent),
)
],
style: textStyle,
),
textAlign: textAlign,
);
}
}
/// Animation that displays [text] elements, as if they are being typed one
/// character at a time. Similar to [TyperAnimatedTextKit], but shows a cursor.
///
/// 
@Deprecated('Use AnimatedTextKit with TypewriterAnimatedText instead.')
class TypewriterAnimatedTextKit extends AnimatedTextKit {
TypewriterAnimatedTextKit({
Key? key,
required List<String> text,
TextAlign textAlign = TextAlign.start,
required TextStyle textStyle,
Duration speed = const Duration(milliseconds: 30),
Duration pause = const Duration(milliseconds: 1000),
bool displayFullTextOnTap = false,
bool stopPauseOnTap = false,
VoidCallback? onTap,
void Function(int, bool)? onNext,
void Function(int, bool)? onNextBeforePause,
VoidCallback? onFinished,
bool isRepeatingAnimation = true,
bool repeatForever = true,
int totalRepeatCount = 3,
Curve curve = Curves.linear,
}) : super(
key: key,
animatedTexts:
_animatedTexts(text, textAlign, textStyle, speed, curve),
pause: pause,
displayFullTextOnTap: displayFullTextOnTap,
stopPauseOnTap: stopPauseOnTap,
onTap: onTap,
onNext: onNext,
onNextBeforePause: onNextBeforePause,
onFinished: onFinished,
isRepeatingAnimation: isRepeatingAnimation,
repeatForever: repeatForever,
totalRepeatCount: totalRepeatCount,
);
static List<AnimatedText> _animatedTexts(
List<String> text,
TextAlign textAlign,
TextStyle textStyle,
Duration speed,
Curve curve,
) =>
text
.map((_) => TypewriterAnimatedText(
_,
textAlign: textAlign,
textStyle: textStyle,
speed: speed,
curve: curve,
))
.toList();
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/rotate.dart
|
import 'package:flutter/material.dart';
import 'animated_text.dart';
/// Animated Text that rotates a [Text] in and then out.
///
/// 
class RotateAnimatedText extends AnimatedText {
/// Transition height.
///
/// By default it is set to [TextStyle.fontSize] * 10 / 3.
final double? transitionHeight;
/// Adds [AlignmentGeometry] property to the text in the widget.
///
/// By default it is set to [Alignment.center]
final AlignmentGeometry alignment;
/// Specifies the [TextDirection] for resolving alignment.
///
/// By default it is set to [TextDirection.ltr]
final TextDirection textDirection;
/// Controls whether the text:
/// * rotates in _and_ out (true), or
/// * just rotates _in_ (false).
///
/// Note that you may want to adjust the [duration] when mixing
/// [RotateAnimatedText] instances with mixed [rotateOut] values.
///
/// By default, it is set to true.
final bool rotateOut;
RotateAnimatedText(
String text, {
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
Duration duration = const Duration(milliseconds: 2000),
this.transitionHeight,
this.alignment = Alignment.center,
this.textDirection = TextDirection.ltr,
this.rotateOut = true,
}) : super(
text: text,
textAlign: textAlign,
textStyle: textStyle,
duration: duration,
);
late Animation<double> _fadeIn, _fadeOut;
late Animation<Alignment> _slideIn, _slideOut;
@override
void initAnimation(AnimationController controller) {
final direction = textDirection;
final inIntervalEnd = rotateOut ? 0.4 : 1.0;
_slideIn = AlignmentTween(
begin: Alignment.topCenter.add(alignment).resolve(direction),
end: Alignment.center.add(alignment).resolve(direction),
).animate(
CurvedAnimation(
parent: controller,
curve: Interval(0.0, inIntervalEnd, curve: Curves.linear),
),
);
_fadeIn = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: controller,
curve: Interval(0.0, inIntervalEnd, curve: Curves.easeOut),
),
);
if (rotateOut) {
_slideOut = AlignmentTween(
begin: Alignment.center.add(alignment).resolve(direction),
end: Alignment.bottomCenter.add(alignment).resolve(direction),
).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.7, 1.0, curve: Curves.linear),
),
);
_fadeOut = Tween<double>(begin: 1.0, end: 0.0).animate(
CurvedAnimation(
parent: controller,
curve: const Interval(0.7, 1.0, curve: Curves.easeIn),
),
);
}
}
@override
Widget completeText(BuildContext context) =>
rotateOut ? SizedBox.shrink() : super.completeText(context);
@override
Widget animatedBuilder(BuildContext context, Widget? child) {
final fontSize =
textStyle?.fontSize ?? DefaultTextStyle.of(context).style.fontSize;
return SizedBox(
height: transitionHeight ?? (fontSize! * 10 / 3),
child: AlignTransition(
alignment: _slideIn.value.y != 0.0 || !rotateOut ? _slideIn : _slideOut,
child: Opacity(
opacity: _fadeIn.value != 1.0 || !rotateOut
? _fadeIn.value
: _fadeOut.value,
child: textWidget(text),
),
),
);
}
}
/// Animation that displays [text] elements, rotating them in one at a time.
///
/// 
@Deprecated('Use AnimatedTextKit with RotateAnimatedText instead.')
class RotateAnimatedTextKit extends AnimatedTextKit {
RotateAnimatedTextKit({
Key? key,
required List<String> text,
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
double? transitionHeight,
AlignmentGeometry alignment = Alignment.center,
TextDirection textDirection = TextDirection.ltr,
Duration duration = const Duration(milliseconds: 2000),
Duration pause = const Duration(milliseconds: 500),
VoidCallback? onTap,
void Function(int, bool)? onNext,
void Function(int, bool)? onNextBeforePause,
VoidCallback? onFinished,
bool isRepeatingAnimation = true,
int totalRepeatCount = 3,
bool repeatForever = false,
bool displayFullTextOnTap = false,
bool stopPauseOnTap = false,
}) : super(
key: key,
animatedTexts: _animatedTexts(
text,
textAlign,
textStyle,
duration,
transitionHeight,
alignment,
textDirection,
),
pause: pause,
displayFullTextOnTap: displayFullTextOnTap,
stopPauseOnTap: stopPauseOnTap,
onTap: onTap,
onNext: onNext,
onNextBeforePause: onNextBeforePause,
onFinished: onFinished,
isRepeatingAnimation: isRepeatingAnimation,
totalRepeatCount: totalRepeatCount,
repeatForever: repeatForever,
);
static List<AnimatedText> _animatedTexts(
List<String> text,
TextAlign textAlign,
TextStyle? textStyle,
Duration duration,
double? transitionHeight,
AlignmentGeometry alignment,
TextDirection textDirection,
) =>
text
.map((_) => RotateAnimatedText(
_,
textAlign: textAlign,
textStyle: textStyle,
duration: duration,
transitionHeight: transitionHeight,
alignment: alignment,
textDirection: textDirection,
))
.toList();
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/flicker.dart
|
import 'package:flutter/material.dart';
import 'animated_text.dart';
/// Animated Text that displays a [Text] element, as a flickering glow text.
///
/// 
class FlickerAnimatedText extends AnimatedText {
/// Marks ending of flickering entry interval of text
final double entryEnd;
final Duration speed;
FlickerAnimatedText(
String text, {
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
this.speed = const Duration(milliseconds: 1600),
this.entryEnd = 0.5,
}) : super(
text: text,
textStyle: textStyle,
duration: speed,
);
late Animation<double> _entry;
@override
void initAnimation(AnimationController controller) {
_entry = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: controller,
curve: Interval(0.0, entryEnd, curve: Curves.bounceIn),
),
);
}
@override
Widget completeText(BuildContext context) => SizedBox.shrink();
@override
Widget animatedBuilder(BuildContext context, Widget? child) {
return Opacity(
opacity: _entry.value != 1.0 ? _entry.value : _entry.value,
child: textWidget(text),
);
}
}
@Deprecated('Use AnimatedTextKit with FlickerAnimatedText instead.')
class FlickerAnimatedTextKit extends AnimatedTextKit {
FlickerAnimatedTextKit({
Key? key,
required List<String> text,
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
TextDirection textDirection = TextDirection.ltr,
Duration speed = const Duration(milliseconds: 1600),
double entryEnd = 0.5,
VoidCallback? onTap,
void Function(int, bool)? onNext,
void Function(int, bool)? onNextBeforePause,
VoidCallback? onFinished,
bool isRepeatingAnimation = true,
int totalRepeatCount = 3,
bool repeatForever = false,
bool displayFullTextOnTap = false,
bool stopPauseOnTap = false,
}) : super(
key: key,
animatedTexts:
_animatedTexts(text, textAlign, textStyle, speed, entryEnd),
onTap: onTap,
onNext: onNext,
onNextBeforePause: onNextBeforePause,
onFinished: onFinished,
isRepeatingAnimation: isRepeatingAnimation,
totalRepeatCount: totalRepeatCount,
repeatForever: repeatForever,
displayFullTextOnTap: displayFullTextOnTap,
stopPauseOnTap: stopPauseOnTap,
);
static List<AnimatedText> _animatedTexts(
List<String> text,
TextAlign textAlign,
TextStyle? textStyle,
Duration speed,
double entryEnd,
) =>
text
.map((_) => FlickerAnimatedText(
_,
textAlign: textAlign,
textStyle: textStyle,
speed: speed,
entryEnd: entryEnd,
))
.toList();
}
| 0
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib
|
mirrored_repositories/stories-app/lib/common/widgets/animated_text/lib/src/fade.dart
|
import 'package:flutter/material.dart';
import 'animated_text.dart';
/// Animated Text that displays a [Text] element, fading it in and then out.
///
/// 
class FadeAnimatedText extends AnimatedText {
/// Marks ending of fade-in interval, default value = 0.5
final double fadeInEnd;
/// Marks the beginning of fade-out interval, default value = 0.8
final double fadeOutBegin;
FadeAnimatedText(
String text, {
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
Duration duration = const Duration(milliseconds: 2000),
this.fadeInEnd = 0.5,
this.fadeOutBegin = 0.8,
}) : assert(fadeInEnd < fadeOutBegin,
'The "fadeInEnd" argument must be less than "fadeOutBegin"'),
super(
text: text,
textAlign: textAlign,
textStyle: textStyle,
duration: duration,
);
late Animation<double> _fadeIn, _fadeOut;
@override
void initAnimation(AnimationController controller) {
_fadeIn = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: controller,
curve: Interval(0.0, fadeInEnd, curve: Curves.linear),
),
);
_fadeOut = Tween<double>(begin: 1.0, end: 0.0).animate(
CurvedAnimation(
parent: controller,
curve: Interval(fadeOutBegin, 1.0, curve: Curves.linear),
),
);
}
@override
Widget completeText(BuildContext context) => SizedBox.shrink();
@override
Widget animatedBuilder(BuildContext context, Widget? child) {
return Opacity(
opacity: _fadeIn.value != 1.0 ? _fadeIn.value : _fadeOut.value,
child: textWidget(text),
);
}
}
/// Animation that displays [text] elements, fading them in and then out.
///
/// 
@Deprecated('Use AnimatedTextKit with FadeAnimatedText instead.')
class FadeAnimatedTextKit extends AnimatedTextKit {
FadeAnimatedTextKit({
Key? key,
required List<String> text,
TextAlign textAlign = TextAlign.start,
TextStyle? textStyle,
Duration duration = const Duration(milliseconds: 2000),
Duration pause = const Duration(milliseconds: 500),
double fadeInEnd = 0.5,
double fadeOutBegin = 0.8,
VoidCallback? onTap,
void Function(int, bool)? onNext,
void Function(int, bool)? onNextBeforePause,
VoidCallback? onFinished,
bool isRepeatingAnimation = true,
int totalRepeatCount = 3,
bool repeatForever = false,
bool displayFullTextOnTap = false,
bool stopPauseOnTap = false,
}) : super(
key: key,
animatedTexts: _animatedTexts(
text, textAlign, textStyle, duration, fadeInEnd, fadeOutBegin),
pause: pause,
displayFullTextOnTap: displayFullTextOnTap,
stopPauseOnTap: stopPauseOnTap,
onTap: onTap,
onNext: onNext,
onNextBeforePause: onNextBeforePause,
onFinished: onFinished,
isRepeatingAnimation: isRepeatingAnimation,
totalRepeatCount: totalRepeatCount,
repeatForever: repeatForever,
);
static List<AnimatedText> _animatedTexts(
List<String> text,
TextAlign textAlign,
TextStyle? textStyle,
Duration duration,
double fadeInEnd,
double fadeOutBegin,
) =>
text
.map((_) => FadeAnimatedText(
_,
textAlign: textAlign,
textStyle: textStyle,
duration: duration,
fadeInEnd: fadeInEnd,
fadeOutBegin: fadeOutBegin,
))
.toList();
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/resource/keys.dart
|
abstract class Keys {
static String token = "token";
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/resource/decorations.dart
|
import 'package:flutter/cupertino.dart';
import 'colors.dart';
class DefaultBackgroundDecoration extends BoxDecoration {
final double? radius;
@override
BorderRadiusGeometry? get borderRadius => BorderRadius.circular(radius ?? 0);
@override
Color? get color => AppColors.primaryColor;
@override
Gradient? get gradient => LinearGradient(
colors: [
AppColors.primaryColor,
AppColors.primaryColorBlack,
],
begin: Alignment.bottomCenter,
end: Alignment.topLeft,
stops: const [0.0, 1],
tileMode: TileMode.clamp);
const DefaultBackgroundDecoration({
this.radius,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/resource/constants.dart
|
abstract class Constants {
static String appUrl =
"https://play.google.com/store/apps/details?id=xaldarof.stories.app";
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/resource/colors.dart
|
import 'package:flutter/material.dart';
class AppColors {
static Color primaryColor = const Color(0xFF0C1A0D);
static Color darkGreen = const Color(0xFF043C14);
static Color darkSpringGreen = const Color(0xffc6e3cc);
static Color primaryColorBlack = const Color(0xFF060A06);
static Color primaryDark = const Color(0xFF050A0F);
static Color black12 = Colors.black12;
static Color whiteAlpha52 = Colors.white.withAlpha(52);
static var black = Colors.black;
static var white = Colors.white;
static var grey = Colors.grey;
static var gold = const Color(0xFFE7BF20);
static var blue = const Color(0xFF20D0E7);
static Color red = const Color(0xFF8F2727);
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/resource/fonts.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/src/painting/text_style.dart';
import 'package:google_fonts/google_fonts.dart';
TextStyle primaryTextStyle(
{Color? color = Colors.white,
FontWeight? fontWeight = FontWeight.normal,
double? fontSize = 14}) {
return GoogleFonts.nunito(
color: color,
fontWeight: fontWeight,
fontSize: fontSize,
);
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/language/language.dart
|
import 'package:flutter/cupertino.dart';
import 'package:modified_localization/easy_localization.dart';
class Language {
static List<Locale> get supportedLanguages {
return [
const Locale('ru', 'RU'),
const Locale('uz', 'UZ'),
const Locale('en', 'US'),
];
}
static List<LanguageInfo> get supportedLanguagesInfo {
var languages = [
LanguageInfo(
title: 'Русский',
locale: supportedLanguages[0],
id: 1),
LanguageInfo(
title: 'Uzbek',
locale: supportedLanguages[1],
id: 2),
LanguageInfo(
title: 'English',
locale: supportedLanguages[2],
id: 0),
];
return languages;
}
static Locale get defaultLanguage {
return supportedLanguages[0];
}
static String get languagePath {
return "assets/translations";
}
}
extension LangExt on BuildContext {
LanguageInfo get localeInfo {
return Language.supportedLanguagesInfo
.where((element) => element.locale.countryCode == locale.countryCode)
.toList()[0];
}
}
class LanguageInfo {
final int id;
final String title;
final Locale locale;
const LanguageInfo({
required this.id,
required this.title,
required this.locale,
});
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/extensions/array.dart
|
extension ListExt<T> on List<T>? {
bool get isNullOrEmpty => this == null || this?.isEmpty == true;
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/extensions/controller_ext.dart
|
import 'package:flutter/material.dart';
extension ScrollExt on ScrollController {
void setupScrollListener({Function? onAtTop, Function? onAtBottom}) {
addListener(() {
if (position.atEdge) {
if (position.pixels == 0) {
onAtTop?.call();
} else {
onAtBottom?.call();
}
}
});
}
void onBottomReached(Function() invoker) {
addListener(() {
if (offset >= position.maxScrollExtent && !position.outOfRange) {
invoker.call();
}
});
}
void onTopReached(Function(bool) onReach) {
addListener(() {
if (offset <= position.minScrollExtent && !position.outOfRange) {
onReach.call(true);
} else {}
});
}
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/utils/printer.dart
|
import 'package:flutter/foundation.dart';
import 'package:another_flushbar/flushbar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import '../resource/colors.dart';
void printMessage(dynamic message) {
if (kDebugMode) {
print(message);
}
}
enum MessageStatus { success, fail, informative }
extension ContextExt on BuildContext {
void showSnackBar(String? message,
{MessageStatus status = MessageStatus.success}) {
if (message != null) {
Color backColor = AppColors.darkGreen;
if (status == MessageStatus.fail) {
backColor = AppColors.red;
}
Flushbar(
maxWidth: 400,
flushbarPosition: FlushbarPosition.TOP,
duration: const Duration(seconds: 2),
messageSize: 16,
messageText: Text(
message,
style: primaryTextStyle(),
),
backgroundColor: backColor,
borderRadius: BorderRadius.circular(16),
margin: const EdgeInsets.all(24),
).show(this);
}
}
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/utils/date.dart
|
import 'package:intl/intl.dart';
extension DateTimeExt on DateTime {
String toDdMm() {
return "${_convert(day)}.${_convert(month)}.${_convert(year)}";
}
String toDdMmHmMm() {
return "${_convert(day)}.${_convert(month)}.${_convert(year)} ${_convert(hour)}:${_convert(minute)}";
}
String _convert(int? num) {
if (num! < 10 && num >= 0) {
return "0$num";
} else {
return num.toString();
}
}
}
extension DateInt on int {
String toDate() {
var date = DateTime.fromMillisecondsSinceEpoch(this);
date = date.copyWith(hour: date.hour + 5);
return "${date.day}.${date.month}.${date.year} ${date.hour}:${date.minute}:${date.second}";
}
}
extension DateFormatExt on String {
String toDate() {
try {
DateTime now = DateTime.parse(this);
now = now.copyWith(hour: now.hour + 5);
var formatter = DateFormat('dd.MM.yyyy HH:mm');
var formatted = formatter.format(now);
return formatted;
} catch (e) {
return this;
}
}
DateTime toDateTime() {
DateTime now = DateTime.parse(this);
return now;
}
String toIso() {
DateTime date = DateTime.parse(this);
return date.toIso8601String();
}
bool isToday() {
DateTime date = DateTime.parse(this);
DateTime today = DateTime.now();
return "${date.day}${date.month}${date.year}" ==
"${today.day}${today.month}${today.year}";
}
}
String today() {
DateTime today = DateTime.now();
return "${today.day}${today.month}${today.year}";
}
extension DateTimeExtNullable on DateTime? {
String? toDDMM() {
return this == null
? null
: "${(_convert(this?.day))}.${(_convert(this?.month))}.${(_convert(this?.year))}";
}
String _convert(int? num) {
if (num! < 10 && num >= 0) {
return "0$num";
} else {
return num.toString();
}
}
}
extension DateTimeExtStrList on List<String> {
String? lastDate() {
if (isNotEmpty) {
try {
var max = DateFormat("dd-MM-yyyy").parse(this[0]);
forEach((element) {
DateTime tempDate = DateFormat("dd-MM-yyyy").parse(element);
if (tempDate.isAfter(max)) {
max = tempDate;
}
});
return max.toDdMm();
} catch (e) {
try {
var max = DateTime.parse(this[0]);
forEach((element) {
DateTime tempDate = DateTime.parse(element);
if (tempDate.isAfter(max)) {
max = tempDate;
}
});
return max.toDdMm();
} catch (e) {
return null;
}
}
} else {
return null;
}
}
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/utils/bloc.dart
|
import 'package:bloc/bloc.dart';
import 'package:rxdart/rxdart.dart';
EventTransformer<Event> debounceSequential<Event>(Duration duration) {
return (events, mapper) => events.debounceTime(duration).asyncExpand(mapper);
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/utils/file.dart
|
import 'package:path_provider/path_provider.dart';
abstract class FileUtils {
static Future<String> generateFilePath(String ext) async {
return "${(await getApplicationDocumentsDirectory()).path}/${DateTime.now().microsecondsSinceEpoch.toString()}.$ext";
}
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/utils/size.dart
|
import 'package:flutter/cupertino.dart';
extension ContentExt on BuildContext {
double get width => MediaQuery.of(this).size.width;
double get height => MediaQuery.of(this).size.height;
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/utils/strings.dart
|
extension StringExt on String {
String cut(int count) {
return length > count ? "${substring(0, count)}..." : this;
}
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/utils/ui.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import '../resource/colors.dart';
void unFocus() {
FocusManager.instance.primaryFocus?.unfocus();
}
void setNavColor() {
var mySystemTheme = SystemUiOverlayStyle.light
.copyWith(systemNavigationBarColor: AppColors.black);
SystemChrome.setSystemUIOverlayStyle(mySystemTheme);
}
| 0
|
mirrored_repositories/stories-app/lib/common
|
mirrored_repositories/stories-app/lib/common/utils/navigator.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
extension NavigatorCustom<T> on BuildContext {
void navigateTo(Widget widget, {bool removeStack = false}) {
Navigator.push(
this,
CupertinoPageRoute(builder: (context) => widget),
);
if (removeStack) {
Navigator.of(this).pushAndRemoveUntil(CupertinoPageRoute(builder: (context) => widget), (Route<dynamic> route) => false);
}
}
void goBack() {
Navigator.pop(this);
}
}
abstract class NavigationModuleController {
void navigate(Module module) {}
}
enum Module { home, fullScreenQuotes, publish, myQuotes, profile }
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/notification_response.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'notification_response.g.dart';
@JsonSerializable()
class NotificationResponse {
final int id;
final String content;
final bool isRead;
final String timeCreate;
const NotificationResponse({
required this.id,
required this.content,
required this.isRead,
required this.timeCreate,
});
factory NotificationResponse.fromJson(Map<String, dynamic> json) =>
_$NotificationResponseFromJson(json);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/story_quote_response.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'story_quote_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
StoryQuoteResponse _$StoryQuoteResponseFromJson(Map<String, dynamic> json) =>
StoryQuoteResponse(
id: json['id'] as int,
storyId: json['storyId'] as int,
body: json['body'] as String,
timeCreate: json['timeCreate'] as String,
author: StoryQuoteAuthorResponse.fromJson(
json['author'] as Map<String, dynamic>),
isOwner: json['isOwner'] as bool,
);
Map<String, dynamic> _$StoryQuoteResponseToJson(StoryQuoteResponse instance) =>
<String, dynamic>{
'id': instance.id,
'storyId': instance.storyId,
'body': instance.body,
'author': instance.author,
'timeCreate': instance.timeCreate,
'isOwner': instance.isOwner,
};
StoryQuoteAuthorResponse _$StoryQuoteAuthorResponseFromJson(
Map<String, dynamic> json) =>
StoryQuoteAuthorResponse(
username: json['username'] as String,
id: json['id'] as int,
);
Map<String, dynamic> _$StoryQuoteAuthorResponseToJson(
StoryQuoteAuthorResponse instance) =>
<String, dynamic>{
'username': instance.username,
'id': instance.id,
};
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/auth_response.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'auth_response.g.dart';
@JsonSerializable()
class AuthResponse {
final String access;
const AuthResponse({
required this.access,
});
factory AuthResponse.fromJson(Map<String, dynamic> json) =>
_$AuthResponseFromJson(json);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/profile_stats_response.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'profile_stats_response.g.dart';
@JsonSerializable()
class ProfileStatsResponse {
final int readStoriesCount;
final int storyCount;
final int viewReachCount;
final int unreadNotificationCount;
const ProfileStatsResponse({
required this.readStoriesCount,
required this.storyCount,
required this.viewReachCount,
required this.unreadNotificationCount,
});
factory ProfileStatsResponse.fromJson(Map<String, dynamic> json) =>
_$ProfileStatsResponseFromJson(json);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/category_response.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'category_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CategoryResponse _$CategoryResponseFromJson(Map<String, dynamic> json) =>
CategoryResponse(
id: json['id'] as int,
name: json['name'] as String,
count: json['count'] as int,
);
Map<String, dynamic> _$CategoryResponseToJson(CategoryResponse instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'count': instance.count,
};
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/profile_stats_response.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'profile_stats_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ProfileStatsResponse _$ProfileStatsResponseFromJson(
Map<String, dynamic> json) =>
ProfileStatsResponse(
readStoriesCount: json['readStoriesCount'] as int,
storyCount: json['storyCount'] as int,
viewReachCount: json['viewReachCount'] as int,
unreadNotificationCount: json['unreadNotificationCount'] as int,
);
Map<String, dynamic> _$ProfileStatsResponseToJson(
ProfileStatsResponse instance) =>
<String, dynamic>{
'readStoriesCount': instance.readStoriesCount,
'storyCount': instance.storyCount,
'viewReachCount': instance.viewReachCount,
'unreadNotificationCount': instance.unreadNotificationCount,
};
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/notification_response.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'notification_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
NotificationResponse _$NotificationResponseFromJson(
Map<String, dynamic> json) =>
NotificationResponse(
id: json['id'] as int,
content: json['content'] as String,
isRead: json['isRead'] as bool,
timeCreate: json['timeCreate'] as String,
);
Map<String, dynamic> _$NotificationResponseToJson(
NotificationResponse instance) =>
<String, dynamic>{
'id': instance.id,
'content': instance.content,
'isRead': instance.isRead,
'timeCreate': instance.timeCreate,
};
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/profile_response.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'profile_response.g.dart';
@JsonSerializable()
class UserResponse {
final int id;
final String username;
final String? email;
final String? firstName;
final String? lastName;
final String dateJoined;
final int? score;
final bool? isMe;
const UserResponse({
required this.id,
required this.username,
this.email,
this.firstName,
this.score,
this.lastName,
this.isMe,
required this.dateJoined,
});
factory UserResponse.fromJson(Map<String, dynamic> json) =>
_$UserResponseFromJson(json);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/story_response.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'story_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
StoryResponse _$StoryResponseFromJson(Map<String, dynamic> json) =>
StoryResponse(
id: json['id'] as int,
body: json['body'] as String,
timeCreate: json['timeCreate'] as String,
categoryId: json['categoryId'] as int,
author:
StoryAuthorResponse.fromJson(json['author'] as Map<String, dynamic>),
title: json['title'] as String,
viewCount: json['viewCount'] as int,
isFrozen: json['isFrozen'] as bool,
isPublished: json['isPublished'] as bool?,
isPremium: json['isPremium'] as bool,
isOwner: json['isOwner'] as bool,
);
Map<String, dynamic> _$StoryResponseToJson(StoryResponse instance) =>
<String, dynamic>{
'id': instance.id,
'body': instance.body,
'timeCreate': instance.timeCreate,
'categoryId': instance.categoryId,
'author': instance.author,
'title': instance.title,
'viewCount': instance.viewCount,
'isPremium': instance.isPremium,
'isFrozen': instance.isFrozen,
'isOwner': instance.isOwner,
'isPublished': instance.isPublished,
};
StoryAuthorResponse _$StoryAuthorResponseFromJson(Map<String, dynamic> json) =>
StoryAuthorResponse(
username: json['username'] as String,
userid: json['userid'] as int,
);
Map<String, dynamic> _$StoryAuthorResponseToJson(
StoryAuthorResponse instance) =>
<String, dynamic>{
'username': instance.username,
'userid': instance.userid,
};
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/category_response.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'category_response.g.dart';
@JsonSerializable()
class CategoryResponse {
final int id;
final String name;
final int count;
const CategoryResponse({
required this.id,
required this.name,
required this.count,
});
factory CategoryResponse.fromJson(Map<String, dynamic> json) =>
_$CategoryResponseFromJson(json);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/story_response.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'story_response.g.dart';
@JsonSerializable()
class StoryResponse {
final int id;
final String body;
final String timeCreate;
final int categoryId;
final StoryAuthorResponse author;
final String title;
final int viewCount;
final bool isPremium;
final bool isFrozen;
final bool isOwner;
final bool? isPublished;
const StoryResponse({
required this.id,
required this.body,
required this.timeCreate,
required this.categoryId,
required this.author,
required this.title,
required this.viewCount,
required this.isFrozen,
required this.isPublished,
required this.isPremium,
required this.isOwner,
});
factory StoryResponse.fromJson(Map<String, dynamic> json) =>
_$StoryResponseFromJson(json);
}
@JsonSerializable()
class StoryAuthorResponse {
final String username;
final int userid;
const StoryAuthorResponse({
required this.username,
required this.userid,
});
factory StoryAuthorResponse.fromJson(Map<String, dynamic> json) =>
_$StoryAuthorResponseFromJson(json);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/story_quote_response.dart
|
import 'package:json_annotation/json_annotation.dart';
part 'story_quote_response.g.dart';
@JsonSerializable()
class StoryQuoteResponse {
final int id;
final int storyId;
final String body;
final StoryQuoteAuthorResponse author;
final String timeCreate;
final bool isOwner;
const StoryQuoteResponse({
required this.id,
required this.storyId,
required this.body,
required this.timeCreate,
required this.author,
required this.isOwner,
});
factory StoryQuoteResponse.fromJson(Map<String, dynamic> json) =>
_$StoryQuoteResponseFromJson(json);
}
@JsonSerializable()
class StoryQuoteAuthorResponse {
final String username;
final int id;
const StoryQuoteAuthorResponse({
required this.username,
required this.id,
});
factory StoryQuoteAuthorResponse.fromJson(Map<String, dynamic> json) =>
_$StoryQuoteAuthorResponseFromJson(json);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/auth_response.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'auth_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
AuthResponse _$AuthResponseFromJson(Map<String, dynamic> json) => AuthResponse(
access: json['access'] as String,
);
Map<String, dynamic> _$AuthResponseToJson(AuthResponse instance) =>
<String, dynamic>{
'access': instance.access,
};
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/network/profile_response.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'profile_response.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
UserResponse _$UserResponseFromJson(Map<String, dynamic> json) => UserResponse(
id: json['id'] as int,
username: json['username'] as String,
email: json['email'] as String?,
firstName: json['firstName'] as String?,
score: json['score'] as int?,
lastName: json['lastName'] as String?,
isMe: json['isMe'] as bool?,
dateJoined: json['dateJoined'] as String,
);
Map<String, dynamic> _$UserResponseToJson(UserResponse instance) =>
<String, dynamic>{
'id': instance.id,
'username': instance.username,
'email': instance.email,
'firstName': instance.firstName,
'lastName': instance.lastName,
'dateJoined': instance.dateJoined,
'score': instance.score,
'isMe': instance.isMe,
};
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/cache/story_cache.dart
|
import 'package:drift/drift.dart';
@DataClassName('StoryCache')
class StoryCacheTable extends Table {
IntColumn get id => integer()();
TextColumn get body => text()();
Column<DateTime> get timeCreate => dateTime()();
IntColumn get categoryId => integer()();
IntColumn get authorId => integer()();
TextColumn get authorName => text()();
TextColumn get title => text()();
IntColumn get viewCount => integer()();
BoolColumn get isPremium => boolean()();
BoolColumn get isFrozen => boolean()();
BoolColumn get isOwner => boolean()();
BoolColumn get isPublished => boolean()();
@override
Set<Column<Object>>? get primaryKey => {
id,
};
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/common/base_response.dart
|
class BaseResponse<T> {
T data;
BaseResponse(this.data);
factory BaseResponse.fromJson(
Map<String, dynamic> json, Function(Map<String, dynamic>) build) {
return BaseResponse(build(json['results']));
}
factory BaseResponse.fromJsonSingle(Map<String, dynamic> json) {
return BaseResponse(json['results'] as T);
}
factory BaseResponse.fromJsonStringData(Map<String, dynamic> json) {
return BaseResponse(json['results'] as T);
}
}
class BaseListResponse {
List<dynamic> data;
BaseListResponse(this.data);
factory BaseListResponse.fromJson(Map<String, dynamic> json) {
return BaseListResponse((json['results'] as List<dynamic>));
}
factory BaseListResponse.fromJsonStringData(Map<String, dynamic> json) {
return BaseListResponse(json['results'] as dynamic);
}
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/common/app_state.dart
|
enum AppState {
logged,
unAuthorized,
initial,
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/common/domain_result.dart
|
abstract class DomainResult {}
class DomainSuccess<T> extends DomainResult {
final T? data;
DomainSuccess({
this.data,
});
}
class DomainFail<T> extends DomainResult {
final T? data;
DomainFail({
this.data,
});
}
class DomainLoading<T> extends DomainResult {
final T? data;
DomainLoading({
this.data,
});
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/ui/profile.dart
|
class User {
final int id;
final String username;
final String? email;
final String? firstName;
final String? lastName;
final String dateJoined;
final int? score;
final bool? isMe;
const User({
required this.id,
required this.username,
this.email,
this.score,
this.firstName,
this.lastName,
this.isMe,
required this.dateJoined,
});
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/ui/profile_stats.dart
|
class ProfileStats {
final int readStoriesCount;
final int storyCount;
final int viewReachCount;
final int unreadNotificationCount;
const ProfileStats({
required this.readStoriesCount,
required this.storyCount,
required this.viewReachCount,
required this.unreadNotificationCount,
});
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/ui/notification.dart
|
class UserNotification {
final int id;
final String content;
final bool isRead;
final String timeCreate;
const UserNotification({
required this.id,
required this.content,
required this.isRead,
required this.timeCreate,
});
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/ui/category.dart
|
class Category {
final int id;
final String name;
final int count;
const Category({
required this.id,
required this.name,
required this.count,
});
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/ui/story_quote.dart
|
class StoryQuote {
final String timeCreate;
final String body;
final String username;
final int userId;
final bool isOwner;
const StoryQuote({
required this.timeCreate,
required this.body,
required this.username,
required this.userId,
required this.isOwner,
});
}
| 0
|
mirrored_repositories/stories-app/lib/domain/models
|
mirrored_repositories/stories-app/lib/domain/models/ui/story.dart
|
class Story {
final int id;
final String body;
final String timeCreate;
final int categoryId;
final int authorId;
final String authorName;
final String title;
final int viewCount;
final bool isPremium;
final bool isEnabled;
final bool canModify;
final bool isPublished;
const Story({
required this.id,
required this.body,
required this.timeCreate,
required this.categoryId,
required this.authorId,
required this.isPublished,
required this.authorName,
required this.title,
required this.isEnabled,
required this.isPremium,
required this.canModify,
required this.viewCount,
});
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/network/stories_network_data_source.dart
|
import 'package:jokes_app/domain/models/network/story_response.dart';
import '../../models/network/category_response.dart';
abstract class StoriesNetworkDataSource {
Future<List<StoryResponse>?> getStories(int? categoryId, int page);
Future<List<CategoryResponse>?> getCategories();
Future<void> setAsRead(int storyId);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/network/main_network_data_source.dart
|
abstract class MainNetworkDataSource {
Future<bool> refreshFCMToken(String token);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/network/global_network_data_source.dart
|
import '../../models/network/profile_response.dart';
abstract class GlobalNetworkDataSource {
Future<List<UserResponse>> getTopUsers();
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/network/auth_network_data_source.dart
|
import '../../models/network/auth_response.dart';
abstract class AuthNetworkDataSource {
Future<AuthResponse> login(String username, String password, String fcmToken);
Future<AuthResponse> register(
String username, String password, String fcmToken);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/network/story_quotes_network_data_source.dart
|
import 'package:jokes_app/domain/models/network/story_quote_response.dart';
abstract class StoryQuotesNetworkDataSource {
Future<List<StoryQuoteResponse>> getQuotes(int storyId);
Future<bool> createQuote(int storyId, String body);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/network/publish_network_data_source.dart
|
import '../../models/network/category_response.dart';
abstract class PublishNetworkDataSource {
Future<bool> publishStory(String body, String title, int categoryId);
Future<List<CategoryResponse>?> getCategories();
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/network/view_story_network_data_source.dart
|
abstract class ViewStoryNetworkDataSource {
Future<bool> unpublish(int storyId, bool state);
Future<bool> createQuote(int storyId, String body);
Future<bool> report(int storyId);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/network/profile_network_data_source.dart
|
import 'package:jokes_app/domain/models/network/notification_response.dart';
import '../../models/network/category_response.dart';
import '../../models/network/profile_response.dart';
import '../../models/network/profile_stats_response.dart';
import '../../models/network/story_response.dart';
abstract class ProfileNetworkDataSource {
Future<UserResponse> getProfile();
Future<ProfileStatsResponse> getStats();
Future<List<StoryResponse>?> getStories(
int userId, int? categoryId, int page);
Future<List<CategoryResponse>?> getCategories(int userId);
Future<void> setAsRead(int storyId);
Future<List<NotificationResponse>> getNotifications();
Future<bool> setNotificationRead(int notificationId);
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/cache/profile_cache_data_source.dart
|
abstract class ProfileCacheDataSource {
Future<void> clearAllCache();
}
| 0
|
mirrored_repositories/stories-app/lib/domain/data_sources
|
mirrored_repositories/stories-app/lib/domain/data_sources/cache/main_data_source.dart
|
abstract class MainDataSource {
Stream<String> getToken();
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/repositories/view_story_repository.dart
|
import '../models/common/domain_result.dart';
abstract class ViewStoryRepository {
Stream<DomainResult> unpublish(int storyId, bool state);
Stream<DomainResult> createQuote(int storyId, String body);
Future<bool> sendReport(int storyId);
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/repositories/main_repository.dart
|
import '../models/common/app_state.dart';
abstract class MainRepository {
Stream<AppState> getAppState();
Future<bool> isAuthorized();
Future<bool> refreshFCMToken(String token);
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/repositories/stories_repository.dart
|
import '../models/common/domain_result.dart';
abstract class StoriesRepository {
Stream<DomainResult> getStories(int? categoryId, int page);
Stream<DomainResult> getCategories();
Future<void> setAsRead(int storyId);
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/repositories/profile_repository.dart
|
import '../models/common/domain_result.dart';
abstract class ProfileRepository {
Stream<DomainResult> getProfile();
Stream<DomainResult> getStats();
Stream<DomainResult> getStories(int userId, int? categoryId, int page);
Stream<DomainResult> getCategories(int userId);
Future<void> setAsRead(int storyId);
Stream<DomainResult> setNotificationRead(int notificationId);
Future<void> logout();
Stream<DomainResult> getNotifications();
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/repositories/global_repository.dart
|
import '../models/common/domain_result.dart';
abstract class GlobalRepository {
Stream<DomainResult> getTopUsers();
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/repositories/publish_repository.dart
|
import '../models/common/domain_result.dart';
abstract class PublishRepository {
Stream<DomainResult> publishStory(String body, String title, int categoryId);
Stream<DomainResult> getCategories();
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/repositories/story_quotes_repository.dart
|
abstract class StoryQuotesRepository {
Stream getQuotes(int storyId);
Stream createQuote(int storyId, String body);
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/repositories/auth_repository.dart
|
import '../models/common/domain_result.dart';
abstract class AuthRepository {
Stream<DomainResult> login(String username, String password);
Stream<DomainResult> register(String username, String password);
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/mappers/base_mapper.dart
|
abstract class Mapper<I, O> {
O map(I data);
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/mappers/category_mapper.dart
|
import 'package:jokes_app/domain/mappers/base_mapper.dart';
import 'package:jokes_app/domain/models/network/category_response.dart';
import 'package:jokes_app/domain/models/ui/category.dart';
class CategoryMapper extends Mapper<CategoryResponse, Category> {
@override
Category map(CategoryResponse data) {
return Category(
id: data.id,
name: "#${data.name}(${data.count})",
count: data.count,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/mappers/profile_mapper.dart
|
import 'package:jokes_app/common/utils/date.dart';
import 'package:jokes_app/domain/mappers/base_mapper.dart';
import 'package:jokes_app/domain/models/network/profile_response.dart';
import 'package:jokes_app/domain/models/ui/profile.dart';
class UserMapper extends Mapper<UserResponse, User> {
@override
User map(UserResponse data) {
return User(
id: data.id,
username: data.username,
dateJoined: data.dateJoined.toDate(),
firstName: data.firstName,
lastName: data.lastName,
email: data.email,
score: data.score,
isMe: data.isMe,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/mappers/profile_stats_mapper.dart
|
import 'package:jokes_app/domain/mappers/base_mapper.dart';
import 'package:jokes_app/domain/models/network/profile_stats_response.dart';
import 'package:jokes_app/domain/models/ui/profile_stats.dart';
class ProfileStatsMapper extends Mapper<ProfileStatsResponse, ProfileStats> {
@override
ProfileStats map(ProfileStatsResponse data) {
return ProfileStats(
readStoriesCount: data.readStoriesCount,
storyCount: data.storyCount,
unreadNotificationCount: data.unreadNotificationCount,
viewReachCount: data.viewReachCount);
}
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/mappers/story_quote_mapper.dart
|
import 'package:jokes_app/domain/mappers/base_mapper.dart';
import 'package:jokes_app/domain/models/network/story_quote_response.dart';
import 'package:jokes_app/domain/models/ui/story_quote.dart';
class StoryQuoteMapper extends Mapper<StoryQuoteResponse, StoryQuote> {
@override
StoryQuote map(StoryQuoteResponse data) {
return StoryQuote(
timeCreate: data.timeCreate,
body: data.body,
username: data.author.username,
userId: data.author.id,
isOwner: data.isOwner,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/mappers/notification_mapper.dart
|
import 'package:jokes_app/common/utils/date.dart';
import 'package:jokes_app/domain/mappers/base_mapper.dart';
import 'package:jokes_app/domain/models/network/notification_response.dart';
import 'package:jokes_app/domain/models/ui/notification.dart';
class NotificationMapper
extends Mapper<NotificationResponse, UserNotification> {
@override
UserNotification map(NotificationResponse data) {
return UserNotification(
id: data.id,
content: data.content,
isRead: data.isRead,
timeCreate: data.timeCreate.toDate(),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/domain
|
mirrored_repositories/stories-app/lib/domain/mappers/story_mapper.dart
|
import 'package:jokes_app/common/utils/date.dart';
import 'package:jokes_app/domain/mappers/base_mapper.dart';
import 'package:jokes_app/domain/models/network/story_response.dart';
import 'package:jokes_app/domain/models/ui/story.dart';
import '../../data/database/app_database.dart';
class StoryResponseToUiMapper extends Mapper<StoryResponse, Story> {
@override
Story map(StoryResponse data) {
return Story(
id: data.id,
body: data.body,
timeCreate: data.timeCreate.toDate(),
categoryId: data.categoryId,
authorId: data.author.userid,
authorName: data.author.username,
title: data.title,
viewCount: data.viewCount,
isEnabled: !data.isFrozen,
isPremium: data.isPremium,
canModify: data.isOwner,
isPublished: data.isPublished == true,
);
}
}
class StoryResponseToCacheMapper extends Mapper<StoryResponse, StoryCache> {
@override
StoryCache map(StoryResponse data) {
return StoryCache(
id: data.id,
body: data.body,
timeCreate: data.timeCreate.toDateTime(),
categoryId: data.categoryId,
authorId: data.author.userid,
authorName: data.author.username,
title: data.title,
viewCount: data.viewCount,
isPremium: data.isPremium,
isFrozen: data.isFrozen,
isOwner: data.isOwner,
isPublished: data.isPublished == null ? true : false,
);
}
}
class StoryCacheToUiMapper extends Mapper<StoryCache, Story> {
@override
Story map(StoryCache data) {
return Story(
id: data.id,
body: data.body,
timeCreate: data.timeCreate.toDdMmHmMm(),
categoryId: data.categoryId,
authorId: data.authorId,
authorName: data.authorName,
title: data.title,
viewCount: data.viewCount,
isEnabled: !data.isFrozen,
isPremium: data.isPremium,
canModify: data.isOwner,
isPublished: data.isPublished == true,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/main/main_screen.dart
|
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/generated/locale_keys.g.dart';
import 'package:jokes_app/ui/main/bloc/main_bloc.dart';
import 'package:jokes_app/ui/main/splash_screen.dart';
import 'package:modified_localization/easy_localization.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:quick_actions/quick_actions.dart';
import '../../common/utils/ui.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
class MainScreen extends StatefulWidget {
const MainScreen({super.key});
@override
State<MainScreen> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
setNavColor();
FirebaseMessaging.instance.getToken().then((value) {
printMessage("Current token : $value");
});
return BlocProvider<MainBloc>(
create: (_) => MainBloc(injector.get())
..add(
ObserveAppState(),
),
child: OverlaySupport.global(
child: MaterialApp(
navigatorKey: navigatorKey,
locale: context.locale,
supportedLocales: context.supportedLocales,
localizationsDelegates: context.localizationDelegates,
debugShowCheckedModeBanner: false,
home: BlocBuilder<MainBloc, MainState>(
builder: (BuildContext context, state) {
return const SplashScreen();
},
),
),
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/main/splash_screen.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/decorations.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/domain/models/common/app_state.dart';
import 'package:jokes_app/ui/auth/login/login_screen.dart';
import 'package:jokes_app/ui/home/home_screen.dart';
import 'package:jokes_app/ui/main/bloc/main_bloc.dart';
import 'package:lottie/lottie.dart';
import '../../assets.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => MainBloc(
injector.get(),
)..add(
GetAppStatus(),
),
child: BlocConsumer<MainBloc, MainState>(
builder: (context, state) {
return Container(
height: 52,
decoration: const DefaultBackgroundDecoration(),
padding: const EdgeInsets.all(100),
child: Lottie.asset(
Assets.writeJson,
frameRate: FrameRate.max,
width: 52,
height: 52,
),
);
},
listener: (context, state) {
if (state.appState == AppState.logged) {
context.navigateTo(const HomeScreen(), removeStack: true);
}
if (state.appState == AppState.unAuthorized) {
context.navigateTo(const LoginScreen(), removeStack: true);
}
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/main
|
mirrored_repositories/stories-app/lib/ui/main/bloc/main_state.dart
|
part of 'main_bloc.dart';
class MainState extends Equatable {
final AppState appState;
@override
List<Object?> get props => [
appState,
];
const MainState({
this.appState = AppState.initial,
});
MainState copyWith({
AppState? appState,
}) {
return MainState(
appState: appState ?? this.appState,
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/main
|
mirrored_repositories/stories-app/lib/ui/main/bloc/main_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/domain/models/common/app_state.dart';
import '../../../common/utils/bloc.dart';
import '../../../domain/repositories/main_repository.dart';
import '../main_screen.dart';
import '../splash_screen.dart';
part 'main_event.dart';
part 'main_state.dart';
class MainBloc extends Bloc<MainEvent, MainState> {
final MainRepository _repository;
MainBloc(
this._repository,
) : super(const MainState()) {
on<ObserveAppState>(_observeAppStatus);
on<GetAppStatus>(_getAppStatus,
transformer: debounceSequential(const Duration(seconds: 3)));
FirebaseMessaging.instance.onTokenRefresh.listen((event) async {
printMessage("Refreshed token : $event");
final res = await _repository.refreshFCMToken(event);
if (res) {
printMessage("Token refreshed");
} else {
printMessage("Something went wrong !");
}
});
stream.listen((event) {
if (state.appState == AppState.unAuthorized) {
navigatorKey.currentContext
?.navigateTo(const SplashScreen(), removeStack: true);
}
});
}
Future<void> _observeAppStatus(ObserveAppState event, Emitter emitter) {
return emitter.forEach(
_repository.getAppState(),
onData: (data) {
return state.copyWith(appState: data);
},
);
}
Future<void> _getAppStatus(GetAppStatus event, Emitter emitter) async {
final isAuthorized = await _repository.isAuthorized();
if (isAuthorized) {
emitter(state.copyWith(appState: AppState.logged));
} else {
emitter(state.copyWith(appState: AppState.unAuthorized));
}
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui/main
|
mirrored_repositories/stories-app/lib/ui/main/bloc/main_event.dart
|
part of 'main_bloc.dart';
abstract class MainEvent {}
class ObserveAppState extends MainEvent {}
class GetAppStatus extends MainEvent {}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/global/global_screen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:jokes_app/common/resource/decorations.dart';
import 'package:jokes_app/common/utils/navigator.dart';
import 'package:jokes_app/common/utils/size.dart';
import 'package:jokes_app/common/widgets/loading.dart';
import 'package:jokes_app/di/app_di.dart';
import 'package:jokes_app/ui/global/bloc/global_bloc.dart';
import 'package:jokes_app/ui/global/user_item.dart';
import 'package:jokes_app/ui/profile/user_stories_screen.dart';
class GlobalScreen extends StatelessWidget {
const GlobalScreen({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => GlobalBloc(injector.get())
..add(
GetTopUsers(),
),
child: BlocBuilder<GlobalBloc, GlobalState>(
builder: (context, state) {
return Scaffold(
body: Container(
height: context.height,
width: context.width,
decoration: const DefaultBackgroundDecoration(),
child: state.topUsers.isEmpty
? const Loading()
: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: state.topUsers.length,
itemBuilder: (e, i) {
final item = state.topUsers[i];
return UserItem(
user: item,
index: i + 1,
onTap: () {
context.navigateTo(UserStoriesScreen(
userId: item.id, username: item.username));
},
);
},
),
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/stories-app/lib/ui
|
mirrored_repositories/stories-app/lib/ui/global/user_item.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jokes_app/common/resource/fonts.dart';
import 'package:jokes_app/common/widgets/scale_tap.dart';
import 'package:jokes_app/domain/models/ui/profile.dart';
import '../../common/resource/colors.dart';
class UserItem extends StatelessWidget {
final User user;
final int index;
final Function() onTap;
@override
Widget build(BuildContext context) {
Color color = AppColors.primaryColor;
if (index == 1) color = AppColors.gold.withAlpha(152);
if (index == 2) color = AppColors.gold.withAlpha(100);
if (index == 3) color = AppColors.gold.withAlpha(62);
if (index > 3) color = AppColors.whiteAlpha52;
return ScaleTap(
onPressed: () {
onTap.call();
},
child: Container(
alignment: Alignment.center,
margin: const EdgeInsets.only(top: 24, left: 24, right: 24),
decoration: BoxDecoration(
color: AppColors.primaryDark,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: color),
),
height: 62,
child: Row(
children: [
const Padding(
padding: EdgeInsets.all(6),
),
if (user.isMe == true)
Icon(
Icons.circle,
color: AppColors.darkSpringGreen,
size: 12,
),
if (user.isMe == true)
const Padding(
padding: EdgeInsets.all(4),
),
Text(
index.toString(),
style: primaryTextStyle(fontWeight: FontWeight.bold),
),
Container(
margin: const EdgeInsets.all(16),
child: Text(
user.username,
style: primaryTextStyle(fontWeight: FontWeight.bold),
),
),
const Spacer(),
Container(
margin: const EdgeInsets.all(16),
child: Row(
children: [
Text(
user.score?.toString() ?? "",
style: primaryTextStyle(fontWeight: FontWeight.bold),
),
const Padding(
padding: EdgeInsets.all(4),
),
Icon(
Icons.sports_score_rounded,
color: AppColors.white,
),
],
),
),
],
),
),
);
}
const UserItem({
super.key,
required this.user,
required this.index,
required this.onTap,
});
}
| 0
|
mirrored_repositories/stories-app/lib/ui/global
|
mirrored_repositories/stories-app/lib/ui/global/bloc/global_event.dart
|
part of 'global_bloc.dart';
@immutable
abstract class GlobalEvent {}
class GetTopUsers extends GlobalEvent {}
| 0
|
mirrored_repositories/stories-app/lib/ui/global
|
mirrored_repositories/stories-app/lib/ui/global/bloc/global_bloc.dart
|
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:jokes_app/common/utils/printer.dart';
import 'package:jokes_app/domain/models/common/domain_result.dart';
import 'package:meta/meta.dart';
import '../../../domain/models/ui/profile.dart';
import '../../../domain/repositories/global_repository.dart';
part 'global_event.dart';
part 'global_state.dart';
class GlobalBloc extends Bloc<GlobalEvent, GlobalState> {
final GlobalRepository _repository;
GlobalBloc(
this._repository,
) : super(const GlobalState()) {
on<GetTopUsers>(_getTopUsers);
}
Future<void> _getTopUsers(GetTopUsers event, Emitter emitter) {
return emitter.forEach(
_repository.getTopUsers(),
onData: (data) {
if (data is DomainLoading) {
return state.copyWith(topUsersStatus: GlobalStatus.loading);
}
if (data is DomainSuccess<List<User>>) {
return state.copyWith(
topUsersStatus: GlobalStatus.success, topUsers: data.data);
}
if (data is DomainFail) {
return state.copyWith(topUsersStatus: GlobalStatus.fail);
}
return state;
},
);
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.