repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/flutter_riverpod_todo_app/lib/data
mirrored_repositories/flutter_riverpod_todo_app/lib/data/repositories/task_repository.dart
import 'package:flutter_riverpod_todo_app/data/data.dart'; abstract class TaskRepository { Future<void> addTask(Task task); Future<void> updateTask(Task task); Future<void> deleteTask(Task task); Future<List<Task>> getAllTasks(); }
0
mirrored_repositories/flutter_riverpod_todo_app/lib/data
mirrored_repositories/flutter_riverpod_todo_app/lib/data/repositories/task_repository_provider.dart
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod_todo_app/data/data.dart'; final taskRepositoryProvider = Provider<TaskRepository>((ref) { final datasource = ref.read(taskDatasourceProvider); return TaskRepositoryImpl(datasource); });
0
mirrored_repositories/flutter_riverpod_todo_app/lib/data
mirrored_repositories/flutter_riverpod_todo_app/lib/data/repositories/repositories.dart
export 'task_repository.dart'; export 'task_repository_provider.dart'; export 'task_repository_impl.dart';
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/utils/helpers.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod_todo_app/data/data.dart'; import 'package:flutter_riverpod_todo_app/providers/providers.dart'; import 'package:intl/intl.dart'; @immutable class Helpers { const Helpers._(); static String timeToString(TimeOfDay time) { try { final DateTime now = DateTime.now(); final date = DateTime( now.year, now.month, now.day, time.hour, time.minute, ); final formatType = DateFormat.jm(); return formatType.format(date); } catch (e) { return '12:00'; } } static void selectDate(BuildContext context, WidgetRef ref) async { final initialDate = ref.read(dateProvider); DateTime? pickedDate = await showDatePicker( context: context, initialDate: initialDate, firstDate: DateTime(2023), lastDate: DateTime(2060), ); if (pickedDate != null) { ref.read(dateProvider.notifier).state = pickedDate; } } static bool isTaskFromSelectedDate(Task task, DateTime selectedDate) { final DateTime taskDate = _stringToDateTime(task.date); if (taskDate.month == selectedDate.month && taskDate.year == selectedDate.year && taskDate.day == selectedDate.day) { return true; } return false; } static DateTime _stringToDateTime(String dateString) { try { DateFormat format = DateFormat.yMMMd(); return format.parse(dateString); } catch (e) { return DateTime.now(); } } static String dateFormatter(DateTime date) { try { return DateFormat.yMMMd().format(date); } catch (e) { return DateFormat.yMMMd().format( DateTime.now(), ); } } }
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/utils/app_keys.dart
import 'package:flutter/foundation.dart' show immutable; @immutable class AppKeys { const AppKeys._(); static const String isDarkMode = 'isDarkMode'; static const String dbTable = 'tasks'; }
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/utils/task_keys.dart
import 'package:flutter/foundation.dart' show immutable; @immutable class TaskKeys { const TaskKeys._(); static const String id = 'id'; static const String title = 'title'; static const String category = 'category'; static const String date = 'date'; static const String time = 'time'; static const String note = 'note'; static const String isCompleted = 'isCompleted'; }
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/utils/task_category.dart
import 'package:flutter/material.dart'; enum TaskCategory { education(Icons.school, Colors.blueGrey), health(Icons.favorite, Colors.orange), home(Icons.home, Colors.green), others(Icons.calendar_month_rounded, Colors.purple), personal(Icons.person, Colors.lightBlue), shopping(Icons.shopping_bag, Colors.deepOrange), social(Icons.people, Colors.brown), travel(Icons.flight, Colors.pink), work(Icons.work, Colors.amber); static TaskCategory stringToTaskCategory(String name) { try { return TaskCategory.values.firstWhere( (category) => category.name == name, ); } catch (e) { return TaskCategory.others; } } final IconData icon; final Color color; const TaskCategory(this.icon, this.color); }
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/utils/utils.dart
export 'app_keys.dart'; export 'extensions.dart'; export 'task_category.dart'; export 'task_keys.dart'; export 'helpers.dart'; export 'app_alerts.dart';
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/utils/app_alerts.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod_todo_app/utils/utils.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod_todo_app/data/data.dart'; import 'package:flutter_riverpod_todo_app/providers/providers.dart'; import 'package:go_router/go_router.dart'; @immutable class AppAlerts { const AppAlerts._(); static displaySnackbar(BuildContext context, String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( message, style: context.textTheme.bodyMedium, ), backgroundColor: context.colorScheme.onSecondary, ), ); } static Future<void> showAlertDeleteDialog({ required BuildContext context, required WidgetRef ref, required Task task, }) async { Widget cancelButton = TextButton( child: const Text('NO'), onPressed: () => context.pop(), ); Widget deleteButton = TextButton( onPressed: () async { await ref.read(tasksProvider.notifier).deleteTask(task).then( (value) { displaySnackbar( context, 'Task deleted successfully', ); context.pop(); }, ); }, child: const Text('YES'), ); AlertDialog alert = AlertDialog( title: const Text('Are you sure you want to delete this task?'), actions: [ deleteButton, cancelButton, ], ); await showDialog( context: context, builder: (BuildContext context) { return alert; }, ); } }
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/utils/extensions.dart
import 'package:flutter/material.dart'; extension BuildContextExtensions on BuildContext { ThemeData get _theme => Theme.of(this); TextTheme get textTheme => _theme.textTheme; ColorScheme get colorScheme => _theme.colorScheme; Size get deviceSize => MediaQuery.sizeOf(this); }
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/screens/create_task_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod_todo_app/config/config.dart'; import 'package:flutter_riverpod_todo_app/data/data.dart'; import 'package:flutter_riverpod_todo_app/providers/providers.dart'; import 'package:flutter_riverpod_todo_app/utils/utils.dart'; import 'package:flutter_riverpod_todo_app/widgets/widgets.dart'; import 'package:gap/gap.dart'; import 'package:go_router/go_router.dart'; import 'package:intl/intl.dart'; class CreateTaskScreen extends ConsumerStatefulWidget { static CreateTaskScreen builder( BuildContext context, GoRouterState state, ) => const CreateTaskScreen(); const CreateTaskScreen({super.key}); @override ConsumerState<ConsumerStatefulWidget> createState() => _CreateTaskScreenState(); } class _CreateTaskScreenState extends ConsumerState<CreateTaskScreen> { final TextEditingController _titleController = TextEditingController(); final TextEditingController _noteController = TextEditingController(); @override void dispose() { _titleController.dispose(); _noteController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final colors = context.colorScheme; return Scaffold( appBar: AppBar( backgroundColor: colors.primary, title: const DisplayWhiteText( text: 'Add New Task', ), ), body: SafeArea( child: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ CommonTextField( hintText: 'Task Title', title: 'Task Title', controller: _titleController, ), const Gap(30), const CategoriesSelection(), const Gap(30), const SelectDateTime(), const Gap(30), CommonTextField( hintText: 'Notes', title: 'Notes', maxLines: 6, controller: _noteController, ), const Gap(30), ElevatedButton( onPressed: _createTask, child: const Padding( padding: EdgeInsets.all(8.0), child: DisplayWhiteText( text: 'Save', ), ), ), const Gap(30), ], ), ), ), ); } void _createTask() async { final title = _titleController.text.trim(); final note = _noteController.text.trim(); final time = ref.watch(timeProvider); final date = ref.watch(dateProvider); final category = ref.watch(categoryProvider); if (title.isNotEmpty) { final task = Task( title: title, category: category, time: Helpers.timeToString(time), date: DateFormat.yMMMd().format(date), note: note, isCompleted: false, ); await ref.read(tasksProvider.notifier).createTask(task).then((value) { AppAlerts.displaySnackbar(context, 'Task create successfully'); context.go(RouteLocation.home); }); } else { AppAlerts.displaySnackbar(context, 'Title cannot be empty'); } } }
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/screens/screens.dart
export 'home_screen.dart'; export 'create_task_screen.dart';
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/screens/home_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod_todo_app/config/config.dart'; import 'package:flutter_riverpod_todo_app/data/data.dart'; import 'package:flutter_riverpod_todo_app/providers/providers.dart'; import 'package:flutter_riverpod_todo_app/utils/utils.dart'; import 'package:flutter_riverpod_todo_app/widgets/widgets.dart'; import 'package:gap/gap.dart'; import 'package:go_router/go_router.dart'; class HomeScreen extends ConsumerWidget { static HomeScreen builder( BuildContext context, GoRouterState state, ) => const HomeScreen(); const HomeScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final deviceSize = context.deviceSize; final date = ref.watch(dateProvider); final taskState = ref.watch(tasksProvider); final inCompletedTasks = _incompltedTask(taskState.tasks, ref); final completedTasks = _compltedTask(taskState.tasks, ref); return Scaffold( body: Stack( children: [ AppBackground( headerHeight: deviceSize.height * 0.3, header: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () => Helpers.selectDate(context, ref), child: DisplayWhiteText( text: Helpers.dateFormatter(date), fontWeight: FontWeight.normal, ), ), const DisplayWhiteText(text: 'My Todo List', size: 40), ], ), ), ), Positioned( top: 130, left: 0, right: 0, child: SafeArea( child: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ DisplayListOfTasks( tasks: inCompletedTasks, ), const Gap(20), Text( 'Completed', style: context.textTheme.headlineSmall?.copyWith( fontWeight: FontWeight.bold, ), ), const Gap(20), DisplayListOfTasks( isCompletedTasks: true, tasks: completedTasks, ), const Gap(20), ElevatedButton( onPressed: () => context.push(RouteLocation.createTask), child: const Padding( padding: EdgeInsets.all(8.0), child: DisplayWhiteText( text: 'Add New Task', ), ), ), ], ), ), ), ), ], ), ); } List<Task> _incompltedTask(List<Task> tasks, WidgetRef ref) { final date = ref.watch(dateProvider); final List<Task> filteredTask = []; for (var task in tasks) { if (!task.isCompleted) { final isTaskDay = Helpers.isTaskFromSelectedDate(task, date); if (isTaskDay) { filteredTask.add(task); } } } return filteredTask; } List<Task> _compltedTask(List<Task> tasks, WidgetRef ref) { final date = ref.watch(dateProvider); final List<Task> filteredTask = []; for (var task in tasks) { if (task.isCompleted) { final isTaskDay = Helpers.isTaskFromSelectedDate(task, date); if (isTaskDay) { filteredTask.add(task); } } } return filteredTask; } }
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/providers/time_provider.dart
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; final timeProvider = StateProvider.autoDispose<TimeOfDay>((ref) { return TimeOfDay.now(); });
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/providers/providers.dart
export 'category_provider.dart'; export 'date_provider.dart'; export 'time_provider.dart'; export 'task/task.dart';
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/providers/category_provider.dart
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod_todo_app/utils/utils.dart'; final categoryProvider = StateProvider.autoDispose<TaskCategory>((ref) { return TaskCategory.others; });
0
mirrored_repositories/flutter_riverpod_todo_app/lib
mirrored_repositories/flutter_riverpod_todo_app/lib/providers/date_provider.dart
import 'package:flutter_riverpod/flutter_riverpod.dart'; final dateProvider = StateProvider<DateTime>((ref) { return DateTime.now(); });
0
mirrored_repositories/flutter_riverpod_todo_app/lib/providers
mirrored_repositories/flutter_riverpod_todo_app/lib/providers/task/task.dart
export 'task_notifier.dart'; export 'task_state.dart'; export 'tasks_provider.dart';
0
mirrored_repositories/flutter_riverpod_todo_app/lib/providers
mirrored_repositories/flutter_riverpod_todo_app/lib/providers/task/task_notifier.dart
import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod_todo_app/data/data.dart'; import 'package:flutter_riverpod_todo_app/providers/providers.dart'; class TaskNotifier extends StateNotifier<TaskState> { final TaskRepository _repository; TaskNotifier(this._repository) : super(const TaskState.initial()) { getTasks(); } Future<void> createTask(Task task) async { try { await _repository.addTask(task); getTasks(); } catch (e) { debugPrint(e.toString()); } } Future<void> deleteTask(Task task) async { try { await _repository.deleteTask(task); getTasks(); } catch (e) { debugPrint(e.toString()); } } Future<void> updateTask(Task task) async { try { final isCompleted = !task.isCompleted; final updatedTask = task.copyWith(isCompleted: isCompleted); await _repository.updateTask(updatedTask); getTasks(); } catch (e) { debugPrint(e.toString()); } } void getTasks() async { try { final tasks = await _repository.getAllTasks(); state = state.copyWith(tasks: tasks); } catch (e) { debugPrint(e.toString()); } } }
0
mirrored_repositories/flutter_riverpod_todo_app/lib/providers
mirrored_repositories/flutter_riverpod_todo_app/lib/providers/task/tasks_provider.dart
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod_todo_app/data/data.dart'; import 'package:flutter_riverpod_todo_app/providers/providers.dart'; final tasksProvider = StateNotifierProvider<TaskNotifier, TaskState>((ref) { final repository = ref.watch(taskRepositoryProvider); return TaskNotifier(repository); });
0
mirrored_repositories/flutter_riverpod_todo_app/lib/providers
mirrored_repositories/flutter_riverpod_todo_app/lib/providers/task/task_state.dart
import 'package:equatable/equatable.dart'; import 'package:flutter_riverpod_todo_app/data/data.dart'; class TaskState extends Equatable { final List<Task> tasks; const TaskState({ required this.tasks, }); const TaskState.initial({ this.tasks = const [], }); TaskState copyWith({ List<Task>? tasks, }) { return TaskState( tasks: tasks ?? this.tasks, ); } @override List<Object> get props => [tasks]; }
0
mirrored_repositories/flutter_foodie
mirrored_repositories/flutter_foodie/lib/foodie_home.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_practice_app/foodie_details.dart'; import 'package:flutter_practice_app/model/Food.dart'; class FoodieHome extends StatefulWidget { @override _FoodieHomeState createState() => _FoodieHomeState(); } class _FoodieHomeState extends State<FoodieHome> { Size _mediaQuerySize; int _cartCounter = 0; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { _mediaQuerySize = MediaQuery.of(context).size; return Scaffold( backgroundColor: Color(0xFF21BFBD), body: ListView( children: <Widget>[ Padding( padding: EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ IconButton( icon: Icon(Icons.arrow_back_ios), color: Colors.white, onPressed: () {}, ), Container( width: 120.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ IconButton( icon: Icon(Icons.filter_list), color: Colors.white, onPressed: () {}, ), IconButton( icon: Icon(Icons.menu), color: Colors.white, onPressed: () {}, ), ], ), ) ], ), ), SizedBox( height: 24.0, ), Padding( padding: EdgeInsets.only(left: 32.0), child: RichText( text: TextSpan( style: TextStyle( color: Colors.white, fontSize: 28.0, ), children: [ TextSpan( text: 'Foodie', style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.bold, shadows: <Shadow>[ Shadow( offset: Offset(0.5, 0.5), blurRadius: 0.5, color: Colors.black, ), ], ), ), TextSpan( text: ' Bazar', style: TextStyle( color: Colors.white.withAlpha(200), ), ), ])), ), SizedBox( height: 40.0, ), SizedBox( height: _mediaQuerySize.height - 182.0, width: _mediaQuerySize.width, child: Stack( children: <Widget>[ Hero( tag: 'card', child: SizedBox( height: _mediaQuerySize.height - 182.0, width: _mediaQuerySize.width, child: Card( margin: EdgeInsets.zero, clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only(topLeft: Radius.circular(72.0)), ), elevation: 4, ), ), ), Container( child: ListView( primary: false, padding: EdgeInsets.only(left: 16.0, right: 16.0), children: <Widget>[ Padding( padding: EdgeInsets.only(top: 24.0), child: Container( height: _mediaQuerySize.height - 280.0, child: ListView( children: <Widget>[ _buildFoodItem(Food('Sea Food', 'assets/images/img1.png', 320.toDouble())), _buildFoodItem(Food('Biryani', 'assets/images/img2.png', 340.00.toDouble())), _buildFoodItem(Food('Whopper Chicken Burger', 'assets/images/img3.png', 260.00.toDouble())), _buildFoodItem(Food('Mutton Burger', 'assets/images/img4.png', 240.00.toDouble())), _buildFoodItem(Food('Salad', 'assets/images/img5.png', 99.00.toDouble())), ], ), ), ), SizedBox( height: 8.0, ), Padding( padding: EdgeInsets.only(left: 8.0, right: 8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( height: 48.0, width: 48.0, decoration: BoxDecoration( border: Border.all( color: Colors.grey, style: BorderStyle.solid, width: 1.0), borderRadius: BorderRadius.all( Radius.circular(8.0), ), ), child: IconButton( icon: Icon(Icons.search), onPressed: () {}, ), ), Container( height: 48.0, width: 48.0, decoration: BoxDecoration( border: Border.all( color: Colors.grey, style: BorderStyle.solid, width: 1.0), borderRadius: BorderRadius.all( Radius.circular(8.0), ), ), child: Stack( children: <Widget>[ IconButton( icon: Icon(Icons.shopping_basket), onPressed: () {}, ), Align( alignment: Alignment.topRight, child: Padding( padding: EdgeInsets.only( top: 2.0, right: 4.0, ), child: Text( '$_cartCounter', style: TextStyle( color: Colors.black, fontSize: 12.0, fontWeight: FontWeight.bold), ), ), ), ], ), ), Container( height: 48.0, width: 120.0, padding: EdgeInsets.all(8.0), decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.all(Radius.circular(8.0))), child: Align( alignment: Alignment.center, child: Text( 'Checkout', style: TextStyle( fontSize: 18.0, color: Colors.white), ), ), ), ], ), ) ], ), ), ], ), ), ], ), ); } Widget _buildFoodItem(Food food) { return Padding( padding: EdgeInsets.only(left: 8.0, right: 8.0, top: 8.0), child: InkWell( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (context) => FoodieDetails(food.image, food), ), ); }, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Container( child: Row( children: <Widget>[ Hero( tag: food.image, child: Image( image: AssetImage(food.image), fit: BoxFit.scaleDown, height: 72.0, width: 72.0, ), ), SizedBox( width: 8.0, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( food.name, style: TextStyle( color: Colors.black, fontSize: 16.0, fontWeight: FontWeight.bold, ), ), Text( "\₹ " + food.price.toString(), style: TextStyle(color: Colors.grey, fontSize: 12.0), ), ], ), ], ), ), IconButton( icon: Icon(Icons.add), color: Colors.black, onPressed: () { setState(() { _cartCounter++; }); }, ) ], ), ), ); } }
0
mirrored_repositories/flutter_foodie
mirrored_repositories/flutter_foodie/lib/foodie_details.dart
import 'package:flutter/material.dart'; import 'package:flutter_practice_app/model/Food.dart'; class FoodieDetails extends StatefulWidget { String tagImage; Food food; FoodieDetails(this.tagImage, this.food); @override FoodieDetailsState createState() => FoodieDetailsState(); } class FoodieDetailsState extends State<FoodieDetails> { Size _mediaQuerySize; double imageSize = 240.0; var selectedCard = 'WEIGHT'; int _itemCartCounter = 0; double _totalCart = 0; double _contentOpacity = 0.0; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { _mediaQuerySize = MediaQuery.of(context).size; Future.delayed(const Duration(microseconds: 100), () { setState(() { _contentOpacity = 1.0; }); }); return Scaffold( backgroundColor: Color(0xFF7A9BEE), appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0.0, leading: IconButton( icon: Icon(Icons.arrow_back_ios), color: Colors.white, onPressed: () { Navigator.of(context).pop(); }), title: Text( 'Details', style: TextStyle(color: Colors.white, fontSize: 18.0), ), centerTitle: true, actions: <Widget>[ IconButton( icon: Icon(Icons.more_horiz), color: Colors.white, onPressed: () {}) ], ), body: ListView( children: <Widget>[ Stack( children: <Widget>[ Container( height: _mediaQuerySize.height - 80, width: _mediaQuerySize.width, color: Colors.transparent, ), Positioned( top: 72.0, height: _mediaQuerySize.height - 100, width: _mediaQuerySize.width, child: Hero( tag: 'card', child: Card( margin: EdgeInsets.zero, clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(72.0), topRight: Radius.circular(72.0), ), ), elevation: 4, ), ), ), Positioned( top: 16.0, left: (_mediaQuerySize.width / 2) - (imageSize / 2), child: Hero( tag: widget.tagImage, child: Image( image: AssetImage(widget.food.image), fit: BoxFit.cover, height: imageSize, width: imageSize, ), ), ), Positioned( top: 256.0, width: _mediaQuerySize.width, child: AnimatedOpacity( opacity: _contentOpacity, duration: Duration(seconds: 1), curve: Curves.easeIn, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only(left: 16.0, right: 16.0), child: Align( alignment: Alignment.centerLeft, child: Text( widget.food.name, style: TextStyle( color: Colors.black, fontSize: 24.0, fontWeight: FontWeight.bold), ), ), ), SizedBox( height: 20.0, ), Padding( padding: EdgeInsets.only(left: 16.0, right: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( "\₹ " + widget.food.price.toString(), style: TextStyle( color: Colors.grey, fontSize: 20.0, ), ), Container( height: 24.0, width: 1.0, color: Colors.grey, ), Container( width: 120.0, height: 40.0, decoration: BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(16.0), ), color: Color(0xFF7A9BEE), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ InkWell( onTap: () { _removeCart(); }, child: Icon( Icons.remove, color: Colors.white, ), ), Text( '$_itemCartCounter', style: TextStyle( color: Colors.white, fontSize: 16.0), ), InkWell( onTap: () { _addCart(); }, child: Container( height: 24.0, width: 24.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: Colors.white, ), child: Center( child: Icon( Icons.add, color: Color(0xFF7A9BEE), ), ), ), ), ], ), ), ], ), ), SizedBox( height: 24.0, ), Padding( padding: EdgeInsets.only(left: 16.0, right: 16.0), child: Container( height: 148.0, child: ListView( scrollDirection: Axis.horizontal, children: <Widget>[ _buildInfoCard('WEIGHT', '300', 'G'), SizedBox(width: 10.0), _buildInfoCard('CALORIES', '267', 'CAL'), SizedBox(width: 10.0), _buildInfoCard('VITAMINS', 'A, B6', 'VIT'), SizedBox(width: 10.0), _buildInfoCard('AVAIL', 'NO', 'AV') ], ), ), ), SizedBox( height: 20.0, ), Padding( padding: EdgeInsets.only( left: 16.0, right: 16.0, bottom: 16.0), child: Container( height: 54.0, width: _mediaQuerySize.width, decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.only( topLeft: Radius.circular(8.0), topRight: Radius.circular(8.0), bottomLeft: Radius.circular(24.0), bottomRight: Radius.circular(24.0), ), ), child: Center( child: Text( '\₹ $_totalCart', style: TextStyle( fontSize: 20.0, color: Colors.white), ), ), ), ), ], ), ), ), ], ), ], )); } Widget _buildInfoCard(String cardTitle, String info, String unit) { return InkWell( onTap: () { setSelected(cardTitle); }, child: AnimatedContainer( height: 100.0, width: 100.0, duration: Duration(milliseconds: 500), curve: Curves.easeIn, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8.0), color: cardTitle == selectedCard ? Color(0xFF7A9BEE) : Colors.white, border: Border.all( color: cardTitle == selectedCard ? Colors.transparent : Colors.grey.withOpacity(0.3), style: BorderStyle.solid, width: 0.75, ), ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.only(top: 8.0, left: 16.0), child: Text(cardTitle, style: TextStyle( fontSize: 12.0, color: cardTitle == selectedCard ? Colors.white : Colors.grey.withOpacity(0.7), )), ), Padding( padding: const EdgeInsets.only(left: 16.0, bottom: 8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(info, style: TextStyle( fontFamily: 'Montserrat', fontSize: 14.0, color: cardTitle == selectedCard ? Colors.white : Colors.black, fontWeight: FontWeight.bold)), Text(unit, style: TextStyle( fontSize: 12.0, color: cardTitle == selectedCard ? Colors.white : Colors.black, )) ], ), ) ], ), ), ); } void setSelected(String cardTitle) { setState(() { selectedCard = cardTitle; }); } void _removeCart() { if (_itemCartCounter > 0) setState(() { _itemCartCounter--; _updateTotal(); }); } void _addCart() { setState(() { _itemCartCounter++; _updateTotal(); }); } void _updateTotal() { setState(() { _totalCart = _itemCartCounter * widget.food.price; }); } }
0
mirrored_repositories/flutter_foodie
mirrored_repositories/flutter_foodie/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_practice_app/foodie_home.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Foodie Bazar', theme: ThemeData( primarySwatch: Colors.cyan, ), home: FoodieHome(), ); } }
0
mirrored_repositories/flutter_foodie/lib
mirrored_repositories/flutter_foodie/lib/model/Food.dart
class Food { String name; String image; double price; Food(this.name, this.image, this.price); }
0
mirrored_repositories/flutter_foodie
mirrored_repositories/flutter_foodie/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_practice_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Noticias384
mirrored_repositories/Noticias384/lib/main.dart
import 'package:flutter/material.dart'; import 'view/Home.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Noticias384', theme: new ThemeData( primarySwatch: Colors.green, accentColor: Colors.red ), home: new Home(), ); } }
0
mirrored_repositories/Noticias384/lib
mirrored_repositories/Noticias384/lib/view/Home.dart
import 'package:flutter/material.dart'; import 'NewsCard.dart'; import '../model/Noticia.dart'; import 'dart:async'; import '../controller/Requests.dart'; import 'package:async_loader/async_loader.dart'; class Home extends StatefulWidget{ @override State createState() => _HomeState(); } class _HomeState extends State<Home>{ var _recursos = []; var _recursoSeleccionado; final GlobalKey<AsyncLoaderState> _asyncLoaderState = new GlobalKey<AsyncLoaderState>(); getMessage() async{ return new Future.delayed(Duration(seconds: 5), ()=> 'Cargado correctamente'); } obteniendoDatosImporantes() async{ var recursos = await Requests.peticionRecursos(); // print('recursosos: '+recursos.toString()); recursos.add({ 'id': 'todos', 'name': 'Todos' }); setState(() { _recursos = recursos; }); return await Requests.petiionNoticias(_recursoSeleccionado); } @override Widget build(BuildContext context) { var _asynLoader = new AsyncLoader( key: _asyncLoaderState, initState: () async => await obteniendoDatosImporantes(), renderLoad: () => Center(child: CircularProgressIndicator(),), renderError: ([error])=> Center(child: Text('Ocurrion un error en la carga'),), renderSuccess: ({data}) => Padding( padding: EdgeInsets.all(16.0), child: ListView.builder( itemBuilder: (BuildContext context, index){ return NewsCard(data[index]); }, itemCount: data.length, ), ), ); return Scaffold( appBar: new AppBar( title: Text('Noticias384'), actions: <Widget>[ PopupMenuButton( onSelected: (seleccion){ print('selecicon: $seleccion'); if (seleccion == 'todos'){ setState(() { _recursoSeleccionado = null; }); }else{ setState(() { _recursoSeleccionado = seleccion; }); } _asyncLoaderState.currentState.reloadState(); }, itemBuilder: (BuildContext contex){ return _recursos.map((objeto){ return PopupMenuItem( value: objeto['id'], child: Text(objeto['name']), ); }).toList(); }, ) ], ), body: _asynLoader // new NewsCard(new Noticia( // titulo: 'Mi noticia', // descripcion: 'Descripcion de noticia', // imagenUrl: 'http://www.elefete.com/wp-content/uploads/2017/06/google-Copiar.jpg' // )) , ); } }
0
mirrored_repositories/Noticias384/lib
mirrored_repositories/Noticias384/lib/view/NewsCard.dart
import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import 'dart:async'; import 'package:share/share.dart'; import '../model/Noticia.dart'; class NewsCard extends StatefulWidget{ NewsCard(this.noticia); final Noticia noticia; @override State createState() => _NewsCard(); } class _NewsCard extends State<NewsCard>{ @override Widget build(BuildContext context) { return Card( child: new Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ new Stack( alignment: Alignment(0.0, 1.0), children: <Widget>[ Image.network(widget.noticia.imagenUrl), Container( width: MediaQuery.of(context).size.width, decoration: new BoxDecoration( color: Color.fromRGBO(0, 0, 0, 0.7), shape: BoxShape.rectangle, borderRadius: BorderRadius.circular(5.0) ), child: Padding( padding: const EdgeInsets.all(8.0), child: new Column( children: <Widget>[ new Text(widget.noticia.titulo, style: new TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: Theme.of(context).textTheme.title.fontSize ), ), new Text(widget.noticia.descripcion.length >= 100 ? widget.noticia.descripcion.substring(0,100) : widget.noticia.descripcion, style: new TextStyle( color: Colors.white ), ) ], ), ), ) ], ), Divider(color: Colors.black,), Container( child: Row( children: <Widget>[ FlatButton( onPressed: (){ // print('url de noticia: ${widget.noticia.urlNoticia}'); _openUrl(widget.noticia.urlNoticia); }, child: Text('Ver Noticia'), ), FlatButton( onPressed: (){ // print('url de noticia: ${widget.noticia.urlNoticia}'); Share.share('Te recomiendo que te leas esta noticia: ${widget.noticia.urlNoticia}'); }, child: Text('Compartir Noticia'), ), ], ), ), ], ), ); } _openUrl(url) async{ if (await canLaunch(url)){ await launch(url, forceWebView: true); } else{ throw 'No se puede abrir URL'; } } }
0
mirrored_repositories/Noticias384/lib
mirrored_repositories/Noticias384/lib/model/Noticia.dart
class Noticia { Noticia({ this.titulo = ' ', this.descripcion = ' ', this.urlNoticia = ' ', this.imagenUrl = ' ' }); final String titulo; final String descripcion; final String urlNoticia; final String imagenUrl; static List<Noticia> fromJson(List<dynamic> json) { List<Noticia> lista = []; for (var i = 0; i< json.length; i++){ lista.add( new Noticia( titulo: json[i]['title'] != null ? json[i]['title'] : ' ', descripcion: json[i]['description'] != null ? json[i]['description'] : ' ', urlNoticia: json[i]['url'] != null ? json[i]['url'] : ' ', imagenUrl: json[i]['urlToImage'] != null ? json[i]['urlToImage'] : ' ' ) ); } return lista; } }
0
mirrored_repositories/Noticias384/lib
mirrored_repositories/Noticias384/lib/controller/Requests.dart
import 'dart:async'; import 'dart:convert'; import '../model/Noticia.dart'; import 'package:http/http.dart' as http; class Requests{ static Future<List<Noticia>> petiionNoticias(recurso) async{ var url = 'https://newsapi.org/v2/top-headlines?language=es&apiKey=ff0f32791a5c466ebbfc382378fc5746'; if(recurso != null){ url = 'https://newsapi.org/v2/top-headlines?language=es&sources=$recurso&apiKey=ff0f32791a5c466ebbfc382378fc5746'; } var respuesta = await http.get(url); if (respuesta.statusCode == 200){ var jsonRespuesta = json.decode(respuesta.body); // print('Respuesta json'); // print(jsonRespuesta); var listaNoticias = Noticia.fromJson(jsonRespuesta['articles']); return listaNoticias; } List<Noticia> no = []; return no; } static Future<List<dynamic>> peticionRecursos() async{ var respuesta = await http.get('https://newsapi.org/v2/sources?language=es&apiKey=ff0f32791a5c466ebbfc382378fc5746'); if (respuesta.statusCode == 200){ var jsonRespuesta = json.decode(respuesta.body); // print('Respuesta json'); // print(jsonRespuesta['sources']); List<dynamic> listaRecursos = []; for (var i = 0; i < jsonRespuesta['sources'].length; i++){ // print(i.toString()); listaRecursos.add( { 'id' : jsonRespuesta['sources'][i]['id'], 'name': jsonRespuesta['sources'][i]['name'] } ); } return listaRecursos; } List<dynamic> no = []; return no; } }
0
mirrored_repositories/Noticias384
mirrored_repositories/Noticias384/test/widget_test.dart
// This is a basic Flutter widget test. // To perform an interaction with a widget in your test, use the WidgetTester utility that Flutter // provides. For example, you can send tap and scroll gestures. You can also use WidgetTester to // find child widgets in the widget tree, read text, and verify that the values of widget properties // are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:noticias_384/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter-headphones-store
mirrored_repositories/flutter-headphones-store/lib/styles.dart
import 'package:flutter/material.dart'; final TextStyle searchBarStyle = TextStyle(fontSize: 18, fontFamily: "Poppins", fontWeight: FontWeight.w100); final TextStyle headingStyle = TextStyle(fontSize: 26, fontFamily: "Poppins", fontWeight: FontWeight.w800); final TextStyle productTitleStyle = TextStyle(fontSize: 18, fontFamily: "Poppins", fontWeight: FontWeight.w800); final TextStyle productSubtitleStyle = TextStyle(fontFamily: "Poppins"); final TextStyle bottomBarItemStyle = TextStyle( fontFamily: "Poppins", color: Colors.white, fontSize: 14, fontWeight: FontWeight.w800); final TextStyle speakerDescStyle = TextStyle( fontSize: 14, color: Colors.grey, fontFamily: "Poppins", fontWeight: FontWeight.w100); final TextStyle speakerTitleStyle = TextStyle( fontSize: 18, color: Colors.grey, fontFamily: "Poppins", fontWeight: FontWeight.w800);
0
mirrored_repositories/flutter-headphones-store
mirrored_repositories/flutter-headphones-store/lib/main.dart
import 'package:flutter/material.dart'; import 'package:bubble_bottom_bar/bubble_bottom_bar.dart'; import './styles.dart'; import './model/headphone.dart'; import 'widgets/productCard.dart'; void main() => runApp(MaterialApp( title: 'App', theme: ThemeData(fontFamily: 'Poppins'), home: MyApp(), debugShowCheckedModeBanner: false, )); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int _currentIndex; @override void initState() { super.initState(); _currentIndex = 0; } void changePage(int index) { setState(() { _currentIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xFFf3f6fb), body: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only(left: 16, right: 16, top: 30), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ IconButton( icon: Icon(Icons.menu), onPressed: () {}, ), IconButton( icon: Icon(Icons.shopping_cart), onPressed: () {}, ) ], ), ), Padding( padding: EdgeInsets.only(left: 25), child: Text( "Shop", style: headingStyle, ), ), SizedBox( height: 22, ), Container( width: double.infinity, height: 60, margin: EdgeInsets.symmetric(horizontal: 22), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(.08), offset: Offset(0, 10), blurRadius: 30, ) ]), child: Center( child: Padding( padding: EdgeInsets.only(left: 18, right: 12), child: TextField( decoration: InputDecoration( border: InputBorder.none, hintText: "Procurar...", suffixIcon: Icon(Icons.search)), ), ), ), ), SizedBox( height: 40, ), Padding( padding: EdgeInsets.only(left: 25), child: Text( "Headphones", style: headingStyle, ), ), SizedBox( height: 16, ), Container( height: 240, child: ListView.builder( itemCount: MOCK_PRODUCTS_LIST.length, scrollDirection: Axis.horizontal, itemBuilder: (context, index) { var product = MOCK_PRODUCTS_LIST[index]; return ProductCard( imgUrl: product.image, name: product.title, color: product.color, ); }, ), ), Container( width: double.infinity, height: 160, margin: EdgeInsets.symmetric(horizontal: 22), child: Stack( children: <Widget>[ Padding( padding: EdgeInsets.only(left: 8), child: Text("Speakers", style: speakerTitleStyle), ), Align( alignment: Alignment.bottomCenter, child: Padding( padding: EdgeInsets.only(left: 10, right: 10, bottom: 10), child: Container( width: double.infinity, height: 100, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Colors.black12, offset: Offset(0, 6), blurRadius: 6), ]), child: Padding( padding: EdgeInsets.only(left: 22, top: 16), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("Rális", style: productTitleStyle), SizedBox( height: 4, ), Text("Haute red, slate blue\nMist Grey", style: speakerDescStyle), ], ), ), ), ), ), Positioned( right: 10, top: -5, child: Image.asset( "assets/images/speaker.png", fit: BoxFit.cover, width: 120, height: 140, ), ) ], ), ) ], ), ), bottomNavigationBar: Padding( padding: EdgeInsets.only(bottom: 12), child: BubbleBottomBar( backgroundColor: Colors.transparent, opacity: 1, elevation: 0, currentIndex: _currentIndex, onTap: changePage, items: <BubbleBottomBarItem>[ BubbleBottomBarItem( backgroundColor: Colors.black, icon: Icon( Icons.home, color: Colors.black, ), activeIcon: Icon( Icons.home, color: Colors.white, ), title: Text("Home", style: bottomBarItemStyle), ), BubbleBottomBarItem( backgroundColor: Colors.black, icon: Icon( Icons.insert_invitation, color: Colors.black, ), activeIcon: Icon( Icons.insert_invitation, color: Colors.white, ), title: Text("Agenda", style: bottomBarItemStyle), ), BubbleBottomBarItem( backgroundColor: Colors.black, icon: Icon( Icons.mail_outline, color: Colors.black, ), activeIcon: Icon( Icons.mail_outline, color: Colors.white, ), title: Text("Inbox", style: bottomBarItemStyle), ), BubbleBottomBarItem( backgroundColor: Colors.black, icon: Icon( Icons.poll, color: Colors.black, ), activeIcon: Icon( Icons.poll, color: Colors.white, ), title: Text("Dash", style: bottomBarItemStyle), ), ], ), ), ); } }
0
mirrored_repositories/flutter-headphones-store/lib
mirrored_repositories/flutter-headphones-store/lib/widgets/productCard.dart
import 'package:flutter/material.dart'; import 'package:lojinha_app/styles.dart'; class ProductCard extends StatelessWidget { final String imgUrl; final String name; final int color; ProductCard({this.imgUrl, this.name, this.color}); @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only(left: 15), child: Container( width: 165, height: 240, child: Stack( fit: StackFit.expand, children: <Widget>[ Align( alignment: Alignment.bottomCenter, child: Padding( padding: EdgeInsets.only(left: 5, right: 5, bottom: 20), child: Container( width: 140, height: 170, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(.1), offset: Offset(0, 10), blurRadius: 12) ]), ), ), ), Positioned( right: -32, top: -10, child: Image.asset( imgUrl, width: 170, height: 150, ), ), Positioned( left: 30, bottom: 50, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(name, style: productTitleStyle), Text( "colors $color", style: productSubtitleStyle, ) ], ), ) ], ), ), ); } }
0
mirrored_repositories/flutter-headphones-store/lib
mirrored_repositories/flutter-headphones-store/lib/model/headphone.dart
class HeadPhone { String image; String title; int color; HeadPhone({this.color, this.image, this.title}); } var MOCK_PRODUCTS_LIST = [ HeadPhone(image: "assets/images/img_01.png", title: "Pampas", color: 6), HeadPhone(image: "assets/images/img_02.png", title: "Plattan TLE", color: 12), HeadPhone(image: "assets/images/img_03.png", title: "Plattan 2", color: 1), ];
0
mirrored_repositories/flutter-headphones-store
mirrored_repositories/flutter-headphones-store/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:lojinha_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Fluid-Action-Card/lib
mirrored_repositories/Fluid-Action-Card/lib/FluidActionCard/Fluid_action_card.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class FluidActionCard extends StatefulWidget { //for setting the card's first gradient color final Color color1; //for setting the card's second gradient color final Color color2; //for setting the screen(container) background color final Color backgroundcolor; //for setting the card's borderradius and shape final BorderRadius borderRadius1; //for setting the card's borderradius and shape final BorderRadius borderRadius2; //for setting the card's height final double height; //for setting the card's width final double width; //for the number of cards the user wants final int CardCount; //for setting the position of the card final double Position; //for setting the shadow of the card final BoxShadow? shadow; //for gesture detection of the card final Function? ontap; //for adding text to the card final Text? text1; //for adding text to the card final Text? text2; //for setting text position on the card final double? TextPosition_Top; //for setting text position on the card final double? TextPosition_Down; //for setting image url final String assetimage; const FluidActionCard( {Key? key, required this.color1, required this.color2, required this.borderRadius1, required this.borderRadius2, required this.height, required this.width, required this.backgroundcolor, required this.CardCount, required this.Position, this.shadow, this.ontap, this.text1, this.text2, this.TextPosition_Top, this.TextPosition_Down, required this.assetimage}) : super(key: key); @override _FluidActionCardState createState() => _FluidActionCardState(); } class _FluidActionCardState extends State<FluidActionCard> with SingleTickerProviderStateMixin { TabController? _tabController; PageController? _pageController; int _selectedPage = 0; @override void initState() { super.initState(); _tabController = TabController(initialIndex: 0, length: 5, vsync: this); _pageController = PageController(initialPage: 0, viewportFraction: 0.8); } _ActionSelector(int index) { return AnimatedBuilder( animation: _pageController!, builder: (BuildContext context, Widget? widget) { double value = 1; if (_pageController!.position.haveDimensions) { value = (_pageController!.page! - index); value = (1 - (value.abs() * 0.4)).clamp(0.0, 1.0); } return Center( child: SizedBox( height: Curves.easeInOut.transform(value) * 500.0, width: Curves.easeInOut.transform(value) * 430.0, child: widget, ), ); }, child: GestureDetector( onTap: () { widget.ontap; }, child: Stack( alignment: Alignment.center, children: <Widget>[ ClipRRect( borderRadius: widget.borderRadius1, child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ widget.color1, widget.color2, ]), boxShadow: [widget.shadow!], borderRadius: widget.borderRadius2, ), margin: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 30.0), child: Stack( children: <Widget>[ Center( child: Center( child: Image( height: 270.0, width: 290.0, image: AssetImage( widget.assetimage, ), fit: BoxFit.cover, ), ), ), Positioned( top: widget.TextPosition_Top, right: widget.TextPosition_Down, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ if (widget.text1 != null) widget.text1!, if (widget.text2 != null) widget.text2!, ], ), ), ], ), ), ), ], ), ), ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: widget.backgroundcolor, body: AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle.dark, child: ListView( padding: EdgeInsets.symmetric(vertical: widget.Position), children: <Widget>[ Container( height: widget.height, width: double.infinity, child: PageView.builder( controller: _pageController, onPageChanged: (int index) { setState(() { _selectedPage = index; }); }, itemCount: widget.CardCount, itemBuilder: (BuildContext context, int index) { return _ActionSelector(index); }, ), ), ]))); } }
0
mirrored_repositories/Fluid-Action-Card
mirrored_repositories/Fluid-Action-Card/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Fluid-Action-Card/example
mirrored_repositories/Fluid-Action-Card/example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:Fluid_action_card/lib/FluidActionCard/fluid_action_card'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Fluid Action card display', debugShowCheckedModeBanner: false, home: Scaffold( body: FluidActionCard( color1: Colors.greenAccent.shade400, color2: Colors.black12, backgroundcolor: Colors.grey[900]!, borderRadius1: BorderRadius.circular(20), borderRadius2: BorderRadius.circular(20), TextPosition_Top: 22.0, TextPosition_Down: 29.0, height: 400.0, width: 240.0, CardCount: 3, text1: Text( "Starts From", style: TextStyle( color: Colors.white, fontSize: 18.0, fontStyle: FontStyle.italic), ), text2: Text( "300", style: TextStyle( color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.w700, letterSpacing: 2.0, ), ), Position: 250.0, shadow: BoxShadow( color: Colors.black12, blurRadius: 10.0, spreadRadius: 0.2, offset: Offset(0, 3), ), assetimage: 'assets/images/plant1.png', ontap: () {}, ), )); } }
0
mirrored_repositories/Fluid-Action-Card/example
mirrored_repositories/Fluid-Action-Card/example/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:example/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Gallery
mirrored_repositories/Gallery/lib/main.dart
import 'package:flutter/material.dart'; import 'package:gallery/screen_home.dart'; void main() { runApp(GalleryApp()); } class GalleryApp extends StatelessWidget { const GalleryApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(primarySwatch: Colors.red), home: ScreenHome(), ); } }
0
mirrored_repositories/Gallery
mirrored_repositories/Gallery/lib/screen_home.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_gallery_saver/image_gallery_saver.dart'; import 'package:image_picker/image_picker.dart'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; class ScreenHome extends StatefulWidget { const ScreenHome({Key? key}) : super(key: key); @override State<ScreenHome> createState() => _ScreenHomeState(); } class _ScreenHomeState extends State<ScreenHome> { List<String> pathLists = []; @override void initState() { var imgPathList = displayImages(); pathLists = imgPathList; super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Gallery'), centerTitle: true, ), floatingActionButton: FloatingActionButton( onPressed: () async { await takePhoto(); var imgPathList = displayImages(); setState(() { pathLists = imgPathList; }); }, child: Icon(Icons.camera_alt), ), body: pathLists == null ? Center(child: Text('NO Images')) : GridView.builder( itemCount: pathLists.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3), itemBuilder: (context, index) { return Container( height: 150, width: 150, child: Card( child: Image.file(File(pathLists[index])), ), ); })); } Future takePhoto() async { if (await _requestPermission(Permission.storage)) { XFile? img = await ImagePicker().pickImage(source: ImageSource.camera); var dir = await getDirectory(); if (!await dir.exists()) { await dir.create(recursive: true); } if (await dir.exists()) { final filename = basename(img!.path); File imgfilenam = File(img.path); final File newimg = await imgfilenam.copy('${dir.path}/$filename'); // await ImageGallerySaver.saveFile(newimg.path); } } else { return; } // if (img == null) { // return; // } // int i = 0; // final appDir = await getExternalStorageDirectory(); // final myImagePath = '${appDir!.path}/ImagesFolder'; // final myImgDir = await Directory(myImagePath).create(); // var compresimg = File("$myImagePath/image_$i.jpg") // ..writeAsBytesSync(img.encodeJpg()); // final fileName = basename(img.path); // final savedImage = await File(img.path).copy('${appDir.path}/$fileName'); } Future<bool> _requestPermission(Permission permission) async { if (await permission.isGranted) { return true; } else { var result = await permission.request(); if (result == PermissionStatus.granted) { return true; } else { return false; } } } getDirectory() async { if (await _requestPermission(Permission.storage)) { Directory dir; dir = (await getExternalStorageDirectory())!; String newpath = ""; List<String> folders = dir.path.split("/"); for (int i = 1; i < folders.length; i++) { String fold = folders[i]; if (fold != "Android") { newpath += "/" + fold; } else { break; } } newpath = newpath + "/MyGalleryImages"; dir = Directory(newpath); return dir; } return null; } checkForImages() async { Directory imgDir = await getDirectory(); if (!await imgDir.exists()) { await imgDir.create(recursive: true); } else { return; } } List<String> displayImages() { // Directory imgDir = await getDirectory(); checkForImages(); final Directory imgDir = Directory('/storage/emulated/0/MyGalleryImages'); List<String> imagesList = imgDir .listSync() .map((item) => item.path) .where((item) => item.endsWith(".jpg")) .toList(); return imagesList; } }
0
mirrored_repositories/Gallery
mirrored_repositories/Gallery/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:gallery/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/beautiful_list
mirrored_repositories/beautiful_list/lib/main.dart
import 'package:beatiful_list/listpage.dart'; import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData(primaryColor: Color.fromRGBO(58, 66, 86, 1.0)), home: ListPage( title: 'Lesson', ), ); } }
0
mirrored_repositories/beautiful_list
mirrored_repositories/beautiful_list/lib/listpage.dart
import 'package:flutter/material.dart'; class ListPage extends StatefulWidget { final String title; ListPage({Key key, this.title}) : super(key: key); @override _ListPageState createState() => _ListPageState(); } class _ListPageState extends State<ListPage> { final makeBottom = Container( height: 55.0, child: BottomAppBar( color: Color.fromRGBO(58, 66, 86, 1.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ IconButton( icon: Icon(Icons.home, color: Colors.white), onPressed: () {}, ), IconButton( icon: Icon( Icons.blur_on, color: Colors.white, ), onPressed: () {}, ), IconButton( icon: Icon( Icons.hotel, color: Colors.white, ), onPressed: () {}, ), IconButton( icon: Icon(Icons.account_box, color: Colors.white), onPressed: () {}, ) ], ), ), ); @override Widget build(BuildContext context) { final toAppBar = AppBar( centerTitle: true, elevation: 0.1, backgroundColor: Color.fromRGBO(58, 66, 86, 1.0), title: Text(widget.title), actions: <Widget>[ IconButton( icon: Icon(Icons.list), onPressed: () {}, ) ], ); final makeListTile = ListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0), leading: Container( padding: EdgeInsets.only(right: 12.0), decoration: BoxDecoration( border: Border(right: BorderSide(width: 1.0, color: Colors.white)), ), child: Icon( Icons.autorenew, color: Colors.white, ), ), title: Text( "Introduccing to Driving", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), ), subtitle: Row( children: <Widget>[ Icon(Icons.linear_scale, color: Colors.yellow), Text( " Intermediate", style: TextStyle(color: Colors.white), ) ], ), trailing: Icon( Icons.keyboard_arrow_right, color: Colors.white, size: 25.0, ), ); final makeCard = Card( elevation: 8.0, margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0), child: Container( decoration: BoxDecoration(color: Color.fromRGBO(64, 75, 96, .9)), child: makeListTile, ), ); final makeBody = Container( child: ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: 10, itemBuilder: (BuildContext context, int index) { return makeCard; }, ), ); return Scaffold( backgroundColor: Color.fromRGBO(58, 66, 86, 1.0), appBar: toAppBar, bottomNavigationBar: makeBottom, body: makeBody, ); } }
0
mirrored_repositories/beautiful_list
mirrored_repositories/beautiful_list/test/widget_test.dart
// This is a basic Flutter widget test. // To perform an interaction with a widget in your test, use the WidgetTester utility that Flutter // provides. For example, you can send tap and scroll gestures. You can also use WidgetTester to // find child widgets in the widget tree, read text, and verify that the values of widget properties // are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:beatiful_list/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/BigBasket__Clone
mirrored_repositories/BigBasket__Clone/lib/main.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } bool _value = true; BoxDecoration myBoxDecoration(Color color, Color bg) { return BoxDecoration( color: bg, border: Border.all( color: color, // <--- border color width: 2.0, ), ); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.green, //leading: IconButton( //icon: Icons.arrow_back, //onPressed: () {}, //), elevation: 0.7, actions: <Widget>[ Padding( padding: EdgeInsets.only(right: 20.0), child: GestureDetector( onTap: () {}, child: Icon( Icons.search, size: 26.0, ), ), ), Padding( padding: EdgeInsets.only(right: 20.0), child: GestureDetector( onTap: () {}, child: Icon( Icons.share, size: 26.0, ), ), ), Padding( padding: EdgeInsets.only(right: 20.0), child: GestureDetector( onTap: () {}, child: Icon( Icons.shopping_cart, size: 26.0, ), ), ), ], ), body: Padding( padding: const EdgeInsets.all(10.0), child: ListView( padding: EdgeInsets.zero, children: <Widget>[ Row( children: <Widget>[ Container( padding: EdgeInsets.all(3), color: Colors.green[300], child: Center( child: Text('Storia'), ), ), ], ), SizedBox( height: 5, ), Row( children: <Widget>[ Container( padding: EdgeInsets.all(3), child: Center( child: Text( 'Rose Shake 200 ml - Bottle', style: TextStyle(fontSize: 18), ), ), ), ], ), SizedBox( height: 3, ), Row( children: <Widget>[ Container( padding: EdgeInsets.all(3), child: Text( 'Rs 27', style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold), ), ), Container( padding: EdgeInsets.all(1), child: Text( 'MRP:', style: TextStyle( fontSize: 10, color: Colors.grey, ), ), ), Container( padding: EdgeInsets.all(1), child: Text( ' Rs 30', style: TextStyle( fontSize: 10, color: Colors.grey, decoration: TextDecoration.lineThrough), ), ), SizedBox( width: 7, ), Container( padding: EdgeInsets.all(0.5), color: Colors.redAccent, child: Text( '10% off', style: TextStyle( fontSize: 10, color: Colors.white, fontWeight: FontWeight.bold), ), ), ], ), Container( padding: EdgeInsets.all(2), child: Text( '(Inclusive of all taxes)', style: TextStyle( fontSize: 10, color: Colors.grey, decoration: TextDecoration.lineThrough), ), ), SizedBox( height: 5, ), Row( children: <Widget>[ Container( padding: EdgeInsets.fromLTRB(2, 1, 2, 1), color: Colors.green[100], child: Text( '3.5 *', style: TextStyle( fontSize: 12, color: Colors.green, fontWeight: FontWeight.bold), ), ), SizedBox( width: 5, ), InkWell( onTap: () {}, child: Container( padding: EdgeInsets.all(1), child: Text( '10 ratings & 1 review >', style: TextStyle( fontSize: 10, color: Colors.grey, ), ), ), ) ], ), SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ Expanded( flex: 1, child: Container( height: 20, child: Image.network( 'https://oslocks.files.wordpress.com/2014/11/vegetarian-symbol.png'), ), ), Expanded( flex: 7, child: Container( height: 300, child: Image.network( 'https://www.bigbasket.com/media/uploads/p/l/40191789_3-storia-rose-shake.jpg'), ), ), ], ), SizedBox( height: 10, ), Row( children: <Widget>[ Container( decoration: myBoxDecoration(Colors.green, Colors.grey[300]), margin: EdgeInsets.only(right: 8), child: CachedNetworkImage( imageUrl: 'https://www.bigbasket.com/media/uploads/p/l/40191789_3-storia-rose-shake.jpg', height: 40, width: 40, fit: BoxFit.cover, ), ), Container( decoration: myBoxDecoration(Colors.grey[300], Colors.grey[300]), margin: EdgeInsets.only(right: 8), child: CachedNetworkImage( imageUrl: 'https://www.bigbasket.com/media/uploads/p/l/40191789_3-storia-rose-shake.jpg', height: 40, width: 40, fit: BoxFit.cover, ), ), Container( decoration: myBoxDecoration(Colors.grey[300], Colors.grey[300]), margin: EdgeInsets.only(right: 8), child: CachedNetworkImage( imageUrl: 'https://www.bigbasket.com/media/uploads/p/l/40191789_3-storia-rose-shake.jpg', height: 40, width: 40, fit: BoxFit.cover, ), ), Container( decoration: myBoxDecoration(Colors.grey[300], Colors.grey[300]), margin: EdgeInsets.only(right: 8), child: CachedNetworkImage( imageUrl: 'https://www.bigbasket.com/media/uploads/p/l/40191789_3-storia-rose-shake.jpg', height: 40, width: 40, fit: BoxFit.cover, ), ), Container( decoration: myBoxDecoration(Colors.grey[300], Colors.grey[300]), margin: EdgeInsets.only(right: 8), height: 42, width: 42, child: Center(child: Text("+2"))), ], ), Divider( height: 28, color: Colors.grey, ), Container( padding: EdgeInsets.all(3), child: Text( 'Pack Sizes', style: TextStyle(fontSize: 16), ), ), Container( decoration: myBoxDecoration(Colors.green[200], Colors.white), margin: EdgeInsets.only(right: 8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Column( children: <Widget>[ Container( padding: EdgeInsets.all(0.5), color: Colors.redAccent, child: Text( '10% off', style: TextStyle( fontSize: 10, color: Colors.white, fontWeight: FontWeight.bold), ), ), Container( padding: EdgeInsets.all(2), child: Text( '200 ml', style: TextStyle( fontSize: 10, ), ), ), Container( child: Text( 'Bottle', style: TextStyle(fontSize: 10, color: Colors.grey), ), ), ], ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( padding: EdgeInsets.all(2), child: Text( 'Rs 27', style: TextStyle( fontSize: 10, ), ), ), Row( children: <Widget>[ Container( padding: EdgeInsets.all(1), child: Text( 'MRP:', style: TextStyle( fontSize: 10, color: Colors.grey, ), ), ), Container( padding: EdgeInsets.all(1), child: Text( ' Rs 30', style: TextStyle( fontSize: 10, color: Colors.grey, decoration: TextDecoration.lineThrough), ), ), ], ), ], ), Padding( padding: const EdgeInsets.all(8.0), child: Center( child: InkWell( onTap: () { setState(() { _value = !_value; }); }, child: Container( height: 25, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.white, border: Border.all( color: Colors .green, // <--- border color width: 2.0, ), ), child: _value ? Icon( Icons.fiber_manual_record, size: 15.0, color: Colors.black, ) : Icon( Icons.check_box_outline_blank, size: 15.0, color: Colors.white, ), ), ), ), ), ], ), ), SizedBox( height: 10, ), Container( decoration: myBoxDecoration(Colors.green[200], Colors.white), margin: EdgeInsets.only(right: 8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( padding: EdgeInsets.all(0.5), color: Colors.redAccent, child: Text( 'Rs 15 off', style: TextStyle( fontSize: 10, color: Colors.white, fontWeight: FontWeight.bold), ), ), Container( padding: EdgeInsets.all(2), child: Text( '5x200 ml', style: TextStyle( fontSize: 10, ), ), ), Container( padding: EdgeInsets.only(left: 5), child: Text( '(Multipack)', style: TextStyle(fontSize: 10, color: Colors.grey), ), ), ], ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( padding: EdgeInsets.all(2), child: Text( 'Rs 135', style: TextStyle( fontSize: 10, ), ), ), Row( children: <Widget>[ Container( padding: EdgeInsets.all(1), child: Text( 'MRP:', style: TextStyle( fontSize: 10, color: Colors.grey, ), ), ), Container( padding: EdgeInsets.all(1), child: Text( ' Rs 150', style: TextStyle( fontSize: 10, color: Colors.grey, decoration: TextDecoration.lineThrough), ), ), ], ), ], ), Padding( padding: const EdgeInsets.all(8.0), child: Center( child: InkWell( onTap: () { setState(() { _value = !_value; }); }, child: Container( height: 25, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.white, border: Border.all( color: Colors .green, // <--- border color width: 2.0, ), ), child: !_value ? Icon( Icons.fiber_manual_record, size: 15.0, color: Colors.black, ) : Icon( Icons.check_box_outline_blank, size: 15.0, color: Colors.white, ), ), ), ), ), ], ), ), SizedBox( height: 15, ), Container( color: Colors.grey[300], height: 12, ), Row( children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Icon( Icons.local_shipping, ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text("Standard Delivery : Tomorrow Morning"), ), ], ), Container( color: Colors.grey[300], height: 12, ), SizedBox( height: 15, ), ], ), ), ); } }
0
mirrored_repositories/webpctv
mirrored_repositories/webpctv/lib/environment.dart
class MyEnvironment { MyEnvironment._(); static const String applicationLegalese = "© 2022 The TV for WebPC"; static const String appName = "WebPC TV"; static String get packageName => "com.king011.webpctv"; static String get playStore => 'https://play.google.com/store/apps/details?id=$packageName'; static String version = "v0.1.1"; static bool get isProduct => const bool.fromEnvironment("dart.vm.product"); static bool get isDebug => !isProduct; static const double viewPadding = 14; static const double spacing = 10; static String durationToString(Duration duration) => duration.inDays > 0 ? "${duration.inDays} days ${duration.inHours.remainder(24).toString().padLeft(2, '0')}:${duration.inMinutes.remainder(60).toString().padLeft(2, '0')}:${duration.inSeconds.remainder(60).toString().padLeft(2, '0')}" : "${duration.inHours.toString().padLeft(2, '0')}:${duration.inMinutes.remainder(60).toString().padLeft(2, '0')}:${duration.inSeconds.remainder(60).toString().padLeft(2, '0')}"; }
0
mirrored_repositories/webpctv
mirrored_repositories/webpctv/lib/main.dart
import 'package:bot_toast/bot_toast.dart'; import 'package:flutter/material.dart'; import 'package:webpctv/pages/load/load.dart'; import 'package:webpctv/service/key_event_service.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final _focusNode = FocusNode(); @override void dispose() { _focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return KeyboardListener( focusNode: _focusNode, onKeyEvent: (evt) => KeyEventService.instance.add(evt), child: MaterialApp( title: 'webpctv', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyLoadPage(), builder: BotToastInit(), navigatorObservers: [ BotToastNavigatorObserver(), ], ), ); } }
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/db/db.dart
import 'dart:async'; import 'dart:io'; import 'package:flutter/rendering.dart'; import 'package:sqflite/sqflite.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import './data/helpers.dart'; /// 定義 static class 用於管理數據庫創建 class DB { DB._(); static const name = 'my.db'; static const version = 10; /// 初始化 ffi static Future<void> _ffiInit() async { if (databaseFactory == databaseFactoryFfi) { return; } if (Platform.isWindows || Platform.isLinux) { // Initialize FFI sqfliteFfiInit(); } else { databaseFactoryFfi.setDatabasesPath(await getDatabasesPath()); } databaseFactory = databaseFactoryFfi; } static Completer<Helpers>? _completer; /// 返回數據庫操作 helper static Future<Helpers> get helpers async { if (_completer == null) { final completer = Completer<Helpers>(); _completer = completer; // 保證同時只有一 future 執行數據庫初始化 try { await _ffiInit(); // 初始化 ffi final db = await openDatabase( name, version: version, onCreate: (Database db, int version) => Helpers.onCreate(db, version), onUpgrade: (Database db, int oldVersion, int newVersion) => Helpers.onUpgrade(db, oldVersion, newVersion), ); debugPrint("db helper ready"); completer.complete(Helpers(db)); } catch (e) { debugPrint("db init error : $e"); _completer = null; // 重置 _completer 以便可以再次執行數據庫初始化 completer.completeError(e); return completer.future; } } return _completer!.future; } }
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/db/settings.dart
import 'package:flutter/rendering.dart'; import 'package:shared_preferences/shared_preferences.dart'; class MySettings { static MySettings? _instance; static MySettings get instance { return _instance ??= MySettings._(); } MySettings._(); Future<String> getString(String key) async { try { final prefs = await SharedPreferences.getInstance(); final v = prefs.getString('settings.$key'); if (v is String) { return v; } } catch (e) { debugPrint('get string $key error: $e'); } return ''; } Future<void> setString(String key, String val) async { try { final prefs = await SharedPreferences.getInstance(); await prefs.setString('settings.$key', val); } catch (e) { debugPrint('set string $key error: $e'); } } Future<int> getInt(String key) async { try { final prefs = await SharedPreferences.getInstance(); final v = prefs.getInt('settings.$key'); if (v is int) { return v; } } catch (e) { debugPrint('get int $key error: $e'); } return 0; } Future<void> setInt(String key, int val) async { try { final prefs = await SharedPreferences.getInstance(); await prefs.setInt('settings.$key', val); } catch (e) { debugPrint('set int $key error: $e'); } } Future<int> getMode() => getInt('mode'); Future<void> setMode(int val) => setInt('mode', val); Future<int> getCaption() => getInt('caption'); Future<void> setCaption(int val) => setInt('caption', val); Future<int> getPlayMode() => getInt('playMode'); Future<void> setPlayMode(int val) => setInt('playMode', val); Future<int> getFontSize() => getInt('fontSize'); Future<void> setFontSize(int val) => setInt('fontSize', val); int? _fontSize; postSetFontSize(int val) { if (_fontSize != null) { _fontSize = val; return; } _fontSize = val; setFontSize(val).whenComplete(() { if (_fontSize == val) { _fontSize = null; } else if (_fontSize != null) { final val = _fontSize!; postSetFontSize(val); } }); } }
0
mirrored_repositories/webpctv/lib/db
mirrored_repositories/webpctv/lib/db/data/account.dart
import 'package:sqflite/sqflite.dart'; import './helper.dart'; List<int> paraseListInt(String str) { final set = <int>{}; var items = <int>[]; str.split(',').forEach((element) { try { var v = int.parse(element); if (v.isFinite) { if (!set.contains(v)) { set.add(v); items.add(v); } } } catch (_) {} }); items.sort(((a, b) => a - b)); return items; } /// 帳戶 class Account { int id; String url; String name; String password; List<int> devices; Account({ required this.id, required this.url, required this.name, required this.password, required this.devices, }); Map<String, dynamic> toMap() => <String, dynamic>{ AccountHelper.columnID: id, AccountHelper.columnURL: url, AccountHelper.columnName: name, AccountHelper.columnPassword: password, AccountHelper.columnDevices: devices.join(','), }; Account.fromMap(Map<String, dynamic> map) : id = map[AccountHelper.columnID] ?? 0, url = map[AccountHelper.columnURL] ?? '', name = map[AccountHelper.columnName] ?? '', password = map[AccountHelper.columnPassword] ?? '', devices = paraseListInt(map[AccountHelper.columnDevices]); } class AccountHelper extends Helper<Account> with Executor, HasId, HasName, ById<Account, int>, ByName<Account, String> { static const table = 'account'; static const columnID = 'id'; static const columnURL = 'url'; static const columnName = 'name'; static const columnPassword = 'password'; static const columnDevices = 'devices'; static const columns = [ columnID, columnURL, columnName, columnPassword, columnDevices, ]; static Future<void> onCreate(Database db, int version) async { await db.execute('''CREATE TABLE IF NOT EXISTS $table ( $columnID INTEGER PRIMARY KEY AUTOINCREMENT, $columnURL TEXT DEFAULT '', $columnName TEXT DEFAULT '', $columnPassword TEXT DEFAULT '', $columnDevices TEXT DEFAULT '' )'''); } static Future<void> onUpgrade( Database db, int oldVersion, int newVersion) async { if (oldVersion < 3) { await db.execute("DROP TABLE IF EXISTS $table"); } await onCreate(db, newVersion); } AccountHelper(Database db) : super(db); @override String get tableName => table; @override Account fromMap(Map<String, dynamic> map) => Account.fromMap(map); @override Map<String, dynamic> toMap(Account data, {bool insert = false}) { final m = data.toMap(); if (insert && data.id == 0) { m.remove(columnID); } return m; } }
0
mirrored_repositories/webpctv/lib/db
mirrored_repositories/webpctv/lib/db/data/helpers.dart
import 'dart:async'; import 'package:flutter/rendering.dart'; import 'package:sqflite/sqflite.dart'; import './account.dart'; import './seek.dart'; import './history.dart'; class Helpers { final AccountHelper account; final SeekHelper seek; final HistoryHelper history; Helpers(Database db) : account = AccountHelper(db), seek = SeekHelper(db), history = HistoryHelper(db); static FutureOr<void> onCreate(Database db, int version) async { debugPrint('onCreate: $version'); await AccountHelper.onCreate(db, version); await SeekHelper.onCreate(db, version); await HistoryHelper.onCreate(db, version); } static FutureOr<void> onUpgrade( Database db, int oldVersion, int newVersion, ) async { debugPrint('onUpgrade: $oldVersion -> $newVersion'); await AccountHelper.onUpgrade(db, oldVersion, newVersion); await SeekHelper.onUpgrade(db, oldVersion, newVersion); await HistoryHelper.onUpgrade(db, oldVersion, newVersion); } }
0
mirrored_repositories/webpctv/lib/db
mirrored_repositories/webpctv/lib/db/data/seek.dart
import 'package:sqflite/sqlite_api.dart'; class Seek { String url; Duration duration; int at; String name; Seek({ required this.url, required this.duration, required this.name, }) : at = DateTime.now().millisecondsSinceEpoch; Map<String, dynamic> toMap() => <String, dynamic>{ SeekHelper.columnURL: url, SeekHelper.columnDuration: duration.inMilliseconds, SeekHelper.columnAt: at, SeekHelper.columnName: name, }; Seek.fromMap(Map<String, dynamic> map) : url = map[SeekHelper.columnURL], duration = Duration(milliseconds: map[SeekHelper.columnDuration]), at = map[SeekHelper.columnAt], name = map[SeekHelper.columnName]; } class SeekHelper { static const table = 'playseek'; static const columnURL = 'url'; static const columnDuration = 'duration'; static const columnAt = 'at'; static const columnName = 'name'; static const columns = [ columnURL, columnDuration, columnAt, columnName, ]; static Future<void> onCreate(Database db, int version) async { await db.execute('''CREATE TABLE IF NOT EXISTS $table ( $columnURL TEXT PRIMARY KEY, $columnDuration INTEGER DEFAULT 0, $columnAt INTEGER DEFAULT 0, $columnName TEXT DEFAULT '' )'''); } static Future<void> onUpgrade( Database db, int oldVersion, int newVersion) async { if (oldVersion < 10) { await db.execute("DROP TABLE IF EXISTS $table"); } await onCreate(db, newVersion); } final Database db; SeekHelper(this.db); Future<Duration?> get(String url, String name) async { final list = await db.query( table, columns: columns, where: '$columnURL = ?', whereArgs: [url], limit: 1, ); if (list.isEmpty) { return null; } final data = Seek.fromMap(list.first); return data.name == name ? data.duration : null; } Future<void> put(String url, String name, Duration duration) { return db.transaction((txn) async { await txn.insert( table, Seek(url: url, duration: duration, name: name).toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); final list = await txn.query( table, orderBy: '$columnAt DESC', limit: 1, offset: 1000, ); if (list.isEmpty) { return; } final h = Seek.fromMap(list.first); await txn.delete( table, where: '$columnAt < ?', whereArgs: [h.at], ); }); } Future<int> clear() { return db.delete(table); } }
0
mirrored_repositories/webpctv/lib/db
mirrored_repositories/webpctv/lib/db/data/history.dart
import 'package:sqflite/sqlite_api.dart'; class History { String url; String name; int at; int device; String root; String path; History({ required this.name, required this.device, required this.root, required this.path, }) : at = DateTime.now().millisecondsSinceEpoch, url = Uri(queryParameters: <String, dynamic>{ 'slave_id': device.toString(), 'root': root, 'path': path, }).query; Map<String, dynamic> toMap() => <String, dynamic>{ HistoryHelper.columnURL: url, HistoryHelper.columnName: name, HistoryHelper.columnAt: at, HistoryHelper.columnDevice: device, HistoryHelper.columnRoot: root, HistoryHelper.columnPath: path, }; History.fromMap(Map<String, dynamic> map) : url = map[HistoryHelper.columnURL], name = map[HistoryHelper.columnName], at = map[HistoryHelper.columnAt], device = map[HistoryHelper.columnDevice], root = map[HistoryHelper.columnRoot], path = map[HistoryHelper.columnPath]; } class HistoryHelper { static const table = 'playhistory'; static const columnURL = 'url'; static const columnName = 'name'; static const columnAt = 'at'; static const columnDevice = 'device'; static const columnRoot = 'root'; static const columnPath = 'path'; static const columns = [ columnURL, columnName, columnAt, columnDevice, columnRoot, columnPath, ]; static Future<void> onCreate(Database db, int version) async { await db.execute('''CREATE TABLE IF NOT EXISTS $table ( $columnURL TEXT PRIMARY KEY DEFAULT '', $columnName TEXT DEFAULT '', $columnAt INTEGER DEFAULT 0, $columnDevice INTEGER DEFAULT 0, $columnRoot TEXT DEFAULT '', $columnPath TEXT DEFAULT '' )'''); await db.execute('''CREATE INDEX IF NOT EXISTS index_${columnAt}_of_$table ON $table ($columnAt); '''); } static Future<void> onUpgrade( Database db, int oldVersion, int newVersion) async { if (oldVersion < 7) { await db.execute("DROP TABLE IF EXISTS $table"); } await onCreate(db, newVersion); } final Database db; HistoryHelper(this.db); Future<History?> get(int device, String root, String path) async { final url = Uri(queryParameters: <String, dynamic>{ 'slave_id': device.toString(), 'root': root, 'path': path, }).query; final list = await db.query( table, columns: columns, where: '$columnURL = ?', whereArgs: [url], limit: 1, ); return list.isEmpty ? null : History.fromMap(list.first); } Future<void> put(History history) async { return db.transaction((txn) async { await txn.insert( table, history.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); final list = await txn.query( table, orderBy: '$columnAt DESC', limit: 1, offset: 100, ); if (list.isEmpty) { return; } final h = History.fromMap(list.first); await txn.delete( table, where: '$columnAt < ?', whereArgs: [h.at], ); }); } Future<Iterable<History>?> list() async { final list = await db.query(table, columns: columns, orderBy: "$columnAt DESC"); return list.isEmpty ? null : list.map((e) => History.fromMap(e)); } Future<int> clear() { return db.delete(table); } }
0
mirrored_repositories/webpctv/lib/db
mirrored_repositories/webpctv/lib/db/data/helper.dart
import 'dart:async'; import 'package:sqflite/sqflite.dart'; _exception(String func) => Exception('Helper function not override: $func'); abstract class Helper<T> { Helper(this.db); final Database db; String get tableName => throw _exception('get tableName'); T fromMap(Map<String, dynamic> map) => throw _exception('fromMap'); Map<String, dynamic> toMap(T data, {bool insert = false}) => throw _exception('toMap'); } mixin HasId { String get byId => 'id'; } mixin HasName { String get byName => 'name'; } /// 爲 helper 提供一些通用的 方法 mixin Executor<T> on Helper<T> { /// 查詢數據 Future<List<T>> query({ bool? distinct, List<String>? columns, String? where, List<Object?>? whereArgs, String? groupBy, String? having, String? orderBy, int? limit, int? offset, }) async { final result = <T>[]; final list = await db.query( tableName, distinct: distinct, columns: columns, where: where, whereArgs: whereArgs, groupBy: groupBy, having: having, limit: limit, offset: offset, ); for (var m in list) { result.add(fromMap(m)); } return result; } /// 查詢第一條數據 Future<T?> first({ bool? distinct, List<String>? columns, String? where, List<Object?>? whereArgs, String? groupBy, String? having, String? orderBy, int? limit, int? offset, }) async { final list = await db.query( tableName, distinct: distinct, columns: columns, where: where, whereArgs: whereArgs, groupBy: groupBy, having: having, limit: 1, ); return list.isEmpty ? null : fromMap(list.first); } /// 添加一條記錄 Future<int> add(T data, {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}) { return db.insert( tableName, toMap(data, insert: true), nullColumnHack: nullColumnHack, conflictAlgorithm: conflictAlgorithm, ); } /// 添加多條記錄 FutureOr<List<int>> addAll(Iterable<T> iterable, {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}) { if (iterable.isNotEmpty) { return <int>[]; } return db.transaction((txn) async { final result = <int>[]; for (var data in iterable) { result.add(await txn.insert( tableName, toMap(data, insert: true), nullColumnHack: nullColumnHack, conflictAlgorithm: conflictAlgorithm, )); } return result; }); } /// 刪除記錄 Future<int> delete({String? where, List<Object?>? whereArgs}) => db.delete( tableName, where: where, whereArgs: whereArgs, ); /// 修改記錄 Future<int> update( Map<String, Object?> values, { String? where, List<Object?>? whereArgs, ConflictAlgorithm? conflictAlgorithm, }) => db.update( tableName, values, where: where, whereArgs: whereArgs, conflictAlgorithm: conflictAlgorithm, ); } /// 提供 xxxById 函數 mixin ById<T, TypeID> on Helper<T>, HasId { /// 返回 id 爲指定值的數據 Future<T?> getById( TypeID id, { bool? distinct, List<String>? columns, String? groupBy, String? having, String? orderBy, int? offset, }) async { final list = await db.query( tableName, distinct: distinct, columns: columns, where: '$byId = ?', whereArgs: [id], groupBy: groupBy, having: having, limit: 1, ); return list.isEmpty ? null : fromMap(list.first); } /// 刪除 id 爲指定值的 數據 Future<int> deleteById(TypeID id) => db.delete( tableName, where: '$byId = ?', whereArgs: [id], ); /// 更新 id 爲指定值的 數據 Future<int> updateById( TypeID id, Map<String, Object?> values, { ConflictAlgorithm? conflictAlgorithm, }) => db.update( tableName, values, where: '$byId = ?', whereArgs: [id], conflictAlgorithm: conflictAlgorithm, ); } /// 提供 xxxByName 函數 mixin ByName<T, TypeName> on Helper<T>, HasName { /// 返回 name 爲指定值的數據 Future<T?> getByName( TypeName name, { bool? distinct, List<String>? columns, String? groupBy, String? having, String? orderBy, int? offset, }) async { final list = await db.query( tableName, distinct: distinct, columns: columns, where: '$byName = ?', whereArgs: [name], groupBy: groupBy, having: having, limit: 1, ); return list.isEmpty ? null : fromMap(list.first); } /// 刪除 name 爲指定值的 數據 Future<int> deleteByName(TypeName name) => db.delete( tableName, where: '$byName = ?', whereArgs: [name], ); /// 更新 name 爲指定值的 數據 Future<int> updateByName( TypeName name, Map<String, Object?> values, { ConflictAlgorithm? conflictAlgorithm, }) => db.update( tableName, values, where: '$byName = ?', whereArgs: [name], conflictAlgorithm: conflictAlgorithm, ); }
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/pages/error.dart
import 'package:flutter/material.dart'; import 'package:webpctv/environment.dart'; Future<void> pushErrorStringsPage(BuildContext context, List<String> body) { return Navigator.of(context).push( MaterialPageRoute( builder: (context) => MyErrorStringsPage( body: body, ), ), ); } Future<void> pushReplacementErrorStringsPage( BuildContext context, List<String> body) { return Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (context) => MyErrorStringsPage( body: body, ), ), ); } Future<void> pushErrorStringPage(BuildContext context, String body) { return pushErrorStringsPage(context, <String>[body]); } Future<void> pushReplacementErrorStringPage(BuildContext context, String body) { return pushReplacementErrorStringsPage(context, <String>[body]); } class MyErrorStringsPage extends StatelessWidget { const MyErrorStringsPage({ Key? key, required this.body, }) : super(key: key); final List<String> body; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: Container(), leadingWidth: 0, title: const Text('Error'), ), body: _buildBody(context), ); } Widget _buildBody(BuildContext context) { return Container( padding: const EdgeInsets.all(MyEnvironment.viewPadding), child: ListView.builder( itemCount: body.length, itemBuilder: (context, i) { final v = body[i]; return Text( v, style: TextStyle(color: Theme.of(context).errorColor), ); }, ), ); } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/load/add.dart
import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:king011_icons/king011_icons.dart'; import 'package:sqflite/sqlite_api.dart'; import 'package:webpctv/db/data/account.dart'; import 'package:webpctv/db/db.dart'; import 'package:webpctv/environment.dart'; import 'package:webpctv/pages/home/home.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/widget/spin.dart'; import 'package:webpctv/widget/state.dart'; class _FocusID { _FocusID._(); static const url = 'url'; static const name = 'name'; static const password = 'password'; static const submit = 'submit'; static const devices = 'devices'; } class MyAddPage extends StatefulWidget { const MyAddPage({ Key? key, this.account, }) : super(key: key); final Account? account; @override _MyAddPageState createState() => _MyAddPageState(); } abstract class _State extends MyState<MyAddPage> { final _urlController = TextEditingController(); final _nameController = TextEditingController(); final _passwordController = TextEditingController(); final _devicesController = TextEditingController(); final _form = GlobalKey<FormState>(); dynamic _error; final _cancelToken = CancelToken(); _submit() async { final url = _urlController.text; final name = _nameController.text; final password = _passwordController.text; final devices = paraseListInt(_devicesController.text); if (widget.account != null) { final account = widget.account!; if (account.url == url && account.name == name && account.password == password && account.devices.join(',') == devices.join(',')) { Navigator.of(context).pop(); return; } } setState(() { disabled = true; _error = null; }); try { if (!url.startsWith('http://') && !url.startsWith('https://')) { throw Exception('invalid url'); } // verify final client = Client( url: url, name: name, password: password, devices: devices, ); await client.sigin(cancelToken: _cancelToken); checkAlive(); // save db final helper = (await DB.helpers).account; checkAlive(); final account = Account( id: 1, url: url, name: name, password: password, devices: devices, ); await helper.add( account, conflictAlgorithm: ConflictAlgorithm.replace, ); checkAlive(); Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute( builder: (_) => MyHomePage( client: client, ), ), (router) => false, ); } catch (e) { aliveSetState(() { disabled = false; _error = e; }); } } } class _MyAddPageState extends _State with _KeyboardComponent { @override void initState() { super.initState(); final account = widget.account; if (account != null) { _urlController.text = account.url; _nameController.text = account.name; _passwordController.text = account.password; _devicesController.text = account.devices.join(','); } if (!_urlController.text.startsWith('http://') && !_urlController.text.startsWith('https://')) { final focus = createFocusNode(_FocusID.url); if (focus.canRequestFocus) { focus.requestFocus(); } } else if (_nameController.text.isEmpty) { final focus = createFocusNode(_FocusID.name); if (focus.canRequestFocus) { focus.requestFocus(); } } else if (_passwordController.text.isEmpty) { final focus = createFocusNode(_FocusID.password); if (focus.canRequestFocus) { focus.requestFocus(); } } else if (_devicesController.text.isEmpty) { final focus = createFocusNode(_FocusID.devices); if (focus.canRequestFocus) { focus.requestFocus(); } } listenKeyUp(onKeyUp); } @override void dispose() { _cancelToken.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return WillPopScope( child: _build(context), onWillPop: () => Future.value(enabled), ); } Widget _build(BuildContext context) { return Scaffold( appBar: AppBar( leading: backOfAppBar(context, disabled: disabled), title: const Text('Server Metadata'), ), body: Form( key: _form, child: ListView( children: [ FocusScope( node: focusScopeNode, child: TextFormField( enabled: enabled, controller: _urlController, focusNode: createFocusNode(_FocusID.url), keyboardType: TextInputType.url, decoration: const InputDecoration( prefixIcon: Icon(MaterialCommunityIcons.server), label: Text('URL'), ), onEditingComplete: () => setFocus(_FocusID.name), ), ), FocusScope( node: focusScopeNode, child: TextFormField( enabled: enabled, controller: _nameController, focusNode: createFocusNode(_FocusID.name), keyboardType: TextInputType.name, decoration: const InputDecoration( prefixIcon: Icon(Icons.account_circle), label: Text('Username'), ), onEditingComplete: () => setFocus(_FocusID.password), ), ), FocusScope( node: focusScopeNode, child: TextFormField( enabled: enabled, controller: _passwordController, focusNode: createFocusNode(_FocusID.password), keyboardType: TextInputType.visiblePassword, decoration: const InputDecoration( prefixIcon: Icon(Icons.password), label: Text('Password'), ), onEditingComplete: () => setFocus(_FocusID.devices), ), ), FocusScope( node: focusScopeNode, child: TextFormField( enabled: enabled, controller: _devicesController, focusNode: createFocusNode(_FocusID.devices), keyboardType: TextInputType.text, decoration: const InputDecoration( prefixIcon: Icon(Icons.device_hub), label: Text('Devices'), hintText: '0,1,2,3', ), onEditingComplete: () => setFocus(_FocusID.submit), ), ), _error == null ? Container() : Container( padding: const EdgeInsets.all(MyEnvironment.viewPadding), child: Text( '$_error', style: TextStyle(color: Theme.of(context).errorColor), ), ), ], ), ), floatingActionButton: _buildFloatingActionButton(context), ); } Widget? _buildFloatingActionButton(BuildContext context) { if (disabled) { return createSpinFloating(); } return FocusScope( node: focusScopeNode, child: FloatingActionButton( focusColor: Theme.of(context).focusColor.withOpacity(0.5), focusNode: createFocusNode(_FocusID.submit), child: const Icon(Icons.send), tooltip: 'Submit', onPressed: disabled ? null : _submit, ), ); } } mixin _KeyboardComponent on _State { void onKeyUp(KeyEvent evt) { if (evt.logicalKey == LogicalKeyboardKey.select) { if (enabled) { final focused = focusedNode(); if (focused != null) { _selectFocused(focused); } } } else if (evt.logicalKey == LogicalKeyboardKey.arrowDown) { final focused = focusedNode(); if (focused != null) { _nextFocus(focused); } } } _nextFocus(MyFocusNode focused) { switch (focused.id) { case _FocusID.url: setFocus(_FocusID.name, focused: focused.focusNode); break; case _FocusID.name: setFocus(_FocusID.password, focused: focused.focusNode); break; case _FocusID.password: setFocus(_FocusID.devices, focused: focused.focusNode); break; case _FocusID.devices: setFocus(_FocusID.submit, focused: focused.focusNode); break; case _FocusID.submit: setFocus(_FocusID.url, focused: focused.focusNode); break; } } _selectFocused(MyFocusNode focused) { switch (focused.id) { case _FocusID.url: case _FocusID.name: case _FocusID.password: case _FocusID.devices: _nextFocus(focused); break; case _FocusID.submit: _submit(); break; } } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/load/load.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:webpctv/db/db.dart'; import 'package:webpctv/environment.dart'; import 'package:webpctv/pages/home/home.dart'; import 'package:webpctv/pages/load/add.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/widget/state.dart'; class _FocusID { _FocusID._(); static const refish = 'refish'; } class MyLoadPage extends StatefulWidget { const MyLoadPage({ Key? key, }) : super(key: key); @override _MyLoadPageState createState() => _MyLoadPageState(); } abstract class _State extends MyState<MyLoadPage> { dynamic _error; _refish() async { aliveSetState(() { disabled = true; _error = null; }); try { // get account final helper = (await DB.helpers).account; checkAlive(); var account = await helper.getById(1); checkAlive(); final url = account?.url ?? ''; if (account == null || account.devices.isEmpty || (!url.startsWith('http://') && !url.startsWith('https://'))) { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (_) => MyAddPage( account: account, ), ), ); } else { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (_) => MyHomePage( client: Client( url: account.url, name: account.name, password: account.password, devices: account.devices, ), ), ), ); } } catch (e) { aliveSetState(() { _error = e; disabled = false; }); } } } class _MyLoadPageState extends _State with _KeyboardComponent { @override void initState() { super.initState(); Future.value().then((value) { if (isNotClosed) { _refish(); } }); listenKeyUp(onKeyUp); } @override Widget build(BuildContext context) { if (disabled) { return const Scaffold( body: Center( child: SizedBox( height: 60, child: FittedBox( child: CupertinoActivityIndicator(), ), ), ), ); } return Scaffold( body: Container( alignment: Alignment.center, padding: const EdgeInsets.all(MyEnvironment.viewPadding), child: Text( '$_error', style: TextStyle(color: Theme.of(context).errorColor), ), ), floatingActionButton: FocusScope( node: focusScopeNode, child: FloatingActionButton( focusColor: Theme.of(context).focusColor.withOpacity(0.5), focusNode: createFocusNode(_FocusID.refish), child: const Icon(Icons.refresh), tooltip: 'Refish', onPressed: disabled ? null : _refish, ), ), ); } } mixin _KeyboardComponent on _State { void onKeyUp(KeyEvent evt) { if (evt.logicalKey == LogicalKeyboardKey.select) { if (enabled) { final focused = focusedNode(); if (focused != null) { _selectFocused(focused); } } } else if (evt.logicalKey == LogicalKeyboardKey.arrowDown || evt.logicalKey == LogicalKeyboardKey.arrowUp || evt.logicalKey == LogicalKeyboardKey.arrowLeft || evt.logicalKey == LogicalKeyboardKey.arrowRight) { final focused = focusedNode(); if (focused?.id != _FocusID.refish) { setFocus(_FocusID.refish); } } } _selectFocused(MyFocusNode focused) { switch (focused.id) { case _FocusID.refish: _refish(); break; } } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/video/video.dart
import 'package:dio/dio.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:video_player/video_player.dart'; import 'package:webpctv/db/settings.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/service/wakelock_service.dart'; import 'package:webpctv/widget/state.dart'; import './controller.dart'; import './values.dart'; import './record.dart'; class MyVideoPage extends StatefulWidget { const MyVideoPage({ Key? key, required this.client, required this.device, required this.root, required this.path, required this.source, required this.videos, required this.access, this.showController = false, required this.mode, required this.caption, required this.playMode, required this.phone, required this.locked, required this.fontSize, }) : super(key: key); final Client client; final int device; final String root; final String path; final Source source; final List<Source> videos; final String access; final bool showController; final Mode mode; final int caption; final PlayMode playMode; final bool phone; final bool locked; final int fontSize; @override _MyVideoPageState createState() => _MyVideoPageState(); } abstract class _State extends MyState<MyVideoPage> { Client get client => widget.client; int get device => widget.device; String get root => widget.root; String get fullpath => widget.path; Source get source => widget.source; List<Source> get videos => widget.videos; String get access => widget.access; final cancelToken = CancelToken(); late VideoPlayerController playerController; Record? _record; Record get record => _record ?? Record( device: device, root: root, path: fullpath, name: source.fileInfo.name, ); getURL(String name) { final baseUrl = client.dio.options.baseUrl; final query = Uri(queryParameters: <String, dynamic>{ 'slave_id': device.toString(), 'root': root, 'path': getPath(name), 'access_token': access, }).query; return '${baseUrl}api/forward/v1/fs/download_access?$query'; } UI? _ui; UI get ui { var m = _ui; if (m == null) { m = UI( show: widget.showController, source: source, videos: videos, locked: widget.locked, phone: widget.phone, ); m.mode = widget.mode; m.caption = widget.caption; m.play = widget.playMode; if (widget.fontSize >= UI.minFontSize && widget.fontSize <= UI.maxFontSize) { m.fontSize = widget.fontSize; } _ui = m; } return m; } bool putseek = false; @override void initState() { super.initState(); playerController = VideoPlayerController.network( getURL(source.name), videoPlayerOptions: VideoPlayerOptions( mixWithOthers: true, ), ) ..initialize().then((_) async { if (isClosed) { return; } final duration = await record.getSeek(); if (isClosed) { return; } try { putseek = true; final value = playerController.value; if (duration != null && duration < value.duration) { await playerController.seekTo(duration); } } finally { if (isNotClosed) { playerController.play(); setCaption(); Future.delayed(const Duration(seconds: 2)).then((value) { if (isNotClosed) { record.setHistory(); } }); } } }) ..addListener(() { if (isNotClosed) { _listener(); } }); } @override void dispose() { cancelToken.cancel(); record.close(); playerController.dispose(); super.dispose(); } void setCaption() { if (!playerController.value.isInitialized) { return; } final fileinfo = ui.getCaption(); if (fileinfo == null) { playerController.setClosedCaptionFile(null); } else { var loader = source.keys[fileinfo]; if (loader == null) { loader = CaptionLoader( client: client, device: device, root: root, path: getPath(fileinfo.name), ); source.keys[fileinfo] = loader; } playerController.setClosedCaptionFile(loader.load()); } } bool _replay = false; _listener() { var value = playerController.value; if (putseek && value.isInitialized && value.isPlaying) { final position = value.position; if (position + const Duration(seconds: 10) < value.duration) { record.setSeek(position); } } if (!value.isInitialized || value.isPlaying) { setState(() {}); return; } if (value.position == value.duration) { switch (ui.play) { case PlayMode.single: break; case PlayMode.loop: _playMore(); break; case PlayMode.list: _playNext(); break; } } } _playMore() async { if (_replay) { return; } _replay = true; try { await playerController.seekTo(const Duration()); await playerController.play(); } catch (e) { debugPrint("playMore err: $e"); } finally { _replay = false; } } _playIndex(int i) async { if (_replay) { return; } _replay = true; try { if (i >= 0 && i < videos.length) { final source = videos[i]; if (source != ui.source) { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (_) => MyVideoPage( client: client, device: device, root: root, path: fullpath, source: source, videos: videos, access: access, showController: ui.show, mode: ui.mode, caption: ui.caption, fontSize: ui.fontSize, playMode: ui.play, locked: ui.locked, phone: ui.phone, ), ), ); } } } catch (e) { debugPrint("_playIndex $i err: $e"); } finally { _replay = false; } } _playNext() async { if (_replay) { return; } _replay = true; try { for (var i = 0; i < videos.length - 1; i++) { if (source == videos[i]) { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (_) => MyVideoPage( client: client, device: device, root: root, path: fullpath, source: videos[i + 1], videos: videos, access: access, showController: ui.show, mode: ui.mode, caption: ui.caption, fontSize: ui.fontSize, playMode: ui.play, locked: ui.locked, phone: ui.phone, ), ), ); return; } } } catch (e) { debugPrint("_playNext err: $e"); } finally { _replay = false; } } String getPath(String name) { return fullpath.endsWith('/') ? '$fullpath$name' : '$fullpath/$name'; } togglePlay() { final value = playerController.value; if (value.isInitialized) { if (value.isPlaying) { playerController.pause(); } else { playerController.play(); } } } Duration _seekTo = Duration.zero; bool _seeking = false; void seekPlay(bool right, {Duration duration = const Duration(seconds: 10)}) { final value = playerController.value; if (!value.isInitialized) { return; } if (right) { _seekTo += const Duration(seconds: 10); } else { _seekTo -= const Duration(seconds: 10); } if (_seeking || _seekTo == Duration.zero) { return; } final position = value.position; final to = position + _seekTo; _seekTo = Duration.zero; _seekToDuration(to); } void _seekToDuration(Duration to) async { _seeking = true; try { final value = playerController.value; if (to < Duration.zero) { to = Duration.zero; } else if (to > value.duration) { to = value.duration; } final diff = to - value.position; if (diff < const Duration(seconds: 1) && diff > const Duration(seconds: -1)) { return; } await playerController.seekTo(to); } catch (e) { if (isNotClosed) { debugPrint("seekTo $e"); } } finally { if (isNotClosed) { if (_seekTo == Duration.zero) { _seeking = false; setState(() {}); } else { final position = playerController.value.position; final to = position + _seekTo; _seekTo = Duration.zero; _seekToDuration(to); } } } } void _seekProgress(Progress progress) { if (_seeking) { return; } final value = playerController.value; if (!value.isInitialized) { return; } const values = Progress.values; for (var i = 1; i < values.length; i++) { if (progress == values[i]) { _seekToDuration(value.duration * i ~/ 10); return; } } _seekToDuration(Duration.zero); } _changedFontsize() { final val = ui.fontSizeSelected; if (val != ui.fontSize) { setState(() { ui.fontSize = val; MySettings.instance.postSetFontSize(val); }); } } } class _MyVideoPageState extends _State with _KeyboardComponent { @override void initState() { super.initState(); WakelockService.instance.enable(); listenKeyUp(onKeyUp); } @override void dispose() { WakelockService.instance.disable(); super.dispose(); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { if (ui.show) { setState(() { ui.show = false; }); return false; } return true; }, child: Scaffold( body: Container( alignment: Alignment.center, color: Colors.black, child: playerController.value.isInitialized ? _buildBody(context) : _buildLoading(context), ), ), ); } Widget _buildLoading(BuildContext context) { return Stack( alignment: Alignment.bottomCenter, children: <Widget>[ _buildController(context), const Center( child: SizedBox( height: 120, child: FittedBox( child: CupertinoActivityIndicator( color: Colors.white, ), ), ), ), ], ); } Widget _buildController(BuildContext context) { return MyControllerWidget( playerController: playerController, ui: ui, onChangedPlayMode: disabled ? null : () { setState(() { final val = ui.changePlayMode(true); MySettings.instance.setPlayMode(val); }); }, onChangedPlayList: disabled ? null : (i) => _playIndex(i), onChangedLocked: disabled ? null : () => setState(() { ui.locked = !ui.locked; }), onChangedCaption: disabled ? null : (i) { if (ui.caption != i) { setState(() { ui.caption = i; setCaption(); MySettings.instance.setCaption(i); }); } }, onChangedFontsize: _changedFontsize, onChangedSeek: disabled ? null : seekPlay, onChangeProgress: disabled ? null : () => _seekProgress(ui.progress), ); } Widget _buildBody(context) { return GestureDetector( onTap: disabled ? null : () => setState(() { ui.show = !ui.show; if (ui.show) { ui.phone = true; } }), child: Container( color: Colors.black, child: Stack( children: [ _buildVideo(context), _buildController(context), ], ), ), ); } Widget _buildVideo(BuildContext context) { return Center( child: AspectRatio( aspectRatio: playerController.value.aspectRatio, child: Stack( alignment: Alignment.bottomCenter, children: <Widget>[ VideoPlayer(playerController), ClosedCaption( text: playerController.value.caption.text, textStyle: Theme.of(context).textTheme.caption?.copyWith( fontSize: ui.fontSize.toDouble(), color: Colors.white, ), ), ui.show ? VideoProgressIndicator( playerController, allowScrubbing: !ui.locked, ) : Container(), ], ), ), ); } } mixin _KeyboardComponent on _State { void onKeyUp(KeyEvent evt) { if (ui.locked) { return; } final value = playerController.value; if (evt.logicalKey == LogicalKeyboardKey.select) { _selected(value); } else if (evt.logicalKey == LogicalKeyboardKey.arrowDown || evt.logicalKey == LogicalKeyboardKey.arrowUp) { if (ui.show) { setState(() { final val = ui.changeMode(evt.logicalKey == LogicalKeyboardKey.arrowDown); MySettings.instance.setMode(val); }); } else { setState(() { ui.show = true; }); } } else if (evt.logicalKey == LogicalKeyboardKey.arrowLeft || evt.logicalKey == LogicalKeyboardKey.arrowRight) { if (ui.show) { _changeValue(evt.logicalKey == LogicalKeyboardKey.arrowRight); } else { seekPlay(evt.logicalKey == LogicalKeyboardKey.arrowRight); } } } _selected(VideoPlayerValue value) { if (!ui.show) { togglePlay(); return; } // controller switch (ui.mode) { case Mode.none: togglePlay(); break; case Mode.playlist: _playIndex(ui.selected); break; case Mode.play: break; case Mode.caption: break; case Mode.fontsize: _changedFontsize(); break; case Mode.progress: _seekProgress(ui.progress); break; } } _changeValue(bool right) { switch (ui.mode) { case Mode.none: seekPlay(right); break; case Mode.playlist: if (ui.changeSelected(right)) { setState(() {}); } break; case Mode.play: setState(() { final val = ui.changePlayMode(right); MySettings.instance.setPlayMode(val); }); break; case Mode.caption: _changeCaption(right); break; case Mode.fontsize: _changeFontSize(right); break; case Mode.progress: setState(() { ui.changeProgress(right); }); break; } } _changeCaption(bool right) { final old = ui.caption; final val = ui.changeCaption(right); if (old != val) { setState(() { setCaption(); MySettings.instance.setCaption(val); }); } } _changeFontSize(bool right) { if (right) { if (ui.fontSizeSelected < UI.maxFontSize) { setState(() { ui.fontSizeSelected++; }); } } else { if (ui.fontSizeSelected > UI.minFontSize) { setState(() { ui.fontSizeSelected--; }); } } } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/video/controller.dart
import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; import 'package:webpctv/pages/video/label.dart'; import './values.dart'; import 'package:path/path.dart' as path; class MyControllerWidget extends StatefulWidget { const MyControllerWidget({ Key? key, required this.playerController, required this.ui, this.onChangedPlayMode, this.onChangedPlayList, this.onChangedLocked, this.onChangedCaption, this.onChangedFontsize, this.onChangedSeek, this.onChangeProgress, }) : super(key: key); final UI ui; final VideoPlayerController playerController; final VoidCallback? onChangedPlayMode; final ValueChanged<int>? onChangedPlayList; final VoidCallback? onChangedLocked; final ValueChanged<int>? onChangedCaption; final VoidCallback? onChangedFontsize; final ValueChanged<bool>? onChangedSeek; final VoidCallback? onChangeProgress; @override _MyControllerWidgetState createState() => _MyControllerWidgetState(); } class _MyControllerWidgetState extends State<MyControllerWidget> { UI get ui => widget.ui; VideoPlayerController get controller => widget.playerController; bool _closed = false; @override void dispose() { _closed = true; super.dispose(); } @override Widget build(BuildContext context) { if (!ui.show) { return Container(); } final children = <Widget>[]; final value = controller.value; children.addAll( <Widget>[ ui.locked ? Container() : Container( padding: const EdgeInsets.only(top: 10, left: 10), alignment: Alignment.topLeft, child: MyLabelWidget( label: ui.mode.name, onTab: () { setState(() { ui.changeMode(true); }); }, ), ), Container( padding: const EdgeInsets.only(top: 10, left: 10), alignment: Alignment.topRight, child: MyLabelWidget( label: ui.source.name, fontSize: 24, ), ), Container( alignment: Alignment.centerRight, padding: const EdgeInsets.only(right: 10), child: MyIconWidget( icon: ui.locked ? Icons.lock : Icons.lock_open_sharp, fontSize: 32, onTab: widget.onChangedLocked, ), ), ], ); if (!ui.locked) { switch (ui.mode) { case Mode.none: break; case Mode.playlist: children.add(_buildPlaylist(context)); break; case Mode.caption: if (ui.source.captions.isNotEmpty) { children.add(_buildCaptions(context)); } break; case Mode.fontsize: children.add(_buildFontsize(context)); break; case Mode.play: children.add( Container( padding: const EdgeInsets.only(top: 60, left: 40), alignment: Alignment.topLeft, child: MyLabelWidget( label: ui.play.name, onTab: widget.onChangedPlayMode, ), ), ); break; case Mode.progress: children.add(_buildProgress(context)); break; } } if (value.isInitialized) { children.add( Container( padding: const EdgeInsets.only(bottom: 10, right: 10), alignment: Alignment.bottomRight, child: MyLabelWidget( label: '${durationToString(value.position)} / ${durationToString(value.duration)}', fontSize: 18, ), ), ); if (ui.phone && !ui.locked) { children.addAll( <Widget>[ Center( child: Transform.translate( offset: const Offset(-120, 0), child: MyIconWidget( icon: Icons.keyboard_arrow_left, fontSize: 58, onTab: widget.onChangedSeek == null ? null : () => widget.onChangedSeek!(false), ), ), ), Center( child: value.isPlaying ? MyIconWidget( icon: Icons.pause, fontSize: 72, onTab: () => controller.pause().then((value) { if (!_closed) { setState(() {}); } }), ) : MyIconWidget( icon: Icons.play_arrow, fontSize: 72, onTab: () => controller.play().then((value) { if (!_closed) { setState(() {}); } }), ), ), Center( child: Transform.translate( offset: const Offset(120, 0), child: MyIconWidget( icon: Icons.keyboard_arrow_right, fontSize: 58, onTab: widget.onChangedSeek == null ? null : () => widget.onChangedSeek!(true), ), ), ), ], ); } } return Stack( children: children, ); } Widget _buildFontsize(BuildContext context) { return Container( padding: const EdgeInsets.only(top: 60, left: 20, right: 20), alignment: Alignment.topLeft, child: Wrap( clipBehavior: Clip.hardEdge, children: <Widget>[ MyIconWidget( icon: Icons.keyboard_arrow_left_sharp, padding: const EdgeInsets.symmetric(horizontal: 4.0), onTab: () { if (ui.fontSizeSelected > UI.minFontSize) { setState(() { ui.fontSizeSelected--; }); } }, ), Container( padding: const EdgeInsets.only(left: 4, top: 1, right: 4), child: MyLabelWidget( fontSize: 28, label: '${ui.fontSizeSelected}', onTab: widget.onChangedFontsize, ), ), MyIconWidget( icon: Icons.keyboard_arrow_right_sharp, padding: const EdgeInsets.symmetric(horizontal: 4.0), onTab: () { if (ui.fontSizeSelected < UI.maxFontSize) { setState(() { ui.fontSizeSelected++; }); } }, ), ], ), ); } Widget _buildCaption(BuildContext context, int i, bool selected) { final item = ui.source.captions[i]; var name = path.basenameWithoutExtension(item.name); final prefix = path.basenameWithoutExtension(ui.source.name); if (name.startsWith(prefix)) { name = name.substring(prefix.length); if (name.startsWith('.')) { name = name.substring(1); } if (name == '') { name = '$i'; } } else { name = '$i'; } return MyLabelWidget( label: name, fontSize: 24, color: selected ? Theme.of(context).primaryColor : null, onTab: widget.onChangedCaption == null ? null : () => widget.onChangedCaption!(i), ); } Widget _buildCaptions(BuildContext context) { const padding = EdgeInsets.only(top: 60, left: 40); const fontSize = 24.0; var i = ui.caption; if (i > ui.source.captions.length) { i = ui.source.captions.length - 1; } if (ui.phone) { final children = <Widget>[]; children.add( MyLabelWidget( label: 'close', fontSize: fontSize, color: i < 0 ? Theme.of(context).primaryColor : null, onTab: widget.onChangedCaption == null ? null : () { widget.onChangedCaption!(-1); }, ), ); for (var index = 0; index < ui.source.captions.length; index++) { children.add(_buildCaption(context, index, i == index)); } return Container( padding: padding, alignment: Alignment.topLeft, child: Wrap( clipBehavior: Clip.hardEdge, children: children, ), ); } if (ui.caption < 0) { return Container( padding: padding, alignment: Alignment.topLeft, child: const MyLabelWidget( label: 'close', fontSize: fontSize, ), ); } final item = ui.source.captions[i]; var name = path.basenameWithoutExtension(item.name); final prefix = path.basenameWithoutExtension(ui.source.name); if (name.startsWith(prefix)) { name = name.substring(prefix.length); if (name.startsWith('.')) { name = name.substring(1); } if (name == '') { name = '$i'; } } else { name = '$i'; } return Container( padding: padding, alignment: Alignment.topLeft, child: MyLabelWidget( label: name, fontSize: fontSize, ), ); } Widget _buildPlaylist(BuildContext context) { var start = ui.selected; var size = 1; final max = ui.videos.length - 1; var end = start; while (size != 3) { if (start > 0) { start--; size++; if (size == 3) { break; } } if (end < max) { end++; size++; } } final children = <Widget>[]; for (var i = start; i <= end; i++) { children.add(MyLabelWidget( label: path.basenameWithoutExtension(ui.videos[i].name), fontSize: 24, padding: const EdgeInsets.symmetric(horizontal: 8), color: i != ui.selected ? null : Theme.of(context).primaryColor, onTab: () { if (i != ui.selected) { setState(() { ui.selected = i; }); } else { if (widget.onChangedPlayList != null) { widget.onChangedPlayList!(i); } } }, )); } return Container( padding: const EdgeInsets.only(top: 60, left: 20, right: 20), alignment: Alignment.topCenter, child: Wrap( alignment: WrapAlignment.center, clipBehavior: Clip.hardEdge, children: children, ), ); } Widget _buildProgress(BuildContext context) { final value = controller.value; if (!value.isInitialized) { return Container(); } const padding = EdgeInsets.only(top: 60, left: 40); var text = '0/10 00:00'; const values = Progress.values; for (var i = 1; i < values.length; i++) { if (ui.progress == values[i]) { text = '$i/10 ${durationToString(value.duration * i ~/ 10)}'; break; } } if (ui.phone) { return Container( padding: padding, alignment: Alignment.topLeft, child: Wrap( clipBehavior: Clip.hardEdge, children: <Widget>[ MyIconWidget( icon: Icons.keyboard_arrow_left_sharp, padding: const EdgeInsets.symmetric(horizontal: 4.0), onTab: () { setState(() { ui.changeProgress(false); }); }, ), Container( padding: const EdgeInsets.only(left: 4, top: 1, right: 4), child: MyLabelWidget( label: text, fontSize: 28, onTab: widget.onChangeProgress, ), ), MyIconWidget( icon: Icons.keyboard_arrow_right_sharp, padding: const EdgeInsets.symmetric(horizontal: 4.0), onTab: () { setState(() { ui.changeProgress(true); }); }, ), ], ), ); } return Container( padding: padding, alignment: Alignment.topLeft, child: MyLabelWidget( label: text, fontSize: 28, ), ); } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/video/label.dart
import 'package:flutter/material.dart'; class MyLabelWidget extends StatelessWidget { const MyLabelWidget({ Key? key, this.fontSize, this.color, this.padding, required this.label, this.onTab, }) : super(key: key); final double? fontSize; final String label; final Color? color; final EdgeInsetsGeometry? padding; final VoidCallback? onTab; @override Widget build(BuildContext context) { return onTab != null ? GestureDetector( onTap: onTab, child: _buildBox(context), ) : _buildBox(context); } Widget _buildBox(BuildContext context) { final style = DefaultTextStyle.of(context).style.copyWith( fontSize: fontSize ?? 36.0, color: color ?? Colors.white, ); return DecoratedBox( decoration: BoxDecoration( color: const Color(0xB8000000), borderRadius: BorderRadius.circular(2.0), ), child: Padding( padding: padding ?? const EdgeInsets.symmetric(horizontal: 4.0), child: Text( label, style: style, ), ), ); } } class MyIconWidget extends StatelessWidget { const MyIconWidget({ Key? key, this.fontSize, this.color, this.padding, required this.icon, this.onTab, }) : super(key: key); final double? fontSize; final IconData icon; final Color? color; final EdgeInsetsGeometry? padding; final VoidCallback? onTab; @override Widget build(BuildContext context) { return onTab != null ? GestureDetector( onTap: onTab, child: _buildBox(context), ) : _buildBox(context); } Widget _buildBox(BuildContext context) { return Opacity( opacity: 0.75, child: DecoratedBox( decoration: BoxDecoration( color: const Color(0xB8000000), borderRadius: BorderRadius.circular(2.0), ), child: Padding( padding: padding ?? const EdgeInsets.symmetric(horizontal: 4.0, vertical: 4.0), child: Icon( icon, size: fontSize ?? 36.0, color: color ?? Colors.white, ), ), ), ); } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/video/values.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/rpc/webapi/fs.dart'; import 'package:path/path.dart' as path; enum Mode { none, playlist, caption, fontsize, // list loop single play, progress, } enum PlayMode { list, loop, single, } enum Progress { v0, v10, v20, v30, v40, v50, v60, v70, v80, v90, } class UI { bool _show; bool get show => _show; bool phone; bool locked; set show(bool v) { if (!v) { phone = false; } if (v == _show) { return; } _show = v; if (v) { resetSelected(); progress = Progress.v0; fontSizeSelected = _fontSize; } } Mode _mode = Mode.none; set mode(Mode mode) => _mode = mode; Mode get mode { final m = _mode; if (phone) { if (m == Mode.none) { return Mode.playlist; } } return m; } PlayMode play = PlayMode.list; Progress progress = Progress.v0; final List<Source> videos; int caption = 0; int _fontSize = 36; int fontSizeSelected = 36; int get fontSize => _fontSize; set fontSize(val) { _fontSize = val; fontSizeSelected = val; } static const int maxFontSize = 72; static const int minFontSize = 5; final Source source; int selected = 0; UI({ required bool show, required this.phone, required this.locked, required this.source, required this.videos, }) : _show = show { resetSelected(); } void resetSelected() { for (var i = 0; i < videos.length; i++) { if (videos[i] == source) { selected = i; } } } void changeProgress(bool right) { const values = Progress.values; final last = values.length - 1; if (right) { for (var i = 0; i < last; i++) { if (progress == values[i]) { progress = values[i + 1]; return; } } progress = values[0]; } else { for (var i = last; i > 0; i--) { if (progress == values[i]) { progress = values[i - 1]; return; } } progress = values[last]; } } bool changeSelected(bool right) { if (right) { final max = videos.length - 1; if (selected < max) { selected++; } return true; } else if (selected > 0) { selected--; return true; } return false; } int changeMode(bool down) { const values = Mode.values; final last = values.length - 1; final min = phone ? 1 : 0; if (down) { for (var i = min; i < last; i++) { if (mode == values[i]) { mode = values[i + 1]; return i + 1; } } mode = values[min]; return min; } else { for (var i = last; i > min; i--) { if (mode == values[i]) { mode = values[i - 1]; return i - 1; } } mode = values[last]; return last; } } int changePlayMode(bool right) { const values = PlayMode.values; final last = values.length - 1; if (right) { for (var i = 0; i < last; i++) { if (play == values[i]) { play = values[i + 1]; return i + 1; } } play = values[0]; return 0; } else { for (var i = last; i > 0; i--) { if (play == values[i]) { play = values[i - 1]; return i - 1; } } play = values[last]; return last; } } int changeCaption(bool right) { if (source.captions.isEmpty) { return caption; } if (right) { if (caption < 0) { caption = 0; } else { final val = caption + 1; if (val >= source.captions.length) { caption = -1; return caption; } caption = val; return val; } } else { if (caption < 0) { return caption; } final max = source.captions.length - 1; if (caption >= max) { caption = max - 1; } else { caption--; } } return caption; } FileInfo? getCaption() { if (source.captions.isEmpty || caption < 0) { return null; } var i = caption; final max = source.captions.length; if (i >= max) { i = max; } return source.captions[i]; } } class Source { bool get isDir => fileInfo.isDir; String get name => fileInfo.name; final FileInfo fileInfo; final List<FileInfo> captions; final keys = <FileInfo, CaptionLoader>{}; Source({required this.fileInfo, required this.captions}); static int compare(Source l, Source r) => FileInfo.compare(l.fileInfo, r.fileInfo); addCaptions(List<FileInfo> items) { final prefix = path.basenameWithoutExtension(fileInfo.name); for (var item in items) { if (item.isCaption && item.name.startsWith(prefix)) { captions.add(item); } } captions.sort(FileInfo.compare); } } class CaptionLoader { final Client client; final int device; final String root; final String path; CaptionLoader({ required this.client, required this.device, required this.root, required this.path, }); Completer<ClosedCaptionFile>? _completer; Future<ClosedCaptionFile> load() async { if (_completer != null) { return _completer!.future; } final completer = Completer<ClosedCaptionFile>(); _completer = completer; try { final text = await client.download(device, root, path); final result = WebVTTCaptionFile(text); completer.complete(result); } catch (e) { debugPrint("CaptionLoader $e"); _completer = null; completer.completeError(e); } return completer.future; } } String durationToString(Duration duration) { final hours = duration.inDays * 24 + duration.inHours; final ms = '${duration.inMinutes.remainder(60).toString().padLeft(2, '0')}:${duration.inSeconds.remainder(60).toString().padLeft(2, '0')}'; if (hours > 0) { return '$hours:$ms'; } return ms; }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/video/record.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:webpctv/db/data/history.dart'; import 'package:webpctv/db/db.dart'; class Record { final int device; final String root; final String path; final String name; final String _seek; bool _closed = false; bool get isClosed => _closed; bool get isNotClosed => _closed; Record({ required this.device, required this.root, required this.path, required this.name, }) : _seek = Uri(queryParameters: <String, dynamic>{ 'slave_id': device.toString(), 'root': root, 'path': path, }).query; void close() { _closed = true; } Future<Duration?> getSeek() async { try { final helpers = await DB.helpers; if (isClosed) { return null; } final helper = helpers.seek; final duration = await helper.get(_seek, name); if (isClosed) { return null; } if (duration != null && duration > const Duration(seconds: 10)) { return duration; } } catch (e) { debugPrint("getSeek error: $e"); } return null; } Duration _seekTo = Duration.zero; Duration _lastTo = Duration.zero; bool _seeking = false; FutureOr<void> setSeek(Duration duration) async { if (duration < const Duration(seconds: 10)) { return; } final diff = duration - _lastTo; if (diff > const Duration(seconds: -2) && diff < const Duration(seconds: 2)) { return; } if (_seeking) { _seekTo = duration; return; } _seeking = true; _seekTo = Duration.zero; try { final helpers = await DB.helpers; if (isClosed) { return null; } final helper = helpers.seek; await helper.put(_seek, name, duration); _lastTo = duration; } catch (e) { debugPrint("setSeek error: $e"); } finally { if (isNotClosed) { if (_seekTo == Duration.zero) { _seeking = false; } else { _seeking = false; setSeek(_seekTo); } } } } Future<void> setHistory() async { try { final helpers = await DB.helpers; if (isClosed) { return; } final helper = helpers.history; await helper.put(History( name: name, device: device, root: root, path: path, )); } catch (e) { debugPrint("setHistory error: $e"); } } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/dev/dev.dart
import 'package:flutter/material.dart'; import 'package:webpctv/rpc/webapi/client.dart'; class MyDevPage extends StatefulWidget { const MyDevPage({ Key? key, required this.client, }) : super(key: key); final Client client; @override _MyDevPageState createState() => _MyDevPageState(); } class _MyDevPageState extends State<MyDevPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('測試頁面'), ), body: ListView( children: [ TextButton( child: const Text('test'), onPressed: () { debugPrint("test button"); }, ), ], ), ); } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/home/mount.dart
import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:webpctv/pages/error.dart'; import 'package:webpctv/pages/home/list.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/widget/spin.dart'; import 'package:webpctv/widget/state.dart'; class MyMountPage extends StatefulWidget { const MyMountPage({ Key? key, required this.client, required this.device, }) : super(key: key); final Client client; final int device; @override _MyMountPageState createState() => _MyMountPageState(); } abstract class _State extends MyState<MyMountPage> { Client get client => widget.client; int get device => widget.device; final cancelToken = CancelToken(); final source = <String>[]; @override void dispose() { cancelToken.cancel(); super.dispose(); } _openRoot(String root) { Navigator.of(context).push( MaterialPageRoute( builder: (_) => MyListPage( client: client, device: device, root: root, path: '/', ), ), ); } } class _MyMountPageState extends _State with _KeyboardComponent { @override void initState() { super.initState(); Future.value().then((value) { if (isNotClosed) { _load(); } }); listenKeyUp(onKeyUp); } _load() async { setState(() { disabled = true; }); try { final resp = await client.mount(device, cancelToken: cancelToken); checkAlive(); setState(() { source.addAll(resp.name); disabled = false; }); } catch (e) { if (isNotClosed) { pushReplacementErrorStringPage(context, '$e'); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // leading: backOfAppBar(context), leading: Container(), leadingWidth: 0, title: Text('$device'), ), body: ListView( children: source .map( (item) => FocusScope( node: focusScopeNode, child: ListTile( focusNode: createFocusNode('root_$item'), leading: const Icon(Icons.star), title: Text(item), onTap: () { _openRoot(item); }, ), ), ) .toList(), ), floatingActionButton: enabled ? null : createSpinFloating(), ); } } mixin _KeyboardComponent on _State { void onKeyUp(KeyEvent evt) { if (evt.logicalKey == LogicalKeyboardKey.select) { final focused = focusedNode(); if (focused != null) { _selectFocused(focused); } } } _selectFocused(MyFocusNode focused) { final id = focused.id; if (id == MyFocusNode.arrowBack) { Navigator.of(context).pop(); return; } if (id.startsWith('root_')) { _openRoot(id.substring('root_'.length)); } } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/home/list.dart
import 'package:bot_toast/bot_toast.dart'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:webpctv/db/db.dart'; import 'package:webpctv/db/settings.dart'; import 'package:webpctv/pages/error.dart'; import 'package:webpctv/pages/video/values.dart'; import 'package:webpctv/pages/video/video.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/rpc/webapi/fs.dart'; import 'package:webpctv/service/wakelock_service.dart'; import 'package:webpctv/widget/spin.dart'; import 'package:webpctv/widget/state.dart'; class MyListPage extends StatefulWidget { const MyListPage({ Key? key, required this.client, required this.device, required this.root, required this.path, }) : super(key: key); final Client client; final int device; final String root; final String path; @override _MyListPageState createState() => _MyListPageState(); } abstract class _State extends MyState<MyListPage> { Client get client => widget.client; int get device => widget.device; String get root => widget.root; String get fullpath => widget.path; final cancelToken = CancelToken(); final keys = <String, Source>{}; final source = <Source>[]; bool hasVideo = false; final videos = <Source>[]; @override void dispose() { cancelToken.cancel(); super.dispose(); } getPath(String name) { return fullpath.endsWith('/') ? '$fullpath$name' : '$fullpath/$name'; } _openList(String name) { Navigator.of(context).push( MaterialPageRoute( builder: (_) => MyListPage( client: client, device: device, root: root, path: getPath(name), ), ), ); } Future<void> _openSource(Source source) async { final settings = MySettings.instance; var i = await settings.getMode(); var mode = Mode.none; if (i < Mode.values.length) { mode = Mode.values[i]; } checkAlive(); final caption = await settings.getCaption(); checkAlive(); final fontSize = await settings.getFontSize(); checkAlive(); i = await settings.getPlayMode(); checkAlive(); var playMode = PlayMode.list; if (i < PlayMode.values.length) { playMode = PlayMode.values[i]; } final access = await client.downloadAccess(device, cancelToken: cancelToken); checkAlive(); Navigator.of(context).push( MaterialPageRoute( builder: (_) => MyVideoPage( client: client, device: device, root: root, path: fullpath, source: source, videos: videos, access: access, mode: mode, caption: caption, fontSize: fontSize, playMode: playMode, locked: false, phone: false, ), ), ); } _openVide(String name) async { Source? source; for (var item in videos) { if (item.name == name) { source = item; break; } } if (source == null) { return; } setState(() { disabled = true; }); try { await _openSource(source); aliveSetState(() { disabled = false; }); } catch (e) { aliveSetState(() { disabled = false; BotToast.showText(text: '$e'); }); } } _playHistory() async { if (disabled) { return; } setState(() { disabled = true; }); try { final helpers = await DB.helpers; checkAlive(); final history = await helpers.history.get(device, root, fullpath); checkAlive(); Source? source; for (var item in videos) { if (item.isDir) { continue; } source ??= item; if (history == null) { break; } if (history.name == item.name) { source = item; break; } } await _openSource(source!); aliveSetState(() { disabled = false; }); } catch (e) { aliveSetState(() { disabled = false; BotToast.showText(text: '$e'); }); } } } class _MyListPageState extends _State with _KeyboardComponent { @override void initState() { super.initState(); Future.value().then((value) { if (isNotClosed) { _load(); } }); listenKeyUp(onKeyUp); } _load() async { setState(() { disabled = true; }); try { final resp = await client.list(device, root, fullpath, cancelToken: cancelToken); checkAlive(); setState(() { for (var item in resp.items) { if (item.isDir) { source.add(Source(fileInfo: item, captions: const <FileInfo>[])); continue; } else if (item.isVideo) { hasVideo = true; final node = Source(fileInfo: item, captions: <FileInfo>[]); keys[item.name] = node; source.add(node); } } source.sort(Source.compare); for (var s in source) { if (!s.isDir) { s.addCaptions(resp.items); videos.add(s); } } disabled = false; }); } catch (e) { if (isNotClosed) { pushReplacementErrorStringPage(context, '$e'); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // leading: backOfAppBar(context), leading: Container(), leadingWidth: 0, title: Text('$device $root $fullpath'), actions: hasVideo ? [ FocusScope( node: focusScopeNode, child: IconButton( focusNode: createFocusNode('play_history'), icon: const Icon(Icons.play_circle), tooltip: 'play history', onPressed: disabled ? null : _playHistory, ), ), ] : null, ), body: ListView( children: source .map( (item) => FocusScope( node: focusScopeNode, child: ListTile( focusNode: createFocusNode( '${item.isDir ? 'dir' : 'video'}_${item.name}'), leading: item.isDir ? const Icon(Icons.folder) : const Icon(Icons.video_collection), title: Text(item.name), onTap: disabled ? null : () { if (item.isDir) { _openList(item.name); } else { _openVide(item.name); } }, ), ), ) .toList(), ), floatingActionButton: enabled ? null : createSpinFloating(), ); } } mixin _KeyboardComponent on _State { void onKeyUp(KeyEvent evt) { if (evt.logicalKey == LogicalKeyboardKey.select) { final focused = focusedNode(); if (focused != null) { _selectFocused(focused); } } else if (evt.logicalKey == LogicalKeyboardKey.arrowLeft || evt.logicalKey == LogicalKeyboardKey.arrowRight) { if (hasVideo) { setFocus('play_history'); } } } _selectFocused(MyFocusNode focused) { final id = focused.id; if (id == MyFocusNode.arrowBack) { Navigator.of(context).pop(); return; } else if (id == 'play_history') { _playHistory(); return; } if (enabled) { if (id.startsWith('dir_')) { _openList(id.substring('dir_'.length)); } else if (id.startsWith('video_')) { _openVide(id.substring('video_'.length)); } } } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/home/home.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:webpctv/pages/home/history.dart'; import 'package:webpctv/pages/home/mount.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/widget/drawer.dart'; import 'package:webpctv/widget/state.dart'; class MyHomePage extends StatefulWidget { const MyHomePage({ Key? key, required this.client, }) : super(key: key); final Client client; @override _MyHomePageState createState() => _MyHomePageState(); } abstract class _State extends MyState<MyHomePage> { Client get client => widget.client; _openHistory() { Navigator.of(context).push( MaterialPageRoute( builder: (_) => MyHistoryPage( client: client, ), ), ); } _openDevice(int id) { Navigator.of(context).push( MaterialPageRoute( builder: (_) => MyMountPage( client: client, device: id, ), ), ); } } class _MyHomePageState extends _State with _KeyboardComponent { @override void initState() { super.initState(); listenKeyUp(onKeyUp); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: openDrawerOfAppBar( context, ), title: const Text('WebPC TV'), ), drawer: MyDrawerView( client: client, ), body: ListView.builder( itemCount: client.devices.length + 1, itemBuilder: (context, i) { if (i == 0) { return FocusScope( node: focusScopeNode, child: ListTile( focusNode: createFocusNode('history'), leading: const Icon(Icons.play_circle), title: const Text('play history'), onTap: () { _openHistory(); }, ), ); } final device = client.devices[i - 1]; return FocusScope( node: focusScopeNode, child: ListTile( focusNode: createFocusNode('device_$device'), leading: const Icon(Icons.star), title: Text('$device'), onTap: () { _openDevice(device); }, ), ); }), ); } } mixin _KeyboardComponent on _State { void onKeyUp(KeyEvent evt) { if (evt.logicalKey == LogicalKeyboardKey.select) { final focused = focusedNode(); if (focused != null) { _selectFocused(focused); } } } _selectFocused(MyFocusNode focused) { final id = focused.id; if (id == MyFocusNode.openDrawer) { openDrawer(); return; } else if (id == 'history') { _openHistory(); return; } if (id.startsWith('device_')) { try { final device = int.parse(id.substring('device_'.length)); _openDevice(device); } catch (_) {} } } }
0
mirrored_repositories/webpctv/lib/pages
mirrored_repositories/webpctv/lib/pages/home/history.dart
import 'package:bot_toast/bot_toast.dart'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:webpctv/db/data/history.dart'; import 'package:webpctv/db/db.dart'; import 'package:webpctv/db/settings.dart'; import 'package:webpctv/pages/error.dart'; import 'package:webpctv/pages/video/values.dart'; import 'package:webpctv/pages/video/video.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/rpc/webapi/fs.dart'; import 'package:webpctv/service/wakelock_service.dart'; import 'package:webpctv/widget/confirmation_dialog.dart'; import 'package:webpctv/widget/state.dart'; class _FocuesID { _FocuesID._(); static const clearHistory = 'clear_history'; static const clearProgress = 'clear_progress'; } class MyHistoryPage extends StatefulWidget { const MyHistoryPage({ Key? key, required this.client, }) : super(key: key); final Client client; @override _MyHistoryPageState createState() => _MyHistoryPageState(); } abstract class _State extends MyState<MyHistoryPage> { final source = <History>[]; final cancelToken = CancelToken(); @override void dispose() { cancelToken.cancel(); super.dispose(); } _openHistory(History history) async { setState(() { disabled = true; }); try { final resp = await widget.client.list( history.device, history.root, history.path, cancelToken: cancelToken, ); checkAlive(); final videos = <Source>[]; final keys = <String, Source>{}; for (var item in resp.items) { if (item.isVideo) { final node = Source(fileInfo: item, captions: <FileInfo>[]); keys[item.name] = node; videos.add(node); } } videos.sort(Source.compare); for (var s in videos) { s.addCaptions(resp.items); } if (videos.isEmpty) { throw Exception("not found any video"); } Source? source; for (var item in videos) { source ??= item; if (history.name == item.name) { source = item; break; } } await _openSource( history: history, source: source!, videos: videos, ); } catch (e) { if (isNotClosed) { BotToast.showText(text: "$e"); } } finally { aliveSetState(() { disabled = false; }); } } Future<void> _openSource({ required History history, required Source source, required List<Source> videos, }) async { final settings = MySettings.instance; var i = await settings.getMode(); var mode = Mode.none; if (i < Mode.values.length) { mode = Mode.values[i]; } checkAlive(); final caption = await settings.getCaption(); checkAlive(); final fontSize = await settings.getFontSize(); checkAlive(); i = await settings.getPlayMode(); checkAlive(); var playMode = PlayMode.list; if (i < PlayMode.values.length) { playMode = PlayMode.values[i]; } final access = await widget.client .downloadAccess(history.device, cancelToken: cancelToken); checkAlive(); Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (_) => MyVideoPage( client: widget.client, device: history.device, root: history.root, path: history.path, source: source, videos: videos, access: access, mode: mode, caption: caption, fontSize: fontSize, playMode: playMode, locked: false, phone: false, ), ), ); } _clearHistory() async { setState(() { disabled = true; }); try { final ok = await showConfirmationDialog( context, const Text('clear history'), const Text('Are you sure you want to clear history?'), ); checkAlive(); if (!ok) { return; } final helpers = await DB.helpers; checkAlive(); await helpers.history.clear(); aliveSetState(() { BotToast.showText(text: 'clear history success'); source.clear(); }); } catch (e) { if (isNotClosed) { BotToast.showText(text: '$e'); } } finally { aliveSetState(() { disabled = false; }); } } _clearProgress() async { setState(() { disabled = true; }); try { final ok = await showConfirmationDialog( context, const Text('clear play progress'), const Text('Are you sure you want to clear play progress?'), ); checkAlive(); if (!ok) { return; } final helpers = await DB.helpers; checkAlive(); await helpers.seek.clear(); BotToast.showText(text: 'clear play progress success'); } catch (e) { if (isNotClosed) { BotToast.showText(text: '$e'); } } finally { aliveSetState(() { disabled = false; }); } } } class _MyHistoryPageState extends _State with _KeyboardComponent { @override void initState() { super.initState(); listenKeyUp(onKeyUp); Future.value().then((value) { if (isNotClosed) { _load(); } }); } _load() async { try { final helpers = await DB.helpers; checkAlive(); final items = await helpers.history.list(); checkAlive(); if (items != null && items.isNotEmpty) { setState(() { source.addAll(items); }); } } catch (e) { if (isNotClosed) { pushReplacementErrorStringPage(context, '$e'); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: Container(), leadingWidth: 0, title: const Text('Play History'), actions: [ FocusScope( node: focusScopeNode, child: IconButton( focusNode: createFocusNode(_FocuesID.clearHistory), icon: const Icon(Icons.delete_forever), tooltip: 'clear history', onPressed: disabled ? null : _clearHistory, ), ), FocusScope( node: focusScopeNode, child: IconButton( focusNode: createFocusNode(_FocuesID.clearProgress), icon: const Icon(Icons.auto_delete_outlined), tooltip: 'clear progress', onPressed: disabled ? null : _clearProgress, ), ), ], ), body: ListView.builder( itemCount: source.length, itemBuilder: (context, i) { final item = source[i]; return FocusScope( node: focusScopeNode, child: ListTile( focusNode: createFocusNode('index_$i', data: item), leading: const Icon(Icons.play_circle), title: Text(item.name), subtitle: Text( '${item.device} ${item.path}', ), onTap: disabled ? null : () { _openHistory(item); }, ), ); }), ); } } mixin _KeyboardComponent on _State { void onKeyUp(KeyEvent evt) { if (evt.logicalKey == LogicalKeyboardKey.select) { final focused = focusedNode(); if (focused != null) { _selectFocused(focused); } } else if (evt.logicalKey == LogicalKeyboardKey.arrowLeft || evt.logicalKey == LogicalKeyboardKey.arrowRight) { final focused = focusedNode(); final id = focused?.id ?? ''; if (id.startsWith('index_')) { setFocus(_FocuesID.clearProgress); } } } _selectFocused(MyFocusNode focused) { final id = focused.id; if (enabled) { if (id == _FocuesID.clearHistory) { _clearHistory(); } else if (id == _FocuesID.clearProgress) { _clearProgress(); } else if (id.startsWith('index_') && focused.data is History) { _openHistory(focused.data); } } } }
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/service/wakelock_service.dart
import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:wakelock/wakelock.dart'; class WakelockService { static WakelockService? _instance; static WakelockService get instance => _instance ??= WakelockService._(); WakelockService._(); bool? _work; /// https://pub.dev/packages/wakelock bool get isSupported => Platform.isAndroid || Platform.isIOS || Platform.isMacOS || Platform.isWindows; int _count = 0; bool _enable = false; void enable() { if (isSupported) { _count++; if (_count > 0) { _work = true; } _run(); } } void disable() { if (isSupported) { _count--; if (_count < 1) { _work = false; } _run(); } } final _mutex = Mutex(); _run() async { bool lock = _mutex.tryLock(); if (!lock) { return false; } try { while (_work != null) { final work = _work!; _work = null; if (work) { if (!_enable) { SystemChrome.setEnabledSystemUIMode( SystemUiMode.manual, overlays: [SystemUiOverlay.bottom], ); _enable = true; await Wakelock.enable(); } } else { if (_enable) { SystemChrome.setEnabledSystemUIMode( SystemUiMode.edgeToEdge, ); _enable = false; await Wakelock.disable(); } } } } finally { _mutex.unlock(); } } } class Mutex { Completer<void>? _completer; Future<void> lock() async { if (_completer != null) { await _completer!.future; } _completer = Completer<void>(); } bool tryLock() { if (_completer != null) { return false; } _completer = Completer<void>(); return true; } void unlock() { final completer = _completer!; _completer = null; completer.complete(); } }
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/service/key_event_service.dart
import 'package:flutter/services.dart'; typedef KeyUpListener = void Function(KeyEvent); /// 全局鍵盤 用於 快捷鍵 和 適配電視 class KeyEventService { static KeyEventService? _instance; static KeyEventService get instance => _instance ??= KeyEventService._(); KeyEventService._(); void add(KeyEvent evt) { if (evt is KeyUpEvent) { if (_keyUplisteners.isNotEmpty) { _keyUplisteners.last(evt); } } } final _keyUplisteners = <KeyUpListener>[]; void addKeyUpListener(KeyUpListener listener) { _keyUplisteners.add(listener); } void removeKeyUpListener(KeyUpListener listener) { _keyUplisteners.remove(listener); } }
0
mirrored_repositories/webpctv/lib/rpc
mirrored_repositories/webpctv/lib/rpc/webapi/rpc.dart
import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; import 'dart:io'; import 'package:crypto/crypto.dart'; import 'package:flutter/foundation.dart'; class Token { static int _parseInt(dynamic val) { if (val is int) { return val; } else if (val is String) { return int.parse(val); } return 0; } String access; String refresh; int accessDeadline; int refreshDeadline; int deadline; bool deleted = false; Token.fromJson(Map<String, dynamic> json) : access = json["access"], refresh = json["refresh"], accessDeadline = _parseInt(json["accessDeadline"]), refreshDeadline = _parseInt(json["refreshDeadline"]), deadline = _parseInt(json["deadline"]) { debugPrint("Token.access: $access"); debugPrint("Token.refresh: $access"); } } class SiginResponse { Token token; SiginResponse.fromJson(Map<String, dynamic> json) : token = Token.fromJson(json["token"]); } class RefreshResponse { Token token; RefreshResponse.fromJson(Map<String, dynamic> json) : token = Token.fromJson(json["token"]); } abstract class RpcClient { final Dio dio; final String name; final String password; final List<int> devices; RpcClient({ required this.dio, required this.name, required this.password, required this.devices, }); Token? _token; Future<Token> sigin({CancelToken? cancelToken}) async { final token = await _sigin(cancelToken: cancelToken); _token = token; return token; } Future<Token> _sigin({CancelToken? cancelToken}) async { try { final platform = Platform.operatingSystem; final unix = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString(); var pwd = md5.convert(utf8.encode(password)).toString(); pwd = md5.convert(utf8.encode('$platform.$pwd.$unix')).toString(); final resp = await dio.post( 'api/v1/sessions', data: <String, dynamic>{ 'platform': platform, 'name': name, 'password': pwd, 'unix': unix, }, cancelToken: cancelToken, ); return SiginResponse.fromJson(resp.data).token; } on DioError catch (e) { throw Exception('${e.message} ${e.response?.data}'); } } Future<Token> refresh(Token token) async { try { final resp = await dio.post( 'api/v1/sessions/refresh', data: <String, dynamic>{ 'access': token.access, 'refresh': token.refresh, }, ); return RefreshResponse.fromJson(resp.data).token; } on DioError catch (e) { final statusCode = e.response?.statusCode ?? 0; if (statusCode == 401) { return await sigin(); } else { throw Exception('${e.message} ${e.response?.data}'); } } } Completer<Token>? _completer; Future<Token> refreshToken({Token? token}) async { var completer = _completer; if (completer != null) { return completer.future; } completer = Completer<Token>(); _completer = completer; try { if (token == null) { final result = await sigin(); _token = result; _completer = null; completer.complete(result); } else { final result = await refresh(token); _token = result; _completer = null; completer.complete(result); } } catch (e) { _completer = null; completer.completeError(e); } return completer.future; } Future<Token> getToken() async { var completer = _completer; if (completer != null) { return completer.future; } var result = _token; if (result == null) { return refreshToken(); } else if (result.deleted) { return refreshToken(); } final deadline = DateTime.now() .add(const Duration(minutes: -5)) .millisecondsSinceEpoch ~/ 1000; if (result.accessDeadline < deadline) { if (result.refreshDeadline < deadline) { if (result.deadline != 0 && result.deadline < deadline) { result = await refreshToken(token: result); } else { result = await refreshToken(); } } else { result = await refreshToken(); } } return result; } }
0
mirrored_repositories/webpctv/lib/rpc
mirrored_repositories/webpctv/lib/rpc/webapi/session.dart
import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:webpctv/rpc/webapi/rpc.dart'; mixin Session on RpcClient { Future<String> downloadAccess(int device, {CancelToken? cancelToken}) async { final token = await getToken(); return _downloadAccess(token, device, cancelToken: cancelToken); } Future<String> _downloadAccess( Token token, int device, { CancelToken? cancelToken, bool retry = true, }) async { try { final resp = await dio.post( 'api/v1/sessions/download_access', cancelToken: cancelToken, options: Options(headers: { 'Authorization': 'Bearer ${token.access}', }), ); return resp.data["access"]; } on DioError catch (e) { if (retry && (e.response?.statusCode ?? 0) == 401) { try { token = await refreshToken(token: token); return _downloadAccess( token, device, cancelToken: cancelToken, retry: false, ); } catch (err) { debugPrint("retry $err"); throw e; } } rethrow; } } Future<String> download( int device, String root, String path, { CancelToken? cancelToken, }) async { final token = await getToken(); return _download(token, device, root, path, cancelToken: cancelToken); } Future<String> _download( Token token, int device, String root, String path, { CancelToken? cancelToken, bool retry = true, }) async { try { final resp = await dio.get( 'api/forward/v1/fs/download', queryParameters: { 'slave_id': device, 'root': root, 'path': path, }, cancelToken: cancelToken, options: Options( headers: { 'Authorization': 'Bearer ${token.access}', }, responseType: ResponseType.plain, ), ); return resp.data; } on DioError catch (e) { if (retry && (e.response?.statusCode ?? 0) == 401) { try { token = await refreshToken(token: token); return _downloadAccess( token, device, cancelToken: cancelToken, retry: false, ); } catch (err) { debugPrint("retry $err"); throw e; } } rethrow; } } }
0
mirrored_repositories/webpctv/lib/rpc
mirrored_repositories/webpctv/lib/rpc/webapi/fs.dart
import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:webpctv/rpc/webapi/rpc.dart'; import 'package:path/path.dart' as path; List<String> parseStrings(dynamic val) { if (val is List) { return val.map((e) => '$e').toList(); } return <String>[]; } class MountResponse { List<String> name; MountResponse.fromJson(Map<String, dynamic> json) : name = parseStrings(json["name"]); } class FileInfo { String name; bool isDir; FileInfo.fromJson(Map<String, dynamic> json) : name = json["name"], isDir = json["isDir"]; @override String toString() { return "${isDir ? 'd' : '-'} $name"; } static int compare(FileInfo l, FileInfo r) { final d0 = l.isDir ? 0 : 1; final d1 = r.isDir ? 0 : 1; final v = d0 - d1; if (v != 0) { return v; } return l.name.compareTo(r.name); } bool get isCaption { if (isDir) { return false; } final ext = path.extension(name).toLowerCase(); return ext == '.vtt'; } bool get isVideo { if (isDir) { return false; } final ext = path.extension(name).toLowerCase(); return ext == '.webm' || ext == '.mp4' || ext == '.m4v' || ext == '.mov' || ext == '.avi' || ext == '.flv' || ext == '.wmv' || ext == '.asf' || ext == '.mpeg' || ext == '.mpg' || ext == '.vob' || ext == '.mkv' || ext == '.rm' || ext == '.rmvb'; } } class ListResponse { static List<FileInfo> _parseItems(dynamic v) { if (v is List) { return v.map((e) => FileInfo.fromJson(e)).toList(); } return <FileInfo>[]; } List<FileInfo> items; ListResponse.fromJson(Map<String, dynamic> json) : items = _parseItems(json["items"]); } mixin FileSystem on RpcClient { Future<MountResponse> mount(int device, {CancelToken? cancelToken}) async { final token = await getToken(); return _mount(token, device, cancelToken: cancelToken); } Future<MountResponse> _mount( Token token, int device, { CancelToken? cancelToken, bool retry = true, }) async { try { final resp = await dio.get( 'api/forward/v1/fs/mount', queryParameters: { 'slave_id': device, }, cancelToken: cancelToken, options: Options(headers: { 'Authorization': 'Bearer ${token.access}', }), ); return MountResponse.fromJson(resp.data); } on DioError catch (e) { if (retry && (e.response?.statusCode ?? 0) == 401) { try { token = await refreshToken(token: token); return _mount( token, device, cancelToken: cancelToken, retry: false, ); } catch (err) { debugPrint("retry $err"); throw e; } } rethrow; } } Future<ListResponse> list( int device, String root, String path, { CancelToken? cancelToken, }) async { final token = await getToken(); return _list(token, device, root, path, cancelToken: cancelToken); } Future<ListResponse> _list( Token token, int device, String root, String path, { CancelToken? cancelToken, bool retry = true, }) async { try { final resp = await dio.get( 'api/forward/v1/fs/list', queryParameters: { 'slave_id': device, 'root': root, 'path': path, }, cancelToken: cancelToken, options: Options(headers: { 'Authorization': 'Bearer ${token.access}', }), ); return ListResponse.fromJson(resp.data); } on DioError catch (e) { if (retry && (e.response?.statusCode ?? 0) == 401) { try { token = await refreshToken(token: token); return _list( token, device, root, path, cancelToken: cancelToken, retry: false, ); } catch (err) { debugPrint("retry $err"); throw e; } } rethrow; } } }
0
mirrored_repositories/webpctv/lib/rpc
mirrored_repositories/webpctv/lib/rpc/webapi/client.dart
import 'package:dio/dio.dart'; import 'package:webpctv/rpc/webapi/fs.dart'; import 'package:webpctv/rpc/webapi/session.dart'; import './rpc.dart'; class Client extends RpcClient with FileSystem, Session { final String url; Client({ required this.url, required String name, required String password, required List<int> devices, }) : super( dio: Dio()..options.baseUrl = url.endsWith('/') ? url : url + '/', name: name, password: password, devices: devices, ); }
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/widget/state.dart
import 'package:flutter/material.dart'; import 'package:ppg_ui/state/state.dart'; import 'package:webpctv/service/key_event_service.dart'; class MyFocusNode { final String id; FocusNode focusNode; dynamic data; MyFocusNode({required this.id, required this.focusNode, this.data}); void dispose() { focusNode.dispose(); } bool get isArrowBack => id == arrowBack; static const openDrawer = 'openDrawer'; static const arrowBack = 'arrow_back'; } abstract class MyState<T extends StatefulWidget> extends UIState<T> { final _keysFocusNode = <String, MyFocusNode>{}; final _focusNodeKeys = <FocusNode, MyFocusNode>{}; final FocusScopeNode focusScopeNode = FocusScopeNode(); KeyUpListener? _onKeyUp; void listenKeyUp(KeyUpListener onKeyUp) { if (isClosed) { return; } if (_onKeyUp != null) { KeyEventService.instance.removeKeyUpListener(_onKeyUp!); } _onKeyUp = onKeyUp; KeyEventService.instance.addKeyUpListener(onKeyUp); } @protected MyFocusNode? getFocusNode(String id) => _keysFocusNode[id]; @protected FocusNode createFocusNode(String id, {dynamic data}) { final focusNode = _keysFocusNode[id]; if (focusNode != null) { if (focusNode.data != data) { focusNode.data = data; } return focusNode.focusNode; } final add = MyFocusNode(id: id, focusNode: FocusNode(), data: data); _keysFocusNode[id] = add; _focusNodeKeys[add.focusNode] = add; return add.focusNode; } @protected MyFocusNode? focusedNode() { if (focusScopeNode.hasFocus) { return _focusNodeKeys[focusScopeNode.focusedChild]; } return null; } @protected void setFocus(String id, {FocusNode? focused}) { final focus = _keysFocusNode[id]?.focusNode; focused?.unfocus(); if (focus?.canRequestFocus ?? false) { focus!.requestFocus(); } } @protected void nextFocus(List<String> values, MyFocusNode? focused) { var i = focused == null ? 0 : values.indexOf(focused.id) + 1; if (i >= values.length) { i = 0; } setFocus(values[i], focused: focused?.focusNode); } @mustCallSuper @override void dispose() { if (_onKeyUp != null) { KeyEventService.instance.removeKeyUpListener(_onKeyUp!); _onKeyUp = null; } _keysFocusNode.forEach((key, value) { value.dispose(); }); focusScopeNode.dispose(); super.dispose(); } @protected Widget? backOfAppBar( BuildContext context, { dynamic data, bool disabled = false, }) { final ModalRoute<dynamic>? parentRoute = ModalRoute.of(context); final bool canPop = parentRoute?.canPop ?? false; if (!canPop) { return null; } return FocusScope( node: focusScopeNode, child: IconButton( focusNode: createFocusNode( MyFocusNode.arrowBack, data: data, ), icon: const Icon(Icons.arrow_back), iconSize: 24, onPressed: disabled ? null : () => Navigator.of(context).pop(), tooltip: MaterialLocalizations.of(context).backButtonTooltip, ), ); } BuildContext? _scaffold; openDrawer() { if (_scaffold != null) { Scaffold.of(_scaffold!).openDrawer(); } } @protected Widget openDrawerOfAppBar(BuildContext context, {dynamic data}) { return FocusScope( node: focusScopeNode, child: Builder( builder: (context) { _scaffold = context; return IconButton( focusNode: createFocusNode( MyFocusNode.openDrawer, data: data, ), icon: const Icon(Icons.menu), iconSize: 24, onPressed: () => Scaffold.of(context).openDrawer(), tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip, ); }, ), ); } }
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/widget/confirmation_dialog.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:webpctv/service/key_event_service.dart'; Future<bool> showConfirmationDialog( BuildContext context, Widget title, Widget child, ) { return showDialog( context: context, builder: (context) => MyConfirmationDialog( title: title, child: child, ), ).then((ok) { return (ok ?? false); }); } class MyConfirmationDialog extends StatefulWidget { const MyConfirmationDialog({ Key? key, this.title, required this.child, }) : super(key: key); final Widget? title; final Widget child; @override _MyAccountPageState createState() => _MyAccountPageState(); } class _MyAccountPageState extends State<MyConfirmationDialog> { final _focusScopeNode = FocusScopeNode(); final _focusOk = FocusNode(); final _focusCancel = FocusNode(); @override void initState() { super.initState(); KeyEventService.instance.addKeyUpListener(_listener); } _listener(KeyEvent evt) { if (!_focusScopeNode.hasFocus) { return; } if (evt.logicalKey == LogicalKeyboardKey.select) { if (_focusOk.hasFocus) { Navigator.of(context).pop(true); } else if (_focusCancel.hasFocus) { Navigator.of(context).pop(false); } } } @override void dispose() { KeyEventService.instance.removeKeyUpListener(_listener); _focusOk.dispose(); _focusCancel.dispose(); _focusScopeNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AlertDialog( title: widget.title, content: SingleChildScrollView( child: widget.child, ), actions: <Widget>[ FocusScope( autofocus: true, node: _focusScopeNode, child: TextButton( focusNode: _focusOk, child: Text(MaterialLocalizations.of(context).okButtonLabel), onPressed: () => Navigator.of(context).pop(true), ), ), FocusScope( node: _focusScopeNode, child: TextButton( focusNode: _focusCancel, child: Text(MaterialLocalizations.of(context).cancelButtonLabel), onPressed: () => Navigator.of(context).pop(false), ), ), ], ); } }
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/widget/spin.dart
import 'package:flutter/material.dart'; import 'package:king011_icons/king011_icons.dart'; import 'package:ppg_ui/widget/spin.dart'; Spin createSpin() => const Spin( child: Icon( FontAwesome.spinner, size: 32, ), ); FloatingActionButton createSpinFloating() => const FloatingActionButton( child: Spin( child: Icon( FontAwesome.spinner, size: 32, ), ), onPressed: null, ); Widget buildError(BuildContext context, error) => Text( "$error", style: TextStyle(color: Theme.of(context).errorColor), );
0
mirrored_repositories/webpctv/lib
mirrored_repositories/webpctv/lib/widget/drawer.dart
import 'dart:io'; import 'package:bot_toast/bot_toast.dart'; import 'package:flutter/material.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:url_launcher/url_launcher_string.dart'; import 'package:webpctv/db/data/account.dart'; import 'package:webpctv/environment.dart'; import 'package:webpctv/pages/dev/dev.dart'; import 'package:webpctv/pages/load/add.dart'; import 'package:webpctv/rpc/webapi/client.dart'; import 'package:webpctv/widget/state.dart'; class _FocusID { _FocusID._(); static const account = 'account'; static const help = 'help'; static const about = 'about'; } class MyDrawerView extends StatefulWidget { const MyDrawerView({ Key? key, this.disabled = false, required this.client, }) : super(key: key); /// 是否禁用 功能按鈕 final bool disabled; final Client client; @override _MyDrawerViewState createState() => _MyDrawerViewState(); } abstract class _State extends MyState<MyDrawerView> { final _recognizer = <String, TapGestureRecognizer>{}; TapGestureRecognizer createRecognizer(String id) { var recognizer = _recognizer[id]; if (recognizer == null) { recognizer = TapGestureRecognizer(); _recognizer[id] = recognizer; } return recognizer; } @override void dispose() { _recognizer.forEach((key, value) { value.dispose(); }); super.dispose(); } Widget _richTextUrl(String tag, String url, TextStyle? style) { return RichText( text: TextSpan( children: <TextSpan>[ TextSpan(style: style, text: '$tag '), TextSpan( style: style?.copyWith( color: Theme.of(context).colorScheme.secondary, ), text: url, recognizer: createRecognizer(url) ..onTap = () async { try { debugPrint('launch $url'); await launchUrlString(url, mode: LaunchMode.externalApplication); } catch (e) { BotToast.showText(text: '$e'); } }, ), TextSpan(style: style, text: ' .'), ], ), ); } void _openAbout() { final TextStyle? textStyle = Theme.of(context).textTheme.bodyText1; final children = <Widget>[ _richTextUrl( 'Source code at', 'https://github.com/powerpuffpenguin/webpctv', textStyle, ), _richTextUrl( 'LICENSE at', 'https://raw.githubusercontent.com/powerpuffpenguin/webpctv/main/LICENSE', textStyle, ), ]; if (Platform.isAndroid) { children.add( _richTextUrl('Play Store at', MyEnvironment.playStore, textStyle)); } showAboutDialog( context: context, applicationName: 'Webpc TV', applicationVersion: MyEnvironment.version, applicationLegalese: MyEnvironment.applicationLegalese, children: children, ); } void _openHelp() async { try { const url = 'https://github.com/powerpuffpenguin/webpctv/issues'; debugPrint('launch $url'); await launchUrlString(url, mode: LaunchMode.externalApplication); } catch (e) { if (isNotClosed) { BotToast.showText(text: '$e'); } } } void _openAccount() { final client = widget.client; Navigator.of(context).push( MaterialPageRoute( builder: (_) => MyAddPage( account: Account( id: 1, url: client.url, name: client.name, password: client.password, devices: client.devices, ), ), ), ); } } class _MyDrawerViewState extends _State with _KeyboardComponent { Client get client => widget.client; @override void initState() { super.initState(); listenKeyUp(onKeyUp); } @override Widget build(BuildContext context) { final children = <Widget>[ DrawerHeader( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Image.asset( "assets/webpctv.png", ), Text(client.name), Text(client.url), ], ), ), ]; children.addAll(<Widget>[ FocusScope( node: focusScopeNode, child: ListTile( focusNode: createFocusNode(_FocusID.account), leading: const Icon(Icons.account_box), title: const Text('account'), onTap: widget.disabled ? null : _openAccount, ), ), const Divider(), FocusScope( autofocus: true, node: focusScopeNode, child: ListTile( focusNode: createFocusNode(_FocusID.help), leading: const Icon(Icons.help), title: const Text('help'), onTap: widget.disabled ? null : _openHelp, ), ), const Divider(), FocusScope( autofocus: true, node: focusScopeNode, child: ListTile( focusNode: createFocusNode(_FocusID.about), leading: const Icon(Icons.info), title: Text( MaterialLocalizations.of(context) .aboutListTileTitle(MyEnvironment.appName), ), onTap: widget.disabled ? null : _openAbout, ), ), ]); if (MyEnvironment.isDebug) { children.addAll(<Widget>[ const Divider(), ListTile( leading: const Icon(Icons.adb), title: const Text("測試"), onTap: widget.disabled ? null : () { Navigator.of(context).push( MaterialPageRoute( builder: (_) => MyDevPage( client: widget.client, ), ), ); }, ), ]); } return Drawer( child: ListView( children: children, ), ); } } mixin _KeyboardComponent on _State { void onKeyUp(KeyEvent evt) { if (evt.logicalKey == LogicalKeyboardKey.select) { if (enabled) { final focused = focusedNode(); if (focused != null) { _selectFocused(focused); } } } } _selectFocused(MyFocusNode focused) { switch (focused.id) { case _FocusID.account: _openAccount(); break; case _FocusID.help: _openHelp(); break; case _FocusID.about: _openAbout(); break; } } }
0
mirrored_repositories/webpctv
mirrored_repositories/webpctv/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:webpctv/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/status-story
mirrored_repositories/status-story/lib/main.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:story_view/story_view.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Status Stories', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.pink, ), home: Home()); } } class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { final storyController = StoryController(); @override void dispose() { storyController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: StoryView( [ //The StoryItem.text accepts a text, you can add any text you want StoryItem.text( "WOW !!! i built my first status story", Colors.pinkAccent, fontSize: 25 ), //The StoryItem.pageImage accepts an image, you can add any image you want //In this tutorial, Cached Network Image Provider was used so as to load the image and also cache images //StoryItem.pageImage accepts a caption //The caption describes the image StoryItem.pageImage( CachedNetworkImageProvider( "https://i.pinimg.com/originals/f6/eb/53/f6eb535411056b553dfdec1665387c0c.jpg"), caption: "Simply beautiful😘😘😘", ), StoryItem.pageImage( CachedNetworkImageProvider( "https://i.pinimg.com/originals/f6/eb/53/f6eb535411056b553dfdec1665387c0c.jpg"), caption: "Simply beautiful😘😘😘", ), StoryItem.pageImage( CachedNetworkImageProvider( "http://s3.weddbook.com/t4/2/5/0/2501568/vanila-wedding-boutique-dubai-on-instagram-have-a-lovely-weekend-everyone-let-it-be-sunny-throughout-the-upcoming-days-to-enjoy-the-beach-and-the-sea-our-lovely-vanila-bride.jpg"), caption: "Vanila Wedding Boutique Dubai", ), StoryItem.pageImage( CachedNetworkImageProvider( "https://i0.pickpik.com/photos/836/957/310/adventure-jump-hipster-ext-preview.jpg"), caption: "Jumping beside cliff during daytime", ), //The StoryItem.pageGif accepts a GIf, you can add any Gif you want //It accepts a caption. The caption describes the Gif StoryItem.pageGif( "https://media.giphy.com/media/XcA8krYsrEAYXKf4UQ/giphy.gif", caption: "Thanks for watching", controller: storyController, ), //The StoryItem.pageVideo accepts a Video. //It accepts a caption. The caption describes the video StoryItem.pageVideo( "https://firebasestorage.googleapis.com/v0/b/tactile-timer-267314.appspot.com/o/Hang%20-%2030902.mp4?alt=media&token=74eec54b-7c4a-43dc-bd7a-522a494b69c0", caption: "title of the video", controller: storyController, shown: true, duration: Duration(m) ), ], onStoryShow: (s) { print("Showing a story"); }, onComplete: () { print("Completed a cycle"); }, progressPosition: ProgressPosition.top, repeat: true, controller: storyController, ), ); } }
0
mirrored_repositories/status-story
mirrored_repositories/status-story/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:status_story_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/launch_pad_complete
mirrored_repositories/launch_pad_complete/lib/main.dart
import 'package:audioplayers/audioplayers.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: "LaunchPad", debugShowCheckedModeBanner: false, home: SafeArea( child: Scaffold( appBar: AppBar( title: Text("LaunchPad", style: GoogleFonts.orbitron()), backgroundColor: Colors.black, ), backgroundColor: Colors.black, body: Center( child: Wrap( spacing: 6, runSpacing: 6, children: [ Pad(Color(0xffADCBFC), Color(0xff067CCB), "1.mp3"), Pad(Color(0xffff2525), Color(0xffc40050), "2.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "3.mp3"), Pad(Color(0xffE247FC), Color(0xffA23AB7), "4.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "5.mp3"), Pad(Color(0xffff2525), Color(0xffc40050), "6.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "7.mp3"), Pad(Color(0xffE247FC), Color(0xffA23AB7), "8.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "9.mp3"), Pad(Color(0xffff2525), Color(0xffc40050), "10.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "11.mp3"), Pad(Color(0xffE247FC), Color(0xffA23AB7), "12.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "13.mp3"), Pad(Color(0xffff2525), Color(0xffc40050), "14.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "15.mp3"), Pad(Color(0xffE247FC), Color(0xffA23AB7), "16.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "17.mp3"), Pad(Color(0xffff2525), Color(0xffc40050), "18.mp3"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "19.mp3"), Pad(Color(0xffE247FC), Color(0xffA23AB7), "20.wav"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "21.mp3"), Pad(Color(0xffff2525), Color(0xffc40050), "22.wav"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "23.wav"), Pad(Color(0xffE247FC), Color(0xffA23AB7), "24.wav"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "25.wav"), Pad(Color(0xffff2525), Color(0xffc40050), "26.wav"), Pad(Color(0xffADCBFC), Color(0xff067CCB), "27.wav"), Pad(Color(0xffE247FC), Color(0xffA23AB7), "28.wav"), ], ), ), ), ), ); } } class Pad extends StatefulWidget { final colorCenter; final colorOutline; final note; Pad(this.colorCenter, this.colorOutline, this.note, {Key? key}) : super(key: key); @override _PadState createState() => _PadState(); } class _PadState extends State<Pad> { late Color colorCenter; late Color colorOutline; final player = AudioPlayer(); @override void initState() { colorCenter = widget.colorCenter; colorOutline = widget.colorOutline; super.initState(); } @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; return GestureDetector( onTap: () async { setState(() { player.play(AssetSource(widget.note)); colorCenter = Colors.white; colorOutline = Colors.white; }); await Future.delayed(const Duration(milliseconds: 500)); setState(() { colorCenter = widget.colorCenter; colorOutline = widget.colorOutline; }); }, child: Container( height: height / 8.2, width: width / 4.3, decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.pink, blurRadius: 5.0, ), ], borderRadius: BorderRadius.all(Radius.circular(6.0)), gradient: RadialGradient(colors: [ colorCenter, colorOutline, ], radius: 0.5), ), ), ); } }
0
mirrored_repositories/launch_pad_complete
mirrored_repositories/launch_pad_complete/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:launch_pad/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter-words-pair
mirrored_repositories/flutter-words-pair/lib/main.dart
import 'package:flutter/material.dart'; import 'package:english_words/english_words.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(primaryColor: Colors.deepOrange), home: RandomWords()); } } class RandomWords extends StatefulWidget { @override RandomWordsState createState() => RandomWordsState(); } class RandomWordsState extends State<RandomWords> { final _randomWordsPairs = <WordPair>[]; Widget _buildList() { return ListView.builder( padding: const EdgeInsets.all(8), itemBuilder: (BuildContext context, int item) { if (item.isOdd) return Divider(); final index = item ~/ 2; if (index >= _randomWordsPairs.length) { _randomWordsPairs.addAll(generateWordPairs().take(10)); } return _buildRow(_randomWordsPairs[index]); }, ); } Widget _buildRow(WordPair pair) { return ListTile( title: Text(pair.asPascalCase), ); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Wordpair Generator'), ), body: _buildList()); } }
0
mirrored_repositories/flutter-words-pair
mirrored_repositories/flutter-words-pair/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:wordpair_generator/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/theseus-navigator
mirrored_repositories/theseus-navigator/lib/theseus_navigator.dart
library theseus_navigator; export 'src/destination.dart'; export 'src/destination_parser.dart'; export 'src/exceptions.dart'; export 'src/navigation_scheme.dart'; export 'src/navigation_controller.dart'; export 'src/redirection.dart'; export 'src/widgets/index.dart';
0
mirrored_repositories/theseus-navigator/lib
mirrored_repositories/theseus-navigator/lib/src/navigation_controller.dart
import 'dart:collection'; import 'dart:math'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'destination.dart'; import 'exceptions.dart'; import 'utils/utils.dart'; import 'widgets/index.dart'; /// A [NavigationController] manages the navigation state. /// /// Using the given [destinations] list, it maintains the navigation [stack]. /// /// The navigation stack is updated when a user navigates to specified destination /// by calling [goTo] method, or returns back with [goBack] method. /// /// The navigation controller (navigator) provides an access to a [currentDestination], /// which is one on the top of the stack. /// /// Initially, the navigation stack contains a destination at [initialDestinationIndex] /// in the provided list of destinations. /// /// [NavigationController] implements [ChangeNotifier] and notifies its listener when /// the [currentDestination]/[stack] is changed, or some error was happened. /// /// See also: /// - [Destination] /// - [NavigationScheme] /// - [NavigationControllerError] /// class NavigationController with ChangeNotifier { /// Creates navigation controller instance. /// /// Adds initial destination to the navigation stack. /// NavigationController({ required this.destinations, this.builder = const DefaultNavigatorBuilder(), this.initialDestinationIndex = 0, this.notifyOnError = true, this.tag = '', }) { _stack.add(destinations[max( destinations.indexWhere((element) => element.isHome), initialDestinationIndex)]); } /// List of destinations, which this navigator operate of. /// final List<Destination> destinations; /// An implementation of [NavigatorBuilder] which creates a navigation UI. /// /// Defaults to [DefaultNavigatorBuilder] which uses Flutter's [Navigator] widget /// to represent the stack of destinations. /// /// Also the following implementations are available: /// - [BottomNavigationBuilder] allows to switch destination using Flutter's /// [BottomNavigationBar] widget. /// - [DrawerNavigationBuilder] uses drawer menu to navigate top-level destinations. /// - [TabsNavigationBuilder] uses [TabBar] with [TabBarView] widgets to switch destinations. /// /// You can implement your custom wrapper by extending the [NavigatorBuilder] class. /// /// See also: /// - [NavigatorBuilder] /// - [DefaultNavigatorBuilder] /// - [BottomNavigationBuilder] /// - [DrawerNavigationBuilder] /// - [TabsNavigationBuilder] /// final NavigatorBuilder builder; /// Index of the initial destination. /// /// Initial destination will be added to the navigation [stack] on creation the /// navigator. If it is omitted, the first destination in the [destinations] list /// will be used as initial one. /// final int initialDestinationIndex; /// Whether to notify listeners on errors in navigation actions. /// /// Defaults to true. Basically the [NavigationScheme] handles the errors. /// When set to false, the exception will be thrown on errors instead of notifying listeners. /// final bool notifyOnError; /// An identifier of this navigator. /// /// It is used in the debug logs to identify entries related to this navigator. /// final String? tag; Destination? _backFrom; /// The destination from [goBack] action is performed. /// /// It is set to current destination right before [goBack] action is processed. /// Otherwise it is set to null. /// Destination? get backFrom => _backFrom; NavigationControllerError? _error; /// Error details /// NavigationControllerError? get error => _error; /// Whether an error was happened on last [goTo] or [goBack] action. /// bool get hasError => _error != null; /// Indicates if persisting of navigation state in destination parameters is needed. /// /// When it is *true*, the following is happened on navigation to a destination: /// - If [DestinationSettings.reset] is not set in the requested destination, /// the current navigation state is saved in the requested destination parameters. /// Particularly, the [currentDestination] is saved in the [DestinationParameters.upwardParameterName] /// parameter, and current destination of each nested [NavigationController] /// is saved in the [DestinationParameters.nestedParameterName] parameter of the requested destination. /// - If [DestinationSettings.reset] is *true*, the navigation state is restored /// from the requested destination parameters. /// bool get keepStateInParameters => builder.keepStateInParameters == KeepingStateInParameters.always || builder.keepStateInParameters == KeepingStateInParameters.auto && kIsWeb; bool _shouldClose = false; /// Whether the navigator should close. /// /// It is set to 'true' when user call [goBack] method when the only destination /// is in the stack. /// /// If this is the root navigator in the [NavigationScheme], setting [shouldClose] /// to true will cause closing the app. /// bool get shouldClose => _shouldClose; final _stack = Queue<Destination>(); String get _tag => '$runtimeType::$tag'; /// The current destination of the navigator. /// /// It is the topmost destination in the navigation [stack]. /// Destination get currentDestination => _stack.last; /// The navigation [stack]. /// /// When [goTo] method is called, the destination is placed on the top of the stack, /// and when [goBack] method is called, the topmost destination is removed from /// the stack. /// List<Destination> get stack => _stack.toList(); /// Builds a widget that wraps destinations of the navigator. /// Widget build(BuildContext context) { return builder.build(context, this); } /// Opens specified destination. /// /// By calling calling this method, depending on [destination.settings], /// the given destination will be either added to the top of the navigation [stack], /// or will replace the topmost destination in the stack. /// /// Also, missing upward destinations can be added to the stack, if the /// current stack state doesn't match, and the [destination.upwardDestinationBuilder] /// is defined. /// /// Throws [UnknownDestinationException] if the navigator's [destinations] /// doesn't contain given destination. /// Future<void> goTo(Destination destination) async { Log.d(_tag, 'goTo(): destination=$destination, reset=${destination.settings.reset}'); _backFrom = null; _error = null; _shouldClose = false; if (currentDestination == destination) { if (!destination.settings.reset) { Log.d(_tag, 'goTo(): The destination is already on top. No action required.'); notifyListeners(); return; } } if (_isDestinationMatched(destination)) { await _updateStack(destination); notifyListeners(); } else { if (notifyOnError) { _error = NavigationControllerError(destination: destination); notifyListeners(); return; } else { throw UnknownDestinationException(destination); } } } /// Closes the current destination. /// /// The topmost destination is removed from the navigation [stack]. /// /// If it is the only destination in the stack, it remains in the stack and /// [shouldClose] flag is set to 'true'. /// void goBack() { _backFrom = currentDestination; if (_stack.length > 1) { _stack.removeLast(); _shouldClose = false; } else { _shouldClose = true; } Log.d(_tag, 'goBack(): destination=${_stack.last}, shouldClose=$_shouldClose'); notifyListeners(); } /// Explicitly set the navigation stack. /// /// The current navigation stack is replaces with the provided [destinations]. /// /// This method doesn't notify listeners on changed made with the navigation stack. /// void resetStack(List<Destination> destinations) { _stack.clear(); for (final destination in destinations) { _stack.add(destination); } } bool _isDestinationMatched(Destination destination) => destinations.any((element) => element.isMatch(destination.uri)); Future<void> _updateStack(Destination destination) async { if (destination.settings.reset) { _stack.clear(); } else { if (destination.settings.transitionMethod == TransitionMethod.replace) { _stack.removeLast(); } } final upwardStack = await _buildUpwardStack(destination); if (upwardStack.isNotEmpty) { // Find first missing item of upward stack int startUpwardFrom = 0; for (int i = 0; i < upwardStack.length; i++) { if (_stack.isNotEmpty && _stack.last == upwardStack[i]) { startUpwardFrom = i + 1; } } // Add all missing upward destinations to the stack if (startUpwardFrom < upwardStack.length) { for (int i = startUpwardFrom; i < upwardStack.length; i++) { _stack.addLast(upwardStack[i]); } } } _stack.addLast(destination); } Future<List<Destination>> _buildUpwardStack(Destination destination) async { final result = <Destination>[]; var upwardDestination = await destination.upwardDestination; while (upwardDestination != null) { result.insert(0, upwardDestination); upwardDestination = await upwardDestination.upwardDestination; } return result; } } /// Automatic persisting of navigation state. /// /// Once persisting of navigation state in destination parameters is enabled, /// the current stack will be serialized and saved in the [DestinationParameters.stateParameterName] /// parameter on navigation to a destination. /// When the destination with persisted navigation state is requested by the platform, /// the navigation stack will be deserialized from the parameter and explicitly set in the /// navigation controller. /// /// Basically, persisting of navigation state in destination parameters make sense in web apps, /// to be able to restore arbitrary navigation stack when the user navigates to a destination /// through the browser history or a deeplink. /// To support this, the [auto] option is used in [NavigatorBuilder] by default. /// /// When automatic persisting of navigation state is disabled, /// you still able to implement your custom logic manually, by providing proper [Destination.upwardDestinationBuilder]. /// enum KeepingStateInParameters { /// The navigation state will be always kept /// always, /// The navigation state will be only kept when the app is running on the Web platform. /// auto, /// The navigation state will not be kept automatically. /// none, } /// Contains navigation error details /// class NavigationControllerError { /// Creates an error object NavigationControllerError({ this.destination, }); /// A destination related to this error /// final Destination? destination; @override String toString() => '$runtimeType: destination=$destination'; }
0
mirrored_repositories/theseus-navigator/lib
mirrored_repositories/theseus-navigator/lib/src/navigation_scheme.dart
import 'dart:async'; import 'dart:convert'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'destination.dart'; import 'exceptions.dart'; import 'navigation_controller.dart'; import 'router_delegate.dart'; import 'route_parser.dart'; import 'utils/utils.dart'; /// Defines a navigation scheme of the app. /// /// Contains a list of possible [destinations] to navigate in the app. /// Each destination can be a final, i.e. is directly rendered as a some screen, /// or might include a nested navigator with its own destinations. /// /// Until the custom [navigator] is provided, the NavigatorScheme creates a default /// root navigator, that manages top level destinations. /// /// In case of some navigation error, user will be redirected to [errorDestination], /// if it is specified. Otherwise an exception will be thrown. /// /// See also: /// - [Destination] /// - [NavigationController] /// class NavigationScheme with ChangeNotifier { /// Creates navigation scheme. /// NavigationScheme({ List<Destination> destinations = const <Destination>[], this.errorDestination, this.waitingOverlayBuilder, NavigationController? navigator, }) : assert( (destinations.isEmpty ? navigator!.destinations : destinations) .any((destination) => destination.isHome), 'One of destinations must be a home destination.'), assert( errorDestination == null || navigator == null || (navigator.destinations .any((destination) => destination == errorDestination)), 'When "errorDestination" and custom "navigator" are specified, you must include the "errorDestination" to the "navigator"s destinations') { _rootNavigator = navigator ?? NavigationController( destinations: <Destination>[ ...destinations, if (errorDestination != null) errorDestination!, ], tag: 'Root', ); _routerDelegate = TheseusRouterDelegate(navigationScheme: this); _routeParser = TheseusRouteInformationParser(navigationScheme: this); _routeInformationProvider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation( uri: Uri.parse( WidgetsBinding.instance.platformDispatcher.defaultRouteName), ), ); _config = RouterConfig( routerDelegate: _routerDelegate, routeInformationParser: _routeParser, routeInformationProvider: _routeInformationProvider, backButtonDispatcher: RootBackButtonDispatcher(), ); _currentDestination = _rootNavigator.currentDestination; _initializeNavigator(_rootNavigator); _updateCurrentDestination(backFrom: null); } /// The destination to redirect in case of error. /// final Destination? errorDestination; /// Returns a widget to display while destination is resolving. /// /// Resolving the destination might be asynchronous, for example, because of parsing typed /// parameters or checking redirection conditions. /// /// In these cases this function is used to build a widget, which would be displayed /// until the current destination is resolved. /// final Widget Function(BuildContext context, Destination destination)? waitingOverlayBuilder; late final RouterConfig<Destination> _config; bool _isInitializing = true; /// Indicates if the [NavigationScheme] object is initializing. /// bool get isInitializing => _isInitializing; /// A configuration for [Router] widget. /// /// Provides custom [TheseusRouterDelegate] and [TheseusRouteInformationParser], /// which implements Theseus Navigator functionality. /// RouterConfig<Destination> get config => _config; late Destination _currentDestination; /// The current destination within the whole navigation scheme. /// /// To get a current top level destination, use [rootNavigator.currentDestination]. /// Destination get currentDestination => _currentDestination; bool _isResolving = false; /// Indicates if a current destination is in resolving state. /// /// This flag is turned on during performing of the redirection validations, or /// parsing of typed parameters. /// bool get isResolving => _isResolving; final _navigatorListeners = <NavigationController, VoidCallback?>{}; // A map of destinations and navigators which they belongs to // final _navigatorMatches = <Destination, NavigationController>{}; // A map of navigators and transit destinations which own them // final _navigatorOwners = <NavigationController, Destination>{}; final _destinationCompleters = <Destination, Completer<void>>{}; late final NavigationController _rootNavigator; /// The root navigator in the navigation scheme. /// /// This navigator manages top level destinations. /// NavigationController get rootNavigator => _rootNavigator; late final TheseusRouterDelegate _routerDelegate; /// Reference to the RouterDelegate implementation /// TheseusRouterDelegate get routerDelegate => _routerDelegate; late final TheseusRouteInformationParser _routeParser; /// Reference to the RouteInformationParser implementation /// TheseusRouteInformationParser get routeParser => _routeParser; late final RouteInformationProvider _routeInformationProvider; RouteInformationProvider get routeInformationProvider => _routeInformationProvider; /// Stores the original destination in case of redirection. /// Destination? get redirectedFrom => _currentDestination.settings.redirectedFrom; bool _shouldClose = false; /// Whether the app should close. /// /// This flag is set on when user perform 'Back' action on top most destination. /// bool get shouldClose => _shouldClose; @override void dispose() { _routerDelegate.dispose(); _removeNavigatorListeners(); super.dispose(); } /// Find a destination in the scheme that match a given URI. /// /// Returns 'null' if no destination matching the URI was found. /// Destination? findDestination(String uri) => _navigatorMatches.keys .firstWhereOrNull((destination) => destination.isMatch(uri)); /// Returns a proper navigator in the navigation scheme for a given destination. /// /// Returns 'null' if no navigator found. /// NavigationController? findNavigator(Destination destination) => _navigatorMatches[findDestination(destination.path)]; /// Navigates to specified [destination]. /// /// First, searches the navigation scheme for proper navigator for the destination. /// If found, uses the navigator's [goTo] method to navigate to the destination. /// Otherwise throws [UnknownDestinationException]. /// Future<void> goTo(Destination destination) async { if (currentDestination == destination) { Log.d(runtimeType, 'goTo(): Ignore navigation to $destination. It is already the current destination.'); return; } final navigator = findNavigator(destination); if (navigator == null) { _handleError(destination); return SynchronousFuture(null); } Log.d(runtimeType, 'goTo(): navigator=${navigator.tag}, destination=$destination, redirectedFrom=${destination.settings.redirectedFrom}, currentDestination=$currentDestination'); _shouldClose = false; final completer = Completer<void>(); _setupCompleter(destination, completer); if (navigator.keepStateInParameters && navigator.stack.isNotEmpty && navigator.currentDestination != destination && destination.settings.reset && _hasStateInParameters(destination)) { Log.d(runtimeType, 'goTo(): Restore navigation state'); _restoreStateFromParameters(destination, navigator); } else { navigator.goTo(destination); } return completer.future; } /// Return to previous destination. /// /// In case when the current destination was reached with [TransitionMethod.replace] by a redirection, /// this method will navigate to original destination. /// /// Otherwise, the current destination will be removed from the navigation stack of the /// current navigation controller, and the next destination in the stack will become the current one. /// /// If the current destination is the only one in the stack of its navigation controller, /// this will try to return back in the parent navigation controller, which eventually /// might cause request of closing the app by setting the [shouldClose] flag. /// Future<void> goBack() async { if (currentDestination.settings.redirectedFrom != null && currentDestination.settings.transitionMethod == TransitionMethod.replace) { return goTo(currentDestination.settings.redirectedFrom!); } final navigator = findNavigator(_currentDestination); if (navigator == null) { _handleError(_currentDestination); return; } navigator.goBack(); } /// Resolves the current destination /// /// Applies redirection validations to the current destination. /// While validations are performed, the [isResolving] flag is set to true. /// This allows to display a widget returned by [waitingOverlayBuilder] /// until the destination is resolved. /// /// In case of validations are not passed, redirects to corresponding redirection destination. /// Future<void> resolve() async { Log.d(runtimeType, 'resolve(): currentDestination=$_currentDestination'); Timer isResolvingTimer = Timer( const Duration(milliseconds: 500), () { if (!_isResolving) { _isResolving = true; notifyListeners(); } }, ); final destinationsToComplete = <Destination>{}; final navigator = findNavigator(_currentDestination); if (navigator == null) { _handleError(_currentDestination); return SynchronousFuture(null); } if (navigator.keepStateInParameters && (!_currentDestination.settings.reset || !_hasStateInParameters(_currentDestination))) { Log.d(runtimeType, 'resolve(): Save navigation state'); destinationsToComplete.add(_currentDestination); _currentDestination = await _saveStateInParameters(_currentDestination); } final requestedDestination = _currentDestination; destinationsToComplete.add(requestedDestination); final resolvedDestination = await _resolveDestination(requestedDestination); isResolvingTimer.cancel(); Log.d(runtimeType, 'resolve(): requestedDestination=$requestedDestination, resolvedDestination=$resolvedDestination, currentDestination=$_currentDestination'); if (requestedDestination != _currentDestination) { _isResolving = false; notifyListeners(); return; } if (resolvedDestination == requestedDestination) { _isResolving = false; for (var destination in destinationsToComplete) { _completeResolvedDestination(destination); } if (_isInitializing) { _isInitializing = false; } else { notifyListeners(); } return; } goTo(resolvedDestination.withSettings(resolvedDestination.settings .copyWith(redirectedFrom: requestedDestination))); } void _initializeNavigator(NavigationController navigator) { void listener() => _onNavigatorStateChanged(navigator); // Add a listener of the navigator _navigatorListeners[navigator] = listener; navigator.addListener(listener); for (var destination in navigator.destinations) { _navigatorMatches[destination] = navigator; if (!destination.isFinalDestination) { // Set navigation owner _navigatorOwners[destination.navigator!] = destination; // Initialize nested navigator _initializeNavigator(destination.navigator!); } } } void _handleError(Destination? destination) { if (errorDestination != null) { goTo((errorDestination!).withSettings( errorDestination!.settings.copyWith(redirectedFrom: destination))); } else { throw UnknownDestinationException(destination); } } void _onNavigatorStateChanged(NavigationController navigator) { Log.d(runtimeType, 'onNavigatorStateChanged(): navigator=${navigator.tag}, error=${navigator.error}, backFrom=${navigator.backFrom}, shouldClose=${navigator.shouldClose}'); if (navigator.hasError) { _handleError(navigator.error!.destination); } final owner = _navigatorOwners[navigator]; if (owner != null) { Log.d(runtimeType, 'onNavigatorStateChanged(): owner=$owner'); if (navigator.backFrom != null) { if (navigator.shouldClose) { final parentNavigator = findNavigator(owner); if (parentNavigator == null) { _handleError(owner); return; } parentNavigator.goBack(); } else { _updateCurrentDestination(backFrom: navigator.backFrom); } } else { if (navigator.currentDestination.settings.reset) { goTo(owner.withSettings(owner.settings.copyWith(reset: true))); } else { goTo(owner); } } } else { _updateCurrentDestination(backFrom: navigator.backFrom); } } void _removeNavigatorListeners() { for (var navigator in _navigatorListeners.keys) { navigator.removeListener(_navigatorListeners[navigator]!); } } void _setupCompleter(Destination destination, Completer completer) { var destinationToComplete = destination; _destinationCompleters[destinationToComplete] = completer; // Setup the same completer for nested destinations, // if they don't have their own non-completed ones while (!destinationToComplete.isFinalDestination) { destinationToComplete = destinationToComplete.navigator!.currentDestination; if (_destinationCompleters[destinationToComplete]?.isCompleted ?? true) { _destinationCompleters[destinationToComplete] = completer; } } } void _updateCurrentDestination({ required Destination? backFrom, }) { // TODO: Probably '_shouldClose' variable is not needed, we can use '_rootNavigator' directly _shouldClose = _rootNavigator.shouldClose; if (_shouldClose) { Log.d(runtimeType, 'updateCurrentDestination(): currentDestination=$_currentDestination, shouldClose=$_shouldClose'); notifyListeners(); return; } Destination newDestination = _rootNavigator.currentDestination; while (!newDestination.isFinalDestination) { newDestination = newDestination.navigator!.currentDestination; } Log.d(runtimeType, 'updateCurrentDestination(): currentDestination=$_currentDestination, newDestination=$newDestination'); if (_currentDestination != newDestination || _isInitializing || newDestination.settings.reset) { _currentDestination = newDestination; if (_currentDestination == backFrom?.settings.redirectedFrom) { notifyListeners(); return; } resolve(); } } // Persisting navigation state in parameters Future<Destination> _saveStateInParameters(Destination destination) async { Future<List<String>> getCleanUris(List<Destination> stack) async { final result = <String>[]; for (final destination in stack.where( (destination) => destination.settings.redirectedFrom == null)) { result.add((await _removeStateFromParameters(destination)).uri); } return result; } final stateMap = <String, List<String>>{ '/': await getCleanUris(_rootNavigator.stack), }; for (final navigator in _navigatorOwners.keys) { if (navigator.keepStateInParameters) { stateMap[_navigatorOwners[navigator]!.path] = await getCleanUris(navigator.stack); } } final parametersWithState = await destination.parser .parametersFromMap(destination.parameters?.map ?? <String, String>{}); final encodedState = base64.encode(jsonEncode(stateMap).codeUnits); parametersWithState.map.addAll(<String, String>{ DestinationParameters.stateParameterName: encodedState, }); return destination.withParameters(parametersWithState); } bool _hasStateInParameters(Destination destination) => destination.parameters?.map .containsKey(DestinationParameters.stateParameterName) ?? false; Future<Destination> _removeStateFromParameters( Destination destination) async => destination.withParameters(await destination.parser.parametersFromMap( (Map.from(destination.parameters?.map ?? const <String, String>{})) ..remove(DestinationParameters.stateParameterName))); Future<void> _restoreStateFromParameters( Destination destination, NavigationController navigator) async { final encodedState = destination.parameters?.map[DestinationParameters.stateParameterName]; if (encodedState == null) { navigator.goTo(destination); return; } final stateMap = jsonDecode(String.fromCharCodes(base64.decode(encodedState))); for (final key in stateMap.keys) { final eventualNavigator = key == '/' ? _rootNavigator : (await _routeParser .parseRouteInformation(RouteInformation(uri: Uri.parse(key)))) .navigator!; final destinations = <Destination>[]; for (final uri in stateMap[key]) { destinations.add(await _routeParser .parseRouteInformation(RouteInformation(uri: Uri.parse(uri)))); } eventualNavigator.resetStack(destinations); } _updateCurrentDestination(backFrom: null); } // Resolving destination Future<Destination> _resolveDestination(Destination destination) async { // Check redirections that are defined for given destination for (var redirection in destination.redirections) { if (!(await redirection.validate(destination))) { return await _resolveDestination( await redirection.resolve(destination)); } } // In case of nested destination, validate the owner final navigator = findNavigator(destination); if (navigator == null) { throw UnknownDestinationException(destination); } final owner = _navigatorOwners[navigator]; if (owner == null) { return destination; } final resolvedOwner = await _resolveDestination(owner); return owner != resolvedOwner ? resolvedOwner : destination; } void _completeResolvedDestination(Destination destination) { Destination? destinationToComplete = destination; while (destinationToComplete != null) { if (!(_destinationCompleters[destinationToComplete]?.isCompleted ?? true)) { _destinationCompleters[destinationToComplete]?.complete(); } destinationToComplete = destinationToComplete.settings.redirectedFrom; } final owner = _navigatorOwners[findNavigator(destination)]; if (owner != null && (!(_destinationCompleters[owner]?.isCompleted ?? true))) { _destinationCompleters[owner]?.complete(); } } }
0
mirrored_repositories/theseus-navigator/lib
mirrored_repositories/theseus-navigator/lib/src/exceptions.dart
import 'destination.dart'; /// Is thrown when the URI string does not match the destination. /// class DestinationNotMatchException implements Exception { /// Creates exception object. /// DestinationNotMatchException(this.uri, this.destination); /// Source URI string. String uri; /// A destination to match the URI. Destination destination; } /// Is thrown when the navigation scheme or the navigator does not contain the destination. /// class UnknownDestinationException implements Exception { /// Creates exception object. /// UnknownDestinationException([this.destination]); /// A destination that is not found in the navigation scheme. Destination? destination; } /// Is thrown when no destination found in the navigation scheme for given URI. /// class UnknownUriException implements Exception { /// Creates exception object. /// UnknownUriException(this.uri); /// A URI string. String uri; }
0
mirrored_repositories/theseus-navigator/lib
mirrored_repositories/theseus-navigator/lib/src/redirection.dart
import 'destination.dart'; import 'utils/log/log.dart'; /// Defines a redirection. /// /// Uses [validator] function to determine if it is allowed to navigate to the /// given destination. /// If it is not, user will be redirected to either a provided fixed [destination], /// or to a destination returned by [resolver] function. /// /// You can extend this class and override its [validate] and [resolve] methods /// to implement more complex logic of redirection. /// /// See also: /// - [NavigationScheme] /// - [Destination] /// class Redirection { /// Creates a redirection. /// const Redirection({ this.destination, this.resolver, this.validator, }) : assert(destination != null || resolver != null, 'Either "destination" or "resolver" must be specified.'); /// Destination to redirect. /// final Destination? destination; /// Identifies a destination to redirect. /// /// Implements a logic of dynamic resolving a destination for redirection. /// /// Consider to use fixed [destination] instead of this function, if dynamic /// resolving is not needed. /// final Future<Destination> Function(Destination destination)? resolver; /// Validates a destination. /// /// Must return true if it is allowed to navigate to the destination. /// Otherwise returns false. /// /// If validation could be performed synchronously consider return result with /// [SynchronousFuture]. /// final Future<bool> Function(Destination destination)? validator; /// Validates the destination. /// /// [NavigationScheme] uses this method to check if it is needed to redirect to /// another destination. /// Future<bool> validate(Destination destination) async { final result = await validator?.call(destination) ?? false; Log.d(runtimeType, 'validate(): $result'); return result; } /// Destination to redirect /// /// Return either a fixed [destination], or call [resolver] to evaluate a destiantion /// to redirect. /// Future<Destination> resolve(Destination destination) async { final result = this.destination ?? (await resolver!.call(destination)); Log.d(runtimeType, 'resolve(): $result'); return result; } }
0
mirrored_repositories/theseus-navigator/lib
mirrored_repositories/theseus-navigator/lib/src/route_parser.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:theseus_navigator/src/navigation_controller.dart'; import 'destination.dart'; import 'exceptions.dart'; import 'navigation_scheme.dart'; import 'utils/utils.dart'; /// Implementation of [RouteInformationParser]. /// /// Uses [navigationScheme] to get access to route's information. /// /// See also: /// - [NavigationScheme] /// - [NavigationController] /// - [Destination] /// class TheseusRouteInformationParser extends RouteInformationParser<Destination> { /// Creates a route information parser. /// TheseusRouteInformationParser({ required this.navigationScheme, }); /// A navigation scheme that contains destinations to parse. /// final NavigationScheme navigationScheme; @override Future<Destination> parseRouteInformation( RouteInformation routeInformation) async { final uri = routeInformation.uri.toString(); Log.d(runtimeType, 'parseRouteInformation(): uri=$uri'); final matchedDestination = navigationScheme.findDestination(uri); if (matchedDestination == null) { if (navigationScheme.errorDestination != null) { return SynchronousFuture(navigationScheme.errorDestination!); } else { throw UnknownUriException(uri); } } try { final result = await matchedDestination.parse(uri); Log.d(runtimeType, 'parseRouteInformation(): destination=$result'); return result; } catch (error) { if (navigationScheme.errorDestination != null) { return SynchronousFuture(navigationScheme.errorDestination!); } else { throw UnknownUriException(uri); } } } @override // ignore: avoid_renaming_method_parameters RouteInformation? restoreRouteInformation(Destination destination) { if (!destination.settings.updateHistory) { Log.d(runtimeType, 'restoreRouteInformation(): Would not restore route information for ${destination.uri}'); return null; } final uri = Uri.parse(Uri.decodeComponent(destination.uri)); Log.d(runtimeType, 'restoreRouteInformation(): $uri'); return RouteInformation(uri: uri); } }
0
mirrored_repositories/theseus-navigator/lib
mirrored_repositories/theseus-navigator/lib/src/destination_parser.dart
import 'package:flutter/foundation.dart'; import 'destination.dart'; import 'exceptions.dart'; /// A base destination parser. /// /// [DestinationParser] is used to parse the destination object from the /// given URI string, and to generate the URI for the destination. /// /// When subclassed, the certain type of destination parameters must be provided. /// /// There are two methods, that must be implemented in the specific parser: /// [parametersFromMap] and [parametersToMap]. /// /// If typed parameters are not required, the [DefaultDestinationParser] is used. /// /// See also: /// - [Destination] /// - [DestinationParameters] /// - [DefaultDestinationParameters] /// - [DefaultDestinationParser] /// abstract class DestinationParser<T extends DestinationParameters> { /// Creates destination parser. /// const DestinationParser(); /// Creates a destination parameters object of type [T] from the given map. /// /// The key of the map entry is a parameter name, and the value is serialized /// parameter's value. /// This method is used by [parseParameters()] to generate the destination object /// from the given URI string. /// Future<T> parametersFromMap(Map<String, String> map); /// Converts destination [parameters] object of type [T] to a map. /// /// The key of the map entry is a parameter name, and the value is serialized /// parameter's value. /// This method is used by [uri()] to generate the destination's URI string. /// Map<String, String> parametersToMap(T parameters); /// Checks if the [destination] matches the [uri]. /// /// The destination does match when its [path] structure (URI segments number /// and values, including path parameters) matches given [uri] string. /// bool isMatch(String uri, Destination<T> destination) { if ((uri == '/' || uri.isEmpty)) { return destination.isHome; } final destinationUri = Uri.parse(destination.path); final sourceUri = Uri.parse(uri); final destinationSegments = destinationUri.pathSegments; final sourceSegments = sourceUri.pathSegments; if (destinationSegments.length < sourceSegments.length) { return false; } final lengthDifference = destinationSegments.length - sourceSegments.length; if (lengthDifference > 1 || lengthDifference == 1 && !isPathParameter(destinationSegments.last)) { return false; } for (var i = 0; i < destinationSegments.length - lengthDifference; i++) { if (destinationSegments[i] != sourceSegments[i] && !isPathParameter(destinationSegments[i])) { return false; } } return true; } /// Check if the path segment string is a valid path parameter placeholder. /// /// The default path parameter format is '{parameterName}'. /// bool isPathParameter(String pathSegment) { return pathSegment.startsWith('{') && pathSegment.endsWith('}'); } /// Extract parameter name from the path segment string. /// /// See [isPathParameter] for default path parameter format. /// String parsePathParameterName(String pathSegment) { if (!isPathParameter(pathSegment)) { // TODO: Implement custom exception throw Exception('$pathSegment is not a valid path parameter'); } return pathSegment.substring(1, pathSegment.length - 1); } /// Parses parameter values from the specified URI for matched destination. /// /// Returns the copy of [matchedDestination] with actual parameter values parsed from the [uri]. /// Uses [parametersFromMap] implementation to create parameters object of /// type [T]. /// /// Also it ensures that raw parameters value in [DestinationParameters.map] are valid. /// /// Throws [DestinationNotMatchException] if the URI does mot match the destination. /// Future<Destination<T>> parseParameters( String uri, Destination<T> matchedDestination) async { // TODO: Is this check really needed here? if (!isMatch(uri, matchedDestination)) { throw DestinationNotMatchException(uri, matchedDestination); } final parsedUri = Uri.parse(uri); final parametersMap = <String, String>{} ..addAll(_parsePathParameters(parsedUri, matchedDestination)) ..addAll(parsedUri.queryParameters); final T parameters = await parametersFromMap(parametersMap); final rawParameters = parametersToMap(parameters); parameters ..map.clear() ..map.addAll(rawParameters) ..map.addAll(_extractReservedParameters(parametersMap)); return matchedDestination.withParameters(parameters); } /// Returns URI string for the destination /// /// The [Destination.path] is used for building the URI path segment. /// The URI query segment is built using [Destination.parameters] converted /// by [parametersToMap] implementation from the [Destination.parser]. /// String uri(Destination destination) { late final Map<String, String> parametersMap; if (destination.parameters == null) { parametersMap = const <String, String>{}; } else { parametersMap = destination.parser .parametersToMap(destination.parameters!) ..addAll(_extractReservedParameters( destination.parameters?.map ?? const <String, String>{})); } final pathParameters = _getPathParameters(destination.path, parametersMap); final queryParameters = _getQueryParameters(pathParameters, parametersMap); final path = _fillPathParameters(destination.path, pathParameters); final result = Uri( path: path, queryParameters: queryParameters.isNotEmpty ? queryParameters : null, ); return result.toString(); } Map<String, String> _parsePathParameters( Uri uri, Destination<T> baseDestination) { final result = <String, String>{}; final baseDestinationUri = Uri.parse(baseDestination.path); for (int i = 0; i < uri.pathSegments.length; i++) { final pathSegment = uri.pathSegments[i]; final baseDestinationPathSegment = baseDestinationUri.pathSegments[i]; if (isPathParameter(baseDestinationPathSegment)) { final parameterName = parsePathParameterName(baseDestinationPathSegment); result[parameterName] = pathSegment; } } return result; } Map<String, String> _getPathParameters( String path, Map<String, String> parameters) { final result = <String, String>{}; final pathUri = Uri.parse(path); for (var pathSegment in pathUri.pathSegments) { if (isPathParameter(pathSegment)) { final parameterName = parsePathParameterName(pathSegment); final value = parameters[parameterName]; if (value != null) { result[parameterName] = value; } } } return result; } Map<String, String> _getQueryParameters( Map<String, String> pathParameters, Map<String, String> parameters) { final result = <String, String>{}; for (MapEntry entry in parameters.entries) { if (pathParameters.keys.contains(entry.key)) { continue; } result[entry.key] = entry.value; } return result; } Map<String, String> _extractReservedParameters( Map<String, String> parameters) => Map.fromEntries(parameters.entries.where( (entry) => DestinationParameters.isReservedParameter(entry.key))); String _fillPathParameters(String path, Map<String, String> parameters) { final pathUri = Uri.parse(path); final filledPathSegments = <String>[]; for (var pathSegment in pathUri.pathSegments) { if (isPathParameter(pathSegment)) { final parameterName = parsePathParameterName(pathSegment); final value = parameters[parameterName]; if (value != null) { filledPathSegments.add(value); } else { if (pathUri.pathSegments.last != pathSegment) { filledPathSegments.add(pathSegment); } } } else { filledPathSegments.add(pathSegment); } } final result = Uri(pathSegments: filledPathSegments).toString(); return '${path.startsWith('/') ? "/" : ""}$result'; } } /// A default implementation of [DestinationParser]. /// class DefaultDestinationParser extends DestinationParser<DestinationParameters> { /// Creates default destination parser. /// const DefaultDestinationParser() : super(); @override Future<DestinationParameters> parametersFromMap(Map<String, String> map) => SynchronousFuture(DestinationParameters(map)); @override Map<String, String> parametersToMap(DestinationParameters parameters) => Map.of(parameters.map); }
0
mirrored_repositories/theseus-navigator/lib
mirrored_repositories/theseus-navigator/lib/src/destination.dart
import 'package:flutter/widgets.dart'; import 'destination_parser.dart'; import 'navigation_controller.dart'; import 'redirection.dart'; /// A class that contains all required information about navigation target. /// /// The destination is identified by its [path]. Optionally, [parameters] can be provided. /// Either content [builder] or nested [navigator] must be provided for the destination. /// /// The navigator uses a destination's [settings] to determine a way of changing /// the navigation stack, apply transition animations and other aspects of updating /// the navigation state. /// /// The [parser] is used to parse destination from the URI and generate a URI string /// for the destination. /// /// Optional [upwardDestinationBuilder] builder function can be used to implement custom /// logic of upward navigation from the current destination. /// /// If [redirections] are specified, they will be applied on navigation to this destination. /// /// See also: /// - [DestinationSettings] /// - [DestinationParameters] /// - [DestinationParser] /// - [Redirection] /// class Destination<T extends DestinationParameters> { /// Creates a destination. /// Destination({ required this.path, this.builder, this.isHome = false, this.navigator, this.parameters, this.parser = const DefaultDestinationParser(), this.redirections = const <Redirection>[], DestinationSettings? settings, this.tag, this.upwardDestinationBuilder, }) : assert(navigator != null || builder != null, 'Either "builder" or "navigator" must be specified.'), assert( (navigator != null && builder == null) || (builder != null && navigator == null), 'If the "navigator" is provided, the "builder" must be null, or vice versa.'), assert( ((T == DestinationParameters) && (parser is DefaultDestinationParser)) || ((T != DestinationParameters) && parser is! DefaultDestinationParser), 'Custom "parser" must be provided when using the parameters of type $T, but ${parser.runtimeType} was provided.') { this.settings = settings ?? const DestinationSettings.material(); _transitBuilder = null; } /// Creates a destination that provides a navigator with nested destinations. /// /// An optional [builder] parameter is basically the same like normal [Destination.builder], /// but has additional [childBuilder] parameter, which provides the nested content that built by [navigator]. /// The implementation of [builder] function must include this child widget sub-tree /// in the result for correct displaying the nested content. /// Destination.transit({ required this.path, required this.navigator, Widget Function( BuildContext context, T? parameters, WidgetBuilder childBuilder)? builder, this.isHome = false, this.redirections = const <Redirection>[], DestinationSettings? settings, this.tag, }) : builder = null, parameters = null, parser = const DefaultDestinationParser(), settings = settings ?? const DestinationSettings.material(), upwardDestinationBuilder = null, _transitBuilder = builder; /// Path identifies the destination. /// /// Usually it follows the common url pattern with optional parameters. /// Example: `/catalog/{id}` /// final String path; /// A content builder. /// /// Returns a widget (basically a screen) that should be rendered for this destination. /// final Widget Function(BuildContext context, T? parameters)? builder; /// Whether the destination is the home destination. /// /// The home destination matches the '/' or empty path, beside of its specific [path]. /// final bool isHome; /// A child navigator. /// /// Allows to implement nested navigation. When specified, the parent navigator /// uses this child navigator to build content for this destination. /// final NavigationController? navigator; /// Parameters of the destination. /// /// If the type *T* is not specified for the destination, then default [DestinationParameters] /// type is used. /// final T? parameters; /// A destination parser. /// /// Used to parse the certain destination object from the URI string, based on /// the current destination, and to generate a URI string from the current destination. /// final DestinationParser parser; /// Destinations and conditions to redirect. /// /// When it is not empty, the navigator will check for each [Redirection] in the list, /// if this destination is allowed to navigate to. /// final List<Redirection> redirections; /// Defines a way of how this destination will appear. /// late final DestinationSettings settings; /// An optional label to identify a destination. /// /// It will be the same for all destinations of the kind, regardless actual /// values of destination parameters. /// final String? tag; /// Function that returns an underlay destination. /// /// A [NavigationController] uses this method to create the underlay destination for the /// current one, using its parameters. /// final Future<Destination?> Function(Destination<T> destination)? upwardDestinationBuilder; late final Widget Function( BuildContext context, T? parameters, WidgetBuilder childBuilder)? _transitBuilder; /// Whether this destination is final, i.e. it builds a content /// /// Final destinations must have a [builder] function provided. /// Non-final destinations must have a [navigator], that manages its own destinations. /// bool get isFinalDestination => navigator == null; /// Return a destination that should be displayed on reverse navigation. /// Future<Destination?> get upwardDestination async => upwardDestinationBuilder?.call(this); /// A full URI of the destination, with parameters placeholders replaced with /// actual parameter values. /// String get uri => parser.uri(this); /// Return a widget that display destination's content. /// /// If the destination is final, then [builder] is called to build the content. /// /// Otherwise [navigator.build] is called to build nested navigator's content. /// In case the destination was created by [Destination.transit] constructor, /// and [builder] parameter was specified, the nested content is also wrapped in /// the widget sub-tree returned by that builder. /// Widget build(BuildContext context) { if (isFinalDestination) { return builder!(context, parameters); } else { if (_transitBuilder != null) { return _transitBuilder!(context, parameters, (nestedContext) => navigator!.build(nestedContext)); } else { return navigator!.build(context); } } } /// Check if the destination matches the provided URI string /// bool isMatch(String uri) => parser.isMatch(uri, this); /// Parses the destination from the provided URI string. /// /// Returns a copy of the current destination with updated parameters, parsed /// from the URI. /// If the URI doesn't match this destination, throws an [DestinationNotMatchException]. /// Future<Destination<T>> parse(String uri) => parser.parseParameters(uri, this) as Future<Destination<T>>; /// Returns a copy of this destination with a different settings. /// Destination<T> withSettings(DestinationSettings settings) => copyWith( settings: settings, ); /// Returns a copy of this destination with different parameters. /// /// For typed parameters ensures that raw parameter values in [DestinationParameters.map] /// are updated as well. /// Destination<T> withParameters(T parameters) { final rawParameters = parser.parametersToMap(parameters); return copyWith( parameters: parameters..map.addAll(rawParameters), ); } /// Creates a copy of this destination with the given fields replaced /// with the new values. /// Destination<T> copyWith({ T? parameters, DestinationSettings? settings, Future<Destination?> Function(Destination<T> destination)? upwardDestinationBuilder, }) => this._transitBuilder == null ? Destination<T>( path: path, builder: builder, isHome: isHome, navigator: navigator, parameters: parameters ?? this.parameters, parser: parser, redirections: redirections, settings: settings ?? this.settings, tag: tag, upwardDestinationBuilder: upwardDestinationBuilder ?? this.upwardDestinationBuilder, ) : Destination<T>.transit( path: path, navigator: navigator, builder: this._transitBuilder, isHome: isHome, redirections: redirections, settings: settings ?? this.settings, tag: tag, ); /// Destinations are equal when their URI string are equal. /// @override bool operator ==(Object other) => identical(this, other) || other is Destination && runtimeType == other.runtimeType && uri == other.uri; @override int get hashCode => uri.hashCode; @override String toString() => uri; } /// Encapsulates the settings attributes which are applied when the navigation state /// is updated with the the destination. /// /// There are convenient factory constructors for commonly used settings. /// [material] - pushes the destination to the navigation stack with standard material animations. /// [dialog] - display the destination like a dialog /// [quiet] - replace the previous destination with the current one without animations. /// /// See also: /// - [TransitionMethod] /// - [DestinationTransition] /// class DestinationSettings { /// Creates an instance of [DestinationSettings]. /// const DestinationSettings({ required this.transitionMethod, required this.transition, this.redirectedFrom, this.reset = false, this.transitionBuilder, this.updateHistory = true, }) : assert( (transition == DestinationTransition.custom && transitionBuilder != null) || (transition != DestinationTransition.custom), 'You have to provide "transitionBuilder" for "custom" transition.'); /// Creates a settings to push a destination to the top of navigation /// stack with a standard Material animations. /// const factory DestinationSettings.material() = _DefaultDestinationSettings; /// Creates a settings to displays a destination as a modal dialog. /// const factory DestinationSettings.dialog() = _DialogDestinationSettings; /// Creates a settings to replaces the current destination with a new one /// with no animations. /// const factory DestinationSettings.quiet() = _QuietDestinationSettings; /// How the destination will update the navigation stack. /// /// See also: /// - [TransitionMethod] /// final TransitionMethod transitionMethod; /// Visual effects that would be applied on updating the stack with the destination. /// /// See also: /// - [DestinationTransition] /// final DestinationTransition transition; /// In case of redirection, contains a destination from which the redirection /// was performed. /// final Destination? redirectedFrom; /// Whether the stack would be cleared before adding the destination. /// final bool reset; /// Function that build custom destination transitions. /// /// It is required when the [transition] value is [DestinationTransition.custom]. /// /// See also /// - [RouteTransitionBuilder] /// final RouteTransitionsBuilder? transitionBuilder; /// Controls if the destination will be added to the navigation history. /// /// Currently it only affects to web applications. When set to *true*, which is /// default, the url in the web browser address field will be updated with the [Destination.uri]. /// final bool updateHistory; /// Creates a copy of this settings with the given fields replaced /// with the new values. /// DestinationSettings copyWith({ // TODO: Add other properties TransitionMethod? transitionMethod, Destination? redirectedFrom, bool? reset, bool? updateHistory, }) => DestinationSettings( transitionMethod: transitionMethod ?? this.transitionMethod, transition: transition, redirectedFrom: redirectedFrom ?? this.redirectedFrom, reset: reset ?? this.reset, transitionBuilder: transitionBuilder, updateHistory: updateHistory ?? this.updateHistory, ); } class _DefaultDestinationSettings extends DestinationSettings { const _DefaultDestinationSettings() : super( transitionMethod: TransitionMethod.push, transition: DestinationTransition.material, ); } class _DialogDestinationSettings extends DestinationSettings { const _DialogDestinationSettings() : super( transitionMethod: TransitionMethod.push, transition: DestinationTransition.materialDialog, ); } class _QuietDestinationSettings extends DestinationSettings { const _QuietDestinationSettings() : super( transitionMethod: TransitionMethod.replace, transition: DestinationTransition.none, ); } /// A way of transition to the destination. /// enum TransitionMethod { /// The destination will be added to the navigation stack. /// On navigation back, the destination will be removed from the stack /// and previous destination will be restored. /// push, /// The previous destination will be removed from the navigation stack, /// and the current destination will be added. /// This means that user will not be able to return to previous destination /// by back navigation. /// replace, } /// Defines transition animations from the previous destination to the current one. /// enum DestinationTransition { /// Standard Material animations. /// material, /// Destination appears as a dialog with Material transitions and modal barrier. /// materialDialog, /// Custom animations. /// custom, /// No animations. /// none, } /// Base destination parameters. /// /// Extend this class to define your custom parameters class. /// Use [Destination<YourCustomDestinationParameters>()] to make a destination /// aware of your custom parameters. /// /// For custom parameters you also must implement [YouCustomDestinationParser<YourCustomDestinationParameters>] /// with [toDestinationParameters()] ans [toMap()] methods, like this: /// ``` dart /// class YourCustomDestinationParser /// extends DestinationParser<YourCustomDestinationParameters> { /// const YourCustomDestinationParser() : super(); /// /// @override /// YourCustomDestinationParameters toDestinationParameters( /// Map<String, String> map) { /// //... /// } /// /// @override /// Map<String, String> toMap(YourCustomDestinationParameters parameters) { /// //... /// } /// } /// ``` /// /// See also: /// - [DestinationParser] /// class DestinationParameters { /// Creates a [DestinationParameters] instance. /// DestinationParameters([Map<String, String>? map]) : map = map ?? <String, String>{}; /// Reserved query parameter name. /// /// It is used for automatic persisting of navigation state. /// Do not use this name for your custom parameters. /// static const String stateParameterName = 'state'; static const _reservedParameterNames = <String>{ stateParameterName, }; /// Contains parameter values parsed from the destination's URI. /// /// The parameter name is a [MapEntry.key], and the value is [MapEntry.value]. /// late final Map<String, String> map; /// Check if a provided parameter name is reserved /// /// This function is used by [DestinationParser] to synchronize internal raw parameter /// values with parsed parameter object properties and build destination URI. /// static bool isReservedParameter(String parameterName) => _reservedParameterNames.contains(parameterName); }
0
mirrored_repositories/theseus-navigator/lib
mirrored_repositories/theseus-navigator/lib/src/router_delegate.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'destination.dart'; import 'navigation_controller.dart'; import 'navigation_scheme.dart'; import 'utils/utils.dart'; /// Implementation of [RouterDelegate]. /// /// Uses [navigationScheme] to build routes. /// /// See also: /// - [NavigationScheme] /// - [NavigationController] /// - [Destination] /// class TheseusRouterDelegate extends RouterDelegate<Destination> with ChangeNotifier { /// Creates router delegate. /// TheseusRouterDelegate({ required this.navigationScheme, }) { Log.d(runtimeType, 'TheseusRouterDelegate():'); navigationScheme.addListener(_onCurrentDestinationChanged); } /// A navigation scheme that contains destinations and navigators. /// /// This router delegate is listening the navigation scheme to identify if the /// current destination is changed, and in turn, notifies its listeners when this /// happens. /// final NavigationScheme navigationScheme; @override Widget build(BuildContext context) { Log.d(runtimeType, 'build(): isResolving=${navigationScheme.isResolving}'); return Navigator( key: const ValueKey('TheseusNavigator'), pages: [ MaterialPage( key: const ValueKey('TheseusRootPage'), child: navigationScheme.rootNavigator.build(context), ), if (navigationScheme.isResolving) _TheseusPageOverlay( child: navigationScheme.waitingOverlayBuilder ?.call(context, navigationScheme.currentDestination) ?? const _TheseusWaitingOverlay( key: Key('_TheseusWaitingOverlay_'), ), ), ], onPopPage: (route, result) { Log.d(runtimeType, 'onPopPage()'); return route.didPop(result); }, ); } @override Future<bool> popRoute() async { Log.d(runtimeType, 'popRoute():'); navigationScheme.goBack(); if (navigationScheme.shouldClose) { if (Platform.isAndroid) { return false; } else { navigationScheme.goTo(navigationScheme.currentDestination); return true; } } return true; } @override // ignore: avoid_renaming_method_parameters Future<void> setInitialRoutePath(destination) async { Log.d(runtimeType, 'setInitialRoutePath(): destination=$destination'); return navigationScheme.goTo( destination.withSettings(destination.settings.copyWith(reset: true))); } @override // ignore: avoid_renaming_method_parameters Future<void> setNewRoutePath(destination) async { if (destination == navigationScheme.currentDestination || destination == navigationScheme.findNavigator(destination)?.currentDestination) { Log.d(runtimeType, 'setNewRoutePath(): Ignore navigation to $destination. It is already the current destination.'); return SynchronousFuture(null); } Log.d(runtimeType, 'setNewRoutePath(): destination=$destination'); // The current navigation stack is reset if the new destination is not an error. final reset = destination != navigationScheme.errorDestination; return navigationScheme.goTo( destination.withSettings(destination.settings.copyWith(reset: reset))); } @override Destination? get currentConfiguration => navigationScheme.isInitializing ? null : navigationScheme.currentDestination; @override void dispose() { navigationScheme.removeListener(_onCurrentDestinationChanged); super.dispose(); } Future<void> _onCurrentDestinationChanged() async { final destination = navigationScheme.currentDestination; Log.d( runtimeType, 'onCurrentDestinationChanged(): destination=$destination'); // Ignore closing app request here. It is processed in the 'popRoute()' method. if (navigationScheme.shouldClose) { Log.d(runtimeType, 'onCurrentDestinationChanged(): Closing the app was requested.'); return; } notifyListeners(); } } class _TheseusPageOverlay extends Page { const _TheseusPageOverlay({ required this.child, LocalKey? key, }) : super(key: key); final Widget child; @override Route createRoute(BuildContext context) { return PageRouteBuilder( settings: this, opaque: false, pageBuilder: (context, animation, secondaryAnimation) => child, transitionsBuilder: (context, animation, secondaryAnimation, child) => child, ); } } class _TheseusWaitingOverlay extends StatelessWidget { const _TheseusWaitingOverlay({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Stack( children: [ ModalBarrier( color: Colors.black.withAlpha(128), dismissible: false, ), const Center( child: CircularProgressIndicator(), ), ], ); } }
0
mirrored_repositories/theseus-navigator/lib/src
mirrored_repositories/theseus-navigator/lib/src/widgets/drawer_navigation_builder.dart
import 'package:flutter/material.dart'; import '../navigation_controller.dart'; import 'index.dart'; /// A [NavigatorBuilder] that allows to switch between destinations using /// [Drawer]. /// /// It builds a wrapper widget, which is a [Scaffold] with a [Scaffold.body] set /// to the current destination's content, and [Scaffold.drawer] specified. /// /// The [drawerItems] must correspond to the navigator's destinations. /// /// The drawer can be customized using [parameters], which includes /// all parameters supported by the [Drawer] widget. /// /// See also: /// - [NavigatorBuilder] /// - [DrawerParameters] /// - [NavigationController] /// - [Drawer] /// class DrawerNavigationBuilder extends NavigatorBuilder { /// Creates a [DrawerNavigationBuilder] instance. /// const DrawerNavigationBuilder({ required this.drawerItems, this.header, this.parameters, }) : super(); /// A list of [DrawerItems], that corresponds to the navigator's /// destination list. /// /// The list must contain the same number of drawer items, /// following with the same order as a destination list specified for the navigator. /// final List<DrawerItem> drawerItems; /// Optional header, that is shown at the top of drawer. /// final Widget? header; /// A set of [Drawer`] parameters. /// /// Contains all supported parameters to customize [Drawer] widget. /// Doesn't include 'child', which is managed by [DrawerNavigationBuilder]. /// final DrawerParameters? parameters; @override Widget build(BuildContext context, NavigationController navigator) { final currentDestination = navigator.currentDestination; final content = currentDestination.build(context); return _DrawerWrapper( content: content, items: drawerItems, header: header, parameters: parameters, onSelectItem: (index) => navigator.goTo(navigator.destinations[index]), selectedIndex: navigator.destinations.indexOf(currentDestination), ); } } class _DrawerWrapper extends StatefulWidget { const _DrawerWrapper({ Key? key, required this.content, required this.items, required this.onSelectItem, required this.selectedIndex, this.header, this.parameters, }) : super(key: key); final Widget content; final List<DrawerItem> items; final void Function(int) onSelectItem; final int selectedIndex; final Widget? header; final DrawerParameters? parameters; @override _DrawerWrapperState createState() => _DrawerWrapperState(); } class _DrawerWrapperState extends State<_DrawerWrapper> { late final OverlayEntry _mainOverlay; @override void initState() { super.initState(); _mainOverlay = OverlayEntry( builder: (context) => Row( children: [ Drawer( backgroundColor: widget.parameters?.backgroundColor, elevation: widget.parameters?.elevation, shape: widget.parameters?.shape, width: widget.parameters?.width, semanticLabel: widget.parameters?.semanticLabel, child: ListView( padding: EdgeInsets.zero, children: [ if (widget.header != null) widget.header!, ...widget.items .map((item) => ListTile( leading: item.leading, title: Text(item.title ?? ''), selected: widget.selectedIndex == widget.items.indexOf(item), selectedColor: widget.parameters?.selectedColor, selectedTileColor: widget.parameters?.selectedTileColor, onTap: () => widget.onSelectItem(widget.items.indexOf(item)), )) .toList(), ], )), Expanded( child: Scaffold( body: widget.content, ), ), ], ), ); } @override void didUpdateWidget(_DrawerWrapper oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.selectedIndex != widget.selectedIndex) { _mainOverlay.markNeedsBuild(); } } @override Widget build(BuildContext context) { return Overlay( initialEntries: [ _mainOverlay, ], ); } } /// A model of drawer item. /// /// The data provided in the model is used to create a [ListTile] widget, which /// represents the drawer list item. /// class DrawerItem { /// Creates an instance of [DrawerItem]. /// const DrawerItem({ this.leading, this.title, }); /// A leading widget in the drawer item. /// /// Usually it is an icon, but could be any widget. /// final Widget? leading; /// An item's title. /// final String? title; } /// Contains parameters to customize the [Drawer]. /// /// It includes all the same arguments as the [Drawer()], excepting /// the 'child', which is managed by the [DrawerNavigationBuilder]. /// /// In addition it includes some parameters of [ListTile()] that are used to style /// selected drawer item. /// /// See also: /// - [DrawerNavigationBuilder] /// - [Drawer] /// - [ListTile] /// class DrawerParameters { /// Create a [DrawerParameters] instance. /// const DrawerParameters({ this.backgroundColor, this.elevation, this.shape, this.width, this.semanticLabel, this.selectedColor, this.selectedTileColor, }); /// [Drawer.backgroundColor] /// final Color? backgroundColor; /// [Drawer.elevation] /// final double? elevation; /// [Drawer.shape] /// final ShapeBorder? shape; /// [Drawer.width] /// final double? width; /// [Drawer.semanticLabel] /// final String? semanticLabel; /// [ListTile.selectedColor] /// final Color? selectedColor; /// [ListTile.selectedTileColor] /// final Color? selectedTileColor; }
0
mirrored_repositories/theseus-navigator/lib/src
mirrored_repositories/theseus-navigator/lib/src/widgets/index.dart
export 'bottom_navigation_builder.dart'; export 'drawer_navigation_builder.dart'; export 'navigator_builder.dart'; export 'tabs_navigation_builder.dart';
0
mirrored_repositories/theseus-navigator/lib/src
mirrored_repositories/theseus-navigator/lib/src/widgets/tabs_navigation_builder.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../destination.dart'; import '../navigation_controller.dart'; import 'index.dart'; /// A [NavigatorBuilder] that allows to switch between destinations using /// [TabBar]. /// /// It builds a wrapper widget, which is a [Scaffold] with a [Scaffold.appbar] set /// to the [TabBar] with provided [tabs], and a [Scaffold.body] set to the [TabBarView], /// which display a content of corresponding destination. /// /// The [tabs] must correspond to the navigator's destinations. /// /// The tab bar can be customized using [parameters], which includes all parameters /// supported by the [TabBar] widget. /// /// See also: /// - [NavigatorBuilder] /// - [AppBarParameters] /// - [TabBarParameters] /// - [NavigationController] /// - [TabBar] /// class TabsNavigationBuilder extends NavigatorBuilder { /// Creates a [TabsNavigationBuilder] instance. /// const TabsNavigationBuilder({ required this.tabs, this.parameters = const TabBarParameters(), this.appBarParametersBuilder, this.wrapInScaffold = true, }) : super(); /// Typically a list of [Tab] widgets, that corresponds to the navigator's /// destination list. /// /// The list must contain the same number of widgets, following with the same order /// as a destination list specified for the navigator. /// final List<Widget> tabs; /// A set of [TabBar] parameters. /// /// Contains all supported parameters to customize [TabBar] widget. /// Doesn't include 'tabs', 'onTap' and 'controller', which are managed by /// [TabsNavigationBuilder]. /// final TabBarParameters parameters; /// Return an instance of [AppBarParameters] for provided destination. /// /// Once this builder is specified, the navigation [TabBar] will appear as part of /// [AppBar] widget. /// When this function is called, the [destination] parameter is set to current /// destination (selected tab). /// /// The function should return an instance of [AppBarParameters], /// which is a set of all parameters available in the [AppBar] widget. /// So the app bar widget con be made to match the current destination. /// For example, you can set a title and actions, depending on the current destination. /// final AppBarParameters Function( BuildContext context, Destination destination)? appBarParametersBuilder; /// Controls if the [Scaffold] widget should be used around the tab bar and tab's content. /// /// This might be needed if you are using tabs as a top level navigation in your app. /// Defaults to 'true'. /// final bool wrapInScaffold; @override Widget build(BuildContext context, NavigationController navigator) { final currentDestination = navigator.currentDestination; return _TabsNavigationWrapper( tabs: tabs, // TODO: This implementation doesn't respect the possible parameters of destinations (excluding current destination). // How this could be resolved? tabDestination: (tabIndex) => navigator.destinations[tabIndex], onTabSelected: (index) => navigator.goTo(navigator.destinations[index]), selectedIndex: navigator.destinations.indexOf(currentDestination), parameters: parameters, appBarParameters: appBarParametersBuilder?.call(context, currentDestination), wrapInScaffold: wrapInScaffold, ); } } class _TabsNavigationWrapper extends StatefulWidget { const _TabsNavigationWrapper({ Key? key, required this.tabs, required this.tabDestination, required this.onTabSelected, required this.selectedIndex, required this.parameters, this.appBarParameters, this.wrapInScaffold = false, }) : super(key: key); final List<Widget> tabs; final Destination Function(int tabIndex) tabDestination; final void Function(int index) onTabSelected; final int selectedIndex; final TabBarParameters parameters; final AppBarParameters? appBarParameters; final bool wrapInScaffold; @override _TabsNavigationWrapperState createState() => _TabsNavigationWrapperState(); } class _TabsNavigationWrapperState extends State<_TabsNavigationWrapper> with TickerProviderStateMixin { final _content = <Widget>[]; late final TabController _controller; @override void initState() { super.initState(); _content.addAll(List<Widget>.generate( widget.tabs.length, (index) => _TabDestinationContentWrapper( keepState: widget.tabDestination(index).isFinalDestination, child: widget.tabDestination(index).build(context), ))); _controller = TabController(length: widget.tabs.length, vsync: this); _controller.addListener(_onTabChanged); _controller.animateTo(widget.selectedIndex); } @override void didUpdateWidget(_TabsNavigationWrapper oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.selectedIndex != widget.selectedIndex) { _controller.animateTo(widget.selectedIndex); } } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final tabBar = TabBar( controller: _controller, tabs: widget.tabs, onTap: (value) => widget.onTabSelected(value), isScrollable: widget.parameters.isScrollable, padding: widget.parameters.padding, indicatorColor: widget.parameters.indicatorColor, automaticIndicatorColorAdjustment: widget.parameters.automaticIndicatorColorAdjustment, indicatorWeight: widget.parameters.indicatorWeight, indicatorPadding: widget.parameters.indicatorPadding, indicator: widget.parameters.indicator, indicatorSize: widget.parameters.indicatorSize, labelColor: widget.parameters.labelColor, labelStyle: widget.parameters.labelStyle, labelPadding: widget.parameters.labelPadding, unselectedLabelColor: widget.parameters.unselectedLabelColor, unselectedLabelStyle: widget.parameters.unselectedLabelStyle, dragStartBehavior: widget.parameters.dragStartBehavior, overlayColor: widget.parameters.overlayColor, mouseCursor: widget.parameters.mouseCursor, enableFeedback: widget.parameters.enableFeedback, physics: widget.parameters.physics, splashFactory: widget.parameters.splashFactory, splashBorderRadius: widget.parameters.splashBorderRadius, ); final tabBarView = TabBarView( controller: _controller, children: _content, ); Widget result; if (widget.appBarParameters != null) { final appBar = AppBar( bottom: tabBar, leading: widget.appBarParameters?.leading, automaticallyImplyLeading: widget.appBarParameters?.automaticallyImplyLeading ?? true, title: widget.appBarParameters?.title, actions: widget.appBarParameters?.actions, flexibleSpace: widget.appBarParameters?.flexibleSpace, elevation: widget.appBarParameters?.elevation, scrolledUnderElevation: widget.appBarParameters?.scrolledUnderElevation, shadowColor: widget.appBarParameters?.shadowColor, surfaceTintColor: widget.appBarParameters?.surfaceTintColor, shape: widget.appBarParameters?.shape, backgroundColor: widget.appBarParameters?.backgroundColor, foregroundColor: widget.appBarParameters?.foregroundColor, iconTheme: widget.appBarParameters?.iconTheme, actionsIconTheme: widget.appBarParameters?.actionsIconTheme, primary: widget.appBarParameters?.primary ?? true, centerTitle: widget.appBarParameters?.centerTitle, excludeHeaderSemantics: widget.appBarParameters?.excludeHeaderSemantics ?? false, titleSpacing: widget.appBarParameters?.titleSpacing, toolbarOpacity: widget.appBarParameters?.toolbarOpacity ?? 1.0, bottomOpacity: widget.appBarParameters?.bottomOpacity ?? 1.0, toolbarHeight: widget.appBarParameters?.toolbarHeight, leadingWidth: widget.appBarParameters?.leadingWidth, toolbarTextStyle: widget.appBarParameters?.toolbarTextStyle, titleTextStyle: widget.appBarParameters?.titleTextStyle, systemOverlayStyle: widget.appBarParameters?.systemOverlayStyle, ); if (widget.wrapInScaffold) { result = Scaffold( appBar: appBar, body: tabBarView, ); } else { result = Column( children: [ appBar, Expanded( child: tabBarView, ), ], ); } } else { result = Column( children: [ tabBar, Expanded( child: tabBarView, ), ], ); if (widget.wrapInScaffold) { result = Scaffold( body: result, ); } } return result; } void _onTabChanged() { widget.onTabSelected(_controller.index); } } class _TabDestinationContentWrapper extends StatefulWidget { const _TabDestinationContentWrapper({ Key? key, required this.keepState, required this.child, }) : super(key: key); final bool keepState; final Widget child; @override State<_TabDestinationContentWrapper> createState() => _TabDestinationContentWrapperState(); } class _TabDestinationContentWrapperState extends State<_TabDestinationContentWrapper> with AutomaticKeepAliveClientMixin<_TabDestinationContentWrapper> { @override bool get wantKeepAlive => widget.keepState; @override Widget build(BuildContext context) { super.build(context); return widget.child; } } /// Contains parameters to customize the [TabBar]. /// /// It includes all the same arguments as the [TabBar()], excepting /// the 'tabs', 'onTap' and 'controller', which are managed by the [TabsNavigationBuilder]. /// /// See also: /// - [TabsNavigationBuilder] /// - [TabBar] /// class TabBarParameters { /// Create a [TabBarParameters] instance. /// const TabBarParameters({ this.isScrollable = false, this.padding, this.indicatorColor, this.automaticIndicatorColorAdjustment = true, this.indicatorWeight = 2.0, this.indicatorPadding = EdgeInsets.zero, this.indicator, this.indicatorSize, this.labelColor, this.labelStyle, this.labelPadding, this.unselectedLabelColor, this.unselectedLabelStyle, this.dragStartBehavior = DragStartBehavior.start, this.overlayColor, this.mouseCursor, this.enableFeedback, this.physics, this.splashFactory, this.splashBorderRadius, }); /// [TabBar.isScrollable] /// final bool isScrollable; /// [TabBar.padding] /// final EdgeInsetsGeometry? padding; /// [TabBar.indicatorColor] /// final Color? indicatorColor; /// [TabBar.automaticIndicatorColorAdjustment] /// final bool automaticIndicatorColorAdjustment; /// [TabBar.indicatorWeight] /// final double indicatorWeight; /// [TabBar.indicatorPadding] /// final EdgeInsetsGeometry indicatorPadding; /// [TabBar.indicator] /// final Decoration? indicator; /// [TabBar.indicatorSize] /// final TabBarIndicatorSize? indicatorSize; /// [TabBar.labelColor] /// final Color? labelColor; /// [TabBar.labelStyle] /// final TextStyle? labelStyle; /// [TabBar.labelPadding] /// final EdgeInsetsGeometry? labelPadding; /// [TabBar.unselectedLabelColor] /// final Color? unselectedLabelColor; /// [TabBar.unselectedLabelStyle] /// final TextStyle? unselectedLabelStyle; /// [TabBar.dragStartBehavior] /// final DragStartBehavior dragStartBehavior; /// [TabBar.overlayColor] /// final MaterialStateProperty<Color?>? overlayColor; /// [TabBar.mouseCursor] /// final MouseCursor? mouseCursor; /// [TabBar.enableFeedback] /// final bool? enableFeedback; /// [TabBar.physics] /// final ScrollPhysics? physics; /// [TabBar.splashFactory] /// final InteractiveInkFeatureFactory? splashFactory; /// [TabBar.splashBorderRadius] /// final BorderRadius? splashBorderRadius; } /// Contains parameters to customize the [AppBar]. /// /// It includes all the same arguments as the [AppBar()], excepting /// the 'bottom' which is managed by the [TabsNavigationBuilder]. /// /// See also: /// - [TabsNavigationBuilder] /// - [AppBar] /// class AppBarParameters { /// Create a [AppBarParameters] instance. /// const AppBarParameters({ this.leading, this.automaticallyImplyLeading = true, this.title, this.actions, this.flexibleSpace, this.elevation, this.scrolledUnderElevation, this.shadowColor, this.surfaceTintColor, this.shape, this.backgroundColor, this.foregroundColor, this.iconTheme, this.actionsIconTheme, this.primary = true, this.centerTitle, this.excludeHeaderSemantics = false, this.titleSpacing, this.toolbarOpacity = 1.0, this.bottomOpacity = 1.0, this.toolbarHeight, this.leadingWidth, this.toolbarTextStyle, this.titleTextStyle, this.systemOverlayStyle, }); /// [AppBar.leading] /// final Widget? leading; /// [AppBar.leading] /// final bool automaticallyImplyLeading; /// [AppBar.title] /// final Widget? title; /// [AppBar.actions] /// final List<Widget>? actions; /// [AppBar.flexibleSpace] /// final Widget? flexibleSpace; /// [AppBar.elevation] /// final double? elevation; /// [AppBar.scrolledUnderElevation] /// final double? scrolledUnderElevation; /// [AppBar.shadowColor] /// final Color? shadowColor; /// [AppBar.surfaceTintColor] /// final Color? surfaceTintColor; /// [AppBar.shape] /// final ShapeBorder? shape; /// [AppBar.backgroundColor] /// final Color? backgroundColor; /// [AppBar.foregroundColor] /// final Color? foregroundColor; /// [AppBar.iconTheme] /// final IconThemeData? iconTheme; /// [AppBar.actionsIconTheme] /// final IconThemeData? actionsIconTheme; /// [AppBar.primary] /// final bool primary; /// [AppBar.centerTitle] /// final bool? centerTitle; /// [AppBar.excludeHeaderSemantics] /// final bool excludeHeaderSemantics; /// [AppBar.titleSpacing] /// final double? titleSpacing; /// [AppBar.toolbarOpacity] /// final double toolbarOpacity; /// [AppBar.bottomOpacity] /// final double bottomOpacity; /// [AppBar.toolbarHeight] /// final double? toolbarHeight; /// [AppBar.leadingWidth] /// final double? leadingWidth; /// [AppBar.toolbarTextStyle] /// final TextStyle? toolbarTextStyle; /// [AppBar.titleTextStyle] /// final TextStyle? titleTextStyle; /// [AppBar.systemOverlayStyle] /// final SystemUiOverlayStyle? systemOverlayStyle; }
0
mirrored_repositories/theseus-navigator/lib/src
mirrored_repositories/theseus-navigator/lib/src/widgets/bottom_navigation_builder.dart
import 'package:flutter/material.dart'; import '../destination.dart'; import '../navigation_controller.dart'; import 'index.dart'; /// A [NavigatorBuilder] that allows to switch between destinations using /// [BottomNavigationBar]. /// /// It builds a wrapper widget, which is a [Scaffold] with a [Scaffold.body] set /// to the current destination's content, and [Scaffold.bottomNavigationBar] /// specified. /// /// The [bottomNavigationItems] must correspond to the navigator's destinations. /// /// The bottom navigation bar can be customized using [parameters], which includes /// all parameters supported by the [BottomNavigationBar] widget. /// /// See also: /// - [NavigatorBuilder] /// - [BottomNavigationBarParameters] /// - [NavigationController] /// - [BottomNavigationBar] /// class BottomNavigationBuilder extends NavigatorBuilder { /// Creates a [BottomNavigationBuilder] instance. /// const BottomNavigationBuilder({ this.bottomNavigationItems = const <BottomNavigationBarItem>[], this.parameters = const BottomNavigationBarParameters(), this.navigationBarItems = const <NavigationDestination>[], this.navigationBarParameters = const NavigationBarParameters(), bool? material3, }) : _material3 = material3 ?? false, super(); /// Creates a [BottomNavigationBuilder] instance that uses Material 3 [NavigationBar] /// widget. /// factory BottomNavigationBuilder.navigationBar({ required List<NavigationDestination> navigationBarItems, NavigationBarParameters? navigationBarParameters, }) => BottomNavigationBuilder( navigationBarItems: navigationBarItems, navigationBarParameters: navigationBarParameters ?? const NavigationBarParameters(), material3: true, ); /// A list of [BottomNavigationBarItems], that corresponds to the navigator's /// destination list. /// /// The list must contain the same number of bottom navigation bar items, /// following with the same order as a destination list specified for the navigator. /// final List<BottomNavigationBarItem> bottomNavigationItems; /// A set of [BottomNavigationBar] parameters. /// /// Contains all supported parameters to customize [BottomNavigationBar] widget. /// Doesn't include 'items', 'onTap' and 'currentIndex', which are managed by /// [BottomNavigationBuilder]. /// final BottomNavigationBarParameters parameters; /// A list of [NavigationDestination] widgets, that corresponds to the navigator's /// destination list. /// /// The list must contain the same number of items, following with the same order /// as a destination list specified in the navigator. /// final List<NavigationDestination> navigationBarItems; /// A set of [NavigationBar] parameters. /// /// Contains all supported parameters to customize [NavigationBar] widget. /// Doesn't include 'items', 'onTap' and 'currentIndex', which are managed by /// [BottomNavigationBuilder]. /// final NavigationBarParameters navigationBarParameters; final bool _material3; @override Widget build(BuildContext context, NavigationController navigator) { final currentDestination = navigator.currentDestination; return _BottomNavigationWrapper( destination: currentDestination, onSelectBottomTab: (index) => navigator.goTo(navigator.destinations[index]), selectedIndex: navigator.destinations.indexOf(currentDestination), items: bottomNavigationItems, parameters: parameters, navigationBarItems: navigationBarItems, navigationBarParameters: navigationBarParameters, material3: _material3, ); } } class _BottomNavigationWrapper extends StatefulWidget { const _BottomNavigationWrapper({ Key? key, required this.destination, required this.onSelectBottomTab, required this.selectedIndex, this.items = const <BottomNavigationBarItem>[], this.parameters = const BottomNavigationBarParameters(), this.navigationBarItems = const <NavigationDestination>[], this.navigationBarParameters = const NavigationBarParameters(), this.material3 = false, }) : super(key: key); final Destination destination; final List<BottomNavigationBarItem> items; final void Function(int) onSelectBottomTab; final int selectedIndex; final BottomNavigationBarParameters parameters; final List<NavigationDestination> navigationBarItems; final NavigationBarParameters navigationBarParameters; final bool material3; @override _BottomNavigationWrapperState createState() => _BottomNavigationWrapperState(); } class _BottomNavigationWrapperState extends State<_BottomNavigationWrapper> { final _content = <Destination, Widget>{}; final _indexes = <Destination, int>{}; late final OverlayEntry _mainOverlay; @override void initState() { super.initState(); _content[widget.destination] = widget.destination.build(context); _indexes[widget.destination] = widget.selectedIndex; _mainOverlay = OverlayEntry( builder: (context) => Scaffold( body: Stack( children: [ ..._content.entries .map((entry) => Offstage( offstage: _indexes[entry.key] != widget.selectedIndex, child: entry.value, )) .toList(), ], ), bottomNavigationBar: widget.material3 ? NavigationBar( animationDuration: widget.navigationBarParameters.animationDuration, selectedIndex: widget.selectedIndex, destinations: widget.navigationBarItems, onDestinationSelected: widget.onSelectBottomTab, backgroundColor: widget.navigationBarParameters.backgroundColor, elevation: widget.navigationBarParameters.elevation, height: widget.navigationBarParameters.height, labelBehavior: widget.navigationBarParameters.labelBehavior, ) : BottomNavigationBar( items: widget.items, currentIndex: widget.selectedIndex, onTap: widget.onSelectBottomTab, elevation: widget.parameters.elevation, type: widget.parameters.type, fixedColor: widget.parameters.fixedColor, backgroundColor: widget.parameters.backgroundColor, iconSize: widget.parameters.iconSize, selectedItemColor: widget.parameters.selectedItemColor, unselectedItemColor: widget.parameters.unselectedItemColor, selectedIconTheme: widget.parameters.selectedIconTheme, unselectedIconTheme: widget.parameters.unselectedIconTheme, selectedFontSize: widget.parameters.selectedFontSize, unselectedFontSize: widget.parameters.unselectedFontSize, selectedLabelStyle: widget.parameters.selectedLabelStyle, unselectedLabelStyle: widget.parameters.unselectedLabelStyle, showSelectedLabels: widget.parameters.showSelectedLabels, showUnselectedLabels: widget.parameters.showUnselectedLabels, mouseCursor: widget.parameters.mouseCursor, enableFeedback: widget.parameters.enableFeedback, landscapeLayout: widget.parameters.landscapeLayout, ), ), ); } @override void didUpdateWidget(_BottomNavigationWrapper oldWidget) { super.didUpdateWidget(oldWidget); bool needsRebuild = false; if (widget.material3 != oldWidget.material3) { needsRebuild = true; } if (!widget.destination.isFinalDestination) { needsRebuild = true; _content[widget.destination] = widget.destination.build(context); _indexes[widget.destination] = widget.selectedIndex; } else if (oldWidget.selectedIndex != widget.selectedIndex && !_content.containsKey(widget.destination)) { needsRebuild = true; _content[widget.destination] = widget.destination.build(context); _indexes[widget.destination] = widget.selectedIndex; } if (needsRebuild) { _mainOverlay.markNeedsBuild(); } } @override Widget build(BuildContext context) { return Overlay( initialEntries: [ _mainOverlay, ], ); } } /// Contains parameters to customize the [BottomNavigationBar]. /// /// It includes all the same arguments as the [BottomNavigationBar()], excepting /// the 'items', 'onTap' and 'currentIndex', which are managed by the [BottomNavigationBuilder]. /// /// See also: /// - [BottomNavigationBuilder] /// - [BottomNavigationBar] /// class BottomNavigationBarParameters { /// Create a [BottomNavigationBarParameters] instance. /// const BottomNavigationBarParameters({ this.elevation, this.type, this.fixedColor, this.backgroundColor, this.iconSize = 24.0, this.selectedItemColor, this.unselectedItemColor, this.selectedIconTheme, this.unselectedIconTheme, this.selectedFontSize = 14.0, this.unselectedFontSize = 12.0, this.selectedLabelStyle, this.unselectedLabelStyle, this.showSelectedLabels, this.showUnselectedLabels, this.mouseCursor, this.enableFeedback, this.landscapeLayout, }); /// [BottomNavigationBar.elevation] /// final double? elevation; /// [BottomNavigationBar.type] /// final BottomNavigationBarType? type; /// [BottomNavigationBar.fixedColor] /// final Color? fixedColor; /// [BottomNavigationBar.backgroundColor] /// final Color? backgroundColor; /// [BottomNavigationBar.iconSize] /// final double iconSize; /// [BottomNavigationBar.selectedItemColor] /// final Color? selectedItemColor; /// [BottomNavigationBar.unselectedItemColor] /// final Color? unselectedItemColor; /// [BottomNavigationBar.selectedIconTheme] /// final IconThemeData? selectedIconTheme; /// [BottomNavigationBar.unselectedIconTheme] /// final IconThemeData? unselectedIconTheme; /// [BottomNavigationBar.selectedLabelStyle] /// final TextStyle? selectedLabelStyle; /// [BottomNavigationBar.unselectedLabelStyle] /// final TextStyle? unselectedLabelStyle; /// [BottomNavigationBar.selectedFontSize] /// final double selectedFontSize; /// [BottomNavigationBar.unselectedFontSize] /// final double unselectedFontSize; /// [BottomNavigationBar.showUnselectedLabels] /// final bool? showUnselectedLabels; /// [BottomNavigationBar.showSelectedLabels] /// final bool? showSelectedLabels; /// [BottomNavigationBar.mouseCursor] /// final MouseCursor? mouseCursor; /// [BottomNavigationBar.enableFeedback] /// final bool? enableFeedback; /// [BottomNavigationBar.landscapeLayout] /// final BottomNavigationBarLandscapeLayout? landscapeLayout; } /// Contains parameters to customize the [NavigationBar]. /// /// It includes all the same arguments as the [NavigationBar()], excepting /// the 'items', 'onTap' and 'currentIndex', which are managed by the [BottomNavigationBuilder]. /// /// See also: /// - [BottomNavigationBuilder] /// - [NavigationBar] /// class NavigationBarParameters { /// Create a [NavigationBarParameters] instance. /// const NavigationBarParameters({ this.animationDuration, this.backgroundColor, this.elevation, this.height, this.labelBehavior, }); /// [NavigationBar.animationDuration] /// final Duration? animationDuration; /// [NavigationBar.backgroundColor] /// final Color? backgroundColor; /// [NavigationBar.elevation] /// final double? elevation; /// [NavigationBar.height] /// final double? height; /// [NavigationBar.labelBehavior] /// final NavigationDestinationLabelBehavior? labelBehavior; }
0