repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/Store-App-UI/lib
|
mirrored_repositories/Store-App-UI/lib/screens/product_details.dart
|
import 'package:card_swiper/card_swiper.dart';
import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/material.dart';
import 'package:small_store_app/constants/color_constants.dart';
class ProductDetails extends StatefulWidget {
const ProductDetails({
Key? key,
}) : super(key: key);
@override
State<ProductDetails> createState() => _ProductDetailsState();
}
class _ProductDetailsState extends State<ProductDetails> {
final titleStyle = const TextStyle(fontSize: 24, fontWeight: FontWeight.bold);
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: 18,
),
const BackButton(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"Category",
style:
TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
),
const SizedBox(
height: 18,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
flex: 3,
child: Text(
"Lorem Ipsum",
textAlign: TextAlign.start,
style: titleStyle,
),
),
Flexible(
flex: 1,
child: RichText(
text: TextSpan(
text: '\$',
style: const TextStyle(
fontSize: 25,
color: Color.fromRGBO(33, 150, 243, 1)),
children: <TextSpan>[
TextSpan(
text: "168.00",
style: TextStyle(
color: lightTextColor,
fontWeight: FontWeight.bold)),
]),
),
),
],
),
const SizedBox(
height: 18,
),
],
),
),
SizedBox(
height: size.height * 0.4,
child: Swiper(
itemBuilder: (BuildContext context, int index) {
return FancyShimmerImage(
width: double.infinity,
imageUrl: "https://placeimg.com/640/480/any",
boxFit: BoxFit.fill,
);
},
autoplay: true,
itemCount: 3,
pagination: const SwiperPagination(
alignment: Alignment.bottomCenter,
builder: DotSwiperPaginationBuilder(
color: Colors.white,
activeColor: Colors.red,
),
),
// control: const SwiperControl(),
),
),
const SizedBox(
height: 18,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Description', style: titleStyle),
const SizedBox(
height: 18,
),
const Text(
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
textAlign: TextAlign.start,
style: TextStyle(fontSize: 25),
),
],
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Store-App-UI
|
mirrored_repositories/Store-App-UI/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:small_store_app/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_todos
|
mirrored_repositories/flutter_todos/lib/constants.dart
|
const kAppTitle = 'flutter_todos';
const kAboutPageUrl = 'http://ithinkdiff.net';
const kAppPortfolioApple =
'https://apps.apple.com/us/developer/ithinkdiff/id377715733';
const kappPortfolioGoogle =
'https://play.google.com/store/apps/developer?id=iThinkdiff';
const kAppTwitterPage = 'https://twitter.com/ithinkdiff_apps';
// AppStore and Google PlayStore URL
const kAppStoreUrl = '';
const kGooglePlayUrl = '';
| 0
|
mirrored_repositories/flutter_todos
|
mirrored_repositories/flutter_todos/lib/main.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
import 'package:flutter_todos/constants.dart';
import 'package:flutter_todos/widgets/header.dart';
import 'package:flutter_todos/widgets/task_input.dart';
import 'package:flutter_todos/widgets/todo.dart';
import 'package:flutter_todos/widgets/done.dart';
import 'package:flutter_todos/model/model.dart' as Model;
import 'package:flutter_todos/model/db_wrapper.dart';
import 'package:flutter_todos/utils/utils.dart';
import 'package:flutter_todos/widgets/popup.dart';
void main() => runApp(TodosApp());
class TodosApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.light().copyWith(
backgroundColor: Color(0xfffff5eb),
),
title: kAppTitle,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String welcomeMsg;
List<Model.Todo> todos;
List<Model.Todo> dones;
//String _selection;
@override
void initState() {
super.initState();
getTodosAndDones();
welcomeMsg = Utils.getWelcomeMessage();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
body: SafeArea(
child: GestureDetector(
onTap: () {
Utils.hideKeyboard(context);
},
child: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
backgroundColor: Theme.of(context).backgroundColor,
floating: true,
flexibleSpace: FlexibleSpaceBar(
background: Column(
children: <Widget>[
Stack(
children: <Widget>[
Column(
children: <Widget>[
Container(
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
Header(
msg: welcomeMsg,
),
Container(
margin: EdgeInsets.only(top: 35),
child: Popup(
getTodosAndDones: getTodosAndDones,
),
),
],
),
),
Container(
margin: EdgeInsets.only(top: 20),
child: TaskInput(
onSubmitted: addTaskInTodo,
), // Add Todos
),
],
),
],
),
],
),
),
expandedHeight: 200,
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
switch (index) {
case 0:
return Todo(
todos: todos,
onTap: markTodoAsDone,
onDeleteTask: deleteTask,
); // Active todos
case 1:
return SizedBox(
height: 30,
);
default:
return Done(
dones: dones,
onTap: markDoneAsTodo,
onDeleteTask: deleteTask,
); // Done todos
}
},
childCount: 3,
),
),
],
),
),
),
);
}
void getTodosAndDones() async {
final _todos = await DBWrapper.sharedInstance.getTodos();
final _dones = await DBWrapper.sharedInstance.getDones();
setState(() {
todos = _todos;
dones = _dones;
});
}
void addTaskInTodo({@required TextEditingController controller}) {
final inputText = controller.text.trim();
if (inputText.length > 0) {
// Add todos
Model.Todo todo = Model.Todo(
title: inputText,
created: DateTime.now(),
updated: DateTime.now(),
status: Model.TodoStatus.active.index,
);
DBWrapper.sharedInstance.addTodo(todo);
getTodosAndDones();
} else {
Utils.hideKeyboard(context);
}
controller.text = '';
}
void markTodoAsDone({@required int pos}) {
DBWrapper.sharedInstance.markTodoAsDone(todos[pos]);
getTodosAndDones();
}
void markDoneAsTodo({@required int pos}) {
DBWrapper.sharedInstance.markDoneAsTodo(dones[pos]);
getTodosAndDones();
}
void deleteTask({@required Model.Todo todo}) {
DBWrapper.sharedInstance.deleteTodo(todo);
getTodosAndDones();
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/widgets/done.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
import 'package:flutter_todos/widgets/shared.dart';
import 'package:flutter_todos/model/model.dart' as Model;
import 'package:flutter_todos/utils/colors.dart';
class Done extends StatefulWidget {
final Function onTap;
final Function onDeleteTask;
final List<Model.Todo> dones;
Done({@required this.dones, this.onTap, this.onDeleteTask});
@override
_DoneState createState() => _DoneState();
}
class _DoneState extends State<Done> {
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Card(
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
color: Color(0xffbcbab8),
child: Column(
children: <Widget>[
SizedBox(
height: 50,
),
if (widget.dones == null || widget.dones.length == 0)
Container(
height: 10,
),
if (widget.dones != null)
for (int i = widget.dones.length - 1; i >= 0; --i)
getTaskItem(
widget.dones[i].title,
index: i,
onTap: () {
widget.onTap(pos: i);
},
),
],
),
),
SharedWidget.getCardHeader(
context: context,
text: 'DONE',
backgroundColorCode: TodosColor.kSecondaryColorCode,
customFontSize: 16),
],
);
}
Widget getTaskItem(String text,
{@required int index, @required Function onTap}) {
final double height = 50.0;
return Container(
child: Column(
children: <Widget>[
Dismissible(
key: Key(text + '$index'),
direction: DismissDirection.endToStart,
onDismissed: (direction) {
widget.onDeleteTask(todo: widget.dones[index]);
},
background: SharedWidget.getOnDismissDeleteBackground(),
child: InkWell(
onTap: onTap,
child: IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 5),
height: height,
child: Icon(
Icons.check,
color: Colors.grey[300],
),
),
Expanded(
child: Container(
padding: EdgeInsets.only(
left: 10, top: 10, right: 20, bottom: 10),
child: Text(
text,
overflow: TextOverflow.clip,
textAlign: TextAlign.justify,
style: Theme.of(context).textTheme.title.copyWith(
color: Colors.grey[300],
decoration: TextDecoration.lineThrough,
),
),
),
),
],
),
),
),
),
SizedBox(
height: 0.5,
child: Container(
color: Colors.white54,
),
),
],
));
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/widgets/popup.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:flutter_todos/model/db_wrapper.dart';
import 'package:flutter_todos/utils/utils.dart';
import 'package:flutter_todos/constants.dart';
class Popup extends StatelessWidget {
Function getTodosAndDones;
Popup({this.getTodosAndDones});
@override
Widget build(BuildContext context) {
String appUrl = Utils.getPlatformSpecificUrl(
iOSUrl: kAppPortfolioApple, androidUrl: kGooglePlayUrl);
String portfolioUrl = Utils.getPlatformSpecificUrl(
iOSUrl: kAppPortfolioApple, androidUrl: kappPortfolioGoogle);
return PopupMenuButton<int>(
elevation: 4,
icon: Icon(Icons.more_vert),
onSelected: (value) {
print('Selected value: $value');
if (value == kMoreOptionsKeys.clearAll.index) {
Utils.showCustomDialog(context,
title: 'Are you sure?',
msg: 'All done todos will be deleted permanently',
onConfirm: () {
DBWrapper.sharedInstance.deleteAllDoneTodos();
getTodosAndDones();
});
} else if (value == kMoreOptionsKeys.moreApps.index) {
Utils.launchURL(portfolioUrl);
} else if (value == kMoreOptionsKeys.about.index) {
Utils.launchURL(kAboutPageUrl);
} else if (value == kMoreOptionsKeys.writeReview.index) {
Utils.launchURL(appUrl);
} else if (value == kMoreOptionsKeys.shareApp.index) {
Share.share('Check out this awesome app ' + appUrl);
} else if (value == kMoreOptionsKeys.followUs.index) {
Utils.launchURL(kAppTwitterPage);
}
},
itemBuilder: (context) {
List list = List<PopupMenuEntry<int>>();
for (int i = 0; i < kMoreOptionsMap.length; ++i) {
list.add(PopupMenuItem(value: i, child: Text(kMoreOptionsMap[i])));
if (i == 0) {
list.add(PopupMenuDivider(
height: 5,
));
}
}
return list;
});
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/widgets/shared.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
import 'package:flutter_todos/utils/colors.dart';
class SharedWidget {
static Widget getCardHeader(
{@required BuildContext context,
@required String text,
Color textColor = Colors.white,
int backgroundColorCode = TodosColor.kPrimaryColorCode,
double customFontSize}) {
customFontSize ??= Theme.of(context).textTheme.title.fontSize;
return Container(
width: 85,
alignment: AlignmentDirectional.center,
margin: EdgeInsets.only(left: 32),
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Color(backgroundColorCode),
),
child: Text(
text,
style: TextStyle(
fontWeight: FontWeight.bold,
color: textColor,
fontSize: customFontSize,
),
),
);
}
static Widget getOnDismissDeleteBackground() {
return Container(
alignment: Alignment.centerRight,
color: Colors.red[300],
padding: EdgeInsets.only(right: 10),
child: Text(
'DELETE',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/widgets/todo.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
import 'package:flutter_todos/widgets/shared.dart';
import 'package:flutter_todos/model/model.dart' as Model;
import 'package:flutter_todos/utils/colors.dart';
const int NoTask = -1;
const int animationMilliseconds = 500;
class Todo extends StatefulWidget {
final Function onTap;
final Function onDeleteTask;
final List<Model.Todo> todos;
Todo({@required this.todos, this.onTap, this.onDeleteTask});
@override
_TodoState createState() => _TodoState();
}
class _TodoState extends State<Todo> {
int taskPosition = NoTask;
bool showCompletedTaskAnimation = false;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Card(
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
color: Colors.white,
child: Column(
children: <Widget>[
SizedBox(
height: 50,
),
if (widget.todos == null || widget.todos.length == 0)
Container(
height: 10,
),
if (widget.todos != null)
for (int i = 0; i < widget.todos.length; ++i)
AnimatedOpacity(
curve: Curves.fastOutSlowIn,
opacity: taskPosition != i
? 1.0
: showCompletedTaskAnimation ? 0 : 1,
duration: Duration(seconds: 1),
child: getTaskItem(
widget.todos[i].title,
index: i,
onTap: () {
setState(() {
taskPosition = i;
showCompletedTaskAnimation = true;
});
Future.delayed(
Duration(milliseconds: animationMilliseconds),
).then((value) {
taskPosition = NoTask;
showCompletedTaskAnimation = false;
widget.onTap(pos: i);
});
},
),
),
],
),
),
SharedWidget.getCardHeader(
context: context, text: 'TO DO', customFontSize: 16),
],
);
}
Widget getTaskItem(String text,
{@required int index, @required Function onTap}) {
final double height = 50.0;
return Container(
child: Column(
children: <Widget>[
Dismissible(
key: Key(text + '$index'),
direction: DismissDirection.endToStart,
onDismissed: (direction) {
widget.onDeleteTask(todo: widget.todos[index]);
},
background: SharedWidget.getOnDismissDeleteBackground(),
child: InkWell(
onTap: onTap,
child: IntrinsicHeight(
child: Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 5),
width: 7,
decoration: BoxDecoration(
color: TodosColor.sharedInstance.leadingTaskColor(index),
),
),
SizedBox(
width: 10,
),
Expanded(
child: Container(
padding: EdgeInsets.only(
left: 10, top: 15, right: 20, bottom: 15),
child: Text(
text,
overflow: TextOverflow.clip,
textAlign: TextAlign.justify,
style: Theme.of(context).textTheme.title.copyWith(
color: Color(0xff373640),
),
),
),
),
],
),
),
),
),
SizedBox(
height: 0.5,
child: Container(
color: Colors.grey,
),
),
],
));
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/widgets/task_input.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
import 'package:flutter_todos/utils/utils.dart';
class TaskInput extends StatefulWidget {
final Function onSubmitted;
TaskInput({@required Function this.onSubmitted});
@override
_TaskInputState createState() => _TaskInputState();
}
class _TaskInputState extends State<TaskInput> {
TextEditingController textEditingController = TextEditingController();
@override
Widget build(BuildContext context) {
return Container(
child: Card(
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
color: Colors.white,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 5),
width: 40,
child: Icon(
Icons.add,
color: Color(0xffca3e47),
size: 30,
),
),
Expanded(
child: TextField(
minLines: 1,
maxLines: 2,
decoration: InputDecoration(
hintText: 'What do you want to do?',
border: InputBorder.none),
textInputAction: TextInputAction.done,
controller: textEditingController,
onEditingComplete: () {
widget.onSubmitted(controller: textEditingController);
},
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/widgets/header.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
class Header extends StatelessWidget {
final String msg;
Header({this.msg});
@override
Widget build(BuildContext context) {
return LimitedBox(
child: Container(
padding: EdgeInsets.only(left: 15.0, top: 30.0),
child: Text(
msg,
style: Theme.of(context)
.textTheme
.headline
.copyWith(fontFamily: 'Lobster Two', fontSize: 30),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/model/db.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_todos/model/model.dart';
const kTodosStatusActive = 0;
const kTodosStatusDone = 1;
const kDatabaseName = 'todos.db';
const kDatabaseVersion = 1;
const kSQLCreateStatement = '''
CREATE TABLE "todos" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" TEXT NOT NULL,
"created" text NOT NULL,
"updated" TEXT NOT NULL,
"status" integer DEFAULT $kTodosStatusActive
);
''';
const kTableTodos = 'todos';
class DB {
DB._();
static final DB sharedInstance = DB._();
Database _database;
Future<Database> get database async {
return _database ?? await initDB();
}
Future<Database> initDB() async {
Directory docsDirectory = await getApplicationDocumentsDirectory();
String path = join(docsDirectory.path, kDatabaseName);
return await openDatabase(path, version: kDatabaseVersion,
onCreate: (Database db, int version) async {
await db.execute(kSQLCreateStatement);
});
}
void createTodo(Todo todo) async {
final db = await database;
await db.insert(kTableTodos, todo.toMapAutoID());
}
void updateTodo(Todo todo) async {
final db = await database;
await db
.update(kTableTodos, todo.toMap(), where: 'id=?', whereArgs: [todo.id]);
}
void deleteTodo(Todo todo) async {
final db = await database;
await db.delete(kTableTodos, where: 'id=?', whereArgs: [todo.id]);
}
void deleteAllTodos({int status = kTodosStatusDone}) async {
final db = await database;
await db.delete(kTableTodos, where: 'status=?', whereArgs: [status]);
}
Future<List<Todo>> retrieveTodos(
{TodoStatus status = TodoStatus.active}) async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.query(kTableTodos,
where: 'status=?', whereArgs: [status.index], orderBy: 'updated ASC');
// Convert List<Map<String, dynamic>> to List<Todo_object>
return List.generate(maps.length, (i) {
return Todo(
id: maps[i]['id'],
title: maps[i]['title'],
created: DateTime.parse(maps[i]['created']),
updated: DateTime.parse(maps[i]['updated']),
status: maps[i]['status'],
);
});
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/model/model.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
enum TodoStatus { active, done }
class Todo {
int id;
String title;
DateTime created;
DateTime updated;
int status;
Todo({this.id, this.title, this.created, this.updated, this.status});
Map<String, dynamic> toMap() {
return {
'id': id,
'title': title,
'created': created.toString(),
'updated': updated.toString(),
'status': status,
};
}
Map<String, dynamic> toMapAutoID() {
return {
'title': title,
'created': created.toString(),
'updated': updated.toString(),
'status': TodoStatus.active.index,
};
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/model/db_wrapper.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter_todos/model/model.dart';
import 'package:flutter_todos/model/db.dart';
class DBWrapper {
static final DBWrapper sharedInstance = DBWrapper._();
DBWrapper._();
Future<List<Todo>> getTodos() async {
List list = await DB.sharedInstance.retrieveTodos();
return list;
}
Future<List<Todo>> getDones() async {
List list = await DB.sharedInstance.retrieveTodos(status: TodoStatus.done);
return list;
}
void addTodo(Todo todo) async {
await DB.sharedInstance.createTodo(todo);
}
void markTodoAsDone(Todo todo) async {
todo.status = TodoStatus.done.index;
todo.updated = DateTime.now();
await DB.sharedInstance.updateTodo(todo);
}
void markDoneAsTodo(Todo todo) async {
todo.status = TodoStatus.active.index;
todo.updated = DateTime.now();
await DB.sharedInstance.updateTodo(todo);
}
void deleteTodo(Todo todo) async {
await DB.sharedInstance.deleteTodo(todo);
}
void deleteAllDoneTodos() async {
await DB.sharedInstance.deleteAllTodos();
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/utils/colors.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
import 'dart:math';
class TodosColor {
static const kPrimaryColorCode = 0xffca3e47;
static const kSecondaryColorCode = 0xff34465d;
static TodosColor sharedInstance = TodosColor._();
List<Color> storedColors;
TodosColor._() {
storedColors = List.generate(100, (pos) {
return Color.fromARGB(0xff - pos * 10, Random().nextInt(255),
Random().nextInt(255), Random().nextInt(255));
});
}
Color leadingTaskColor(int pos) {
switch (pos) {
case 0:
return Colors.red[900];
case 1:
return Colors.green[900];
case 2:
return Colors.blue[900];
}
if (pos < storedColors.length) {
return storedColors[pos];
}
// default case when need more than 100 colors
return Color.fromARGB(0xff - pos * 10, Random().nextInt(255),
Random().nextInt(255), Random().nextInt(255));
}
}
| 0
|
mirrored_repositories/flutter_todos/lib
|
mirrored_repositories/flutter_todos/lib/utils/utils.dart
|
/**
* Created by Mahmud Ahsan
* https://github.com/mahmudahsan
*/
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:flutter_todos/utils/colors.dart';
enum kMoreOptionsKeys {
clearAll,
moreApps,
about,
writeReview,
shareApp,
followUs,
}
Map<int, String> kMoreOptionsMap = {
kMoreOptionsKeys.clearAll.index: 'Clear Done',
kMoreOptionsKeys.moreApps.index: 'More Apps',
kMoreOptionsKeys.about.index: 'About',
kMoreOptionsKeys.writeReview.index: 'Write a Review',
kMoreOptionsKeys.shareApp.index: 'Share',
kMoreOptionsKeys.followUs.index: 'Follow Us',
};
class Utils {
static void hideKeyboard(BuildContext context) {
FocusScope.of(context).requestFocus(new FocusNode());
}
static String getWelcomeMessage() {
final hour = DateTime.now().hour;
String msg;
if (hour < 12) {
msg = 'Good Morning';
} else if (hour < 18) {
msg = 'Good Afternoon';
} else {
msg = 'Good Evening';
}
return msg;
}
static void launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
print('Could not launch $url');
}
}
static String getPlatformSpecificUrl({String iOSUrl, String androidUrl}) {
if (Platform.isIOS) {
return iOSUrl;
} else if (Platform.isAndroid) {
return androidUrl;
}
}
static void showCustomDialog(BuildContext context,
{String title,
String msg,
String noBtnTitle: 'Close',
Function onConfirm,
String confirmBtnTitle: 'Yes'}) {
final dialog = AlertDialog(
title: Text(title),
content: Text(msg),
actions: <Widget>[
if (onConfirm != null)
RaisedButton(
color: Color(TodosColor.kPrimaryColorCode),
onPressed: () {
onConfirm();
Navigator.pop(context);
},
child: Text(
confirmBtnTitle,
style: TextStyle(
color: Colors.white,
),
),
),
RaisedButton(
color: Color(TodosColor.kSecondaryColorCode),
onPressed: () {
Navigator.pop(context);
},
child: Text(
noBtnTitle,
style: TextStyle(
color: Colors.white,
),
),
),
],
);
showDialog(context: context, builder: (x) => dialog);
}
}
| 0
|
mirrored_repositories/flutter_todos
|
mirrored_repositories/flutter_todos/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_todos/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(TodosApp());
// 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-file-upload
|
mirrored_repositories/flutter-file-upload/lib/main.dart
|
import 'dart:io';
import 'package:dotted_border/dotted_border.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:iconsax/iconsax.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: 'File Upload',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
Key? key,
}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
with SingleTickerProviderStateMixin {
final String _image =
'https://ouch-cdn2.icons8.com/84zU-uvFboh65geJMR5XIHCaNkx-BZ2TahEpE9TpVJM/rs:fit:784:784/czM6Ly9pY29uczgu/b3VjaC1wcm9kLmFz/c2V0cy9wbmcvODU5/L2E1MDk1MmUyLTg1/ZTMtNGU3OC1hYzlh/LWU2NDVmMWRiMjY0/OS5wbmc.png';
late AnimationController loadingController;
File? _file;
PlatformFile? _platformFile;
selectFile() async {
final file = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['png', 'jpg', 'jpeg']
);
if (file != null) {
setState(() {
_file = File(file.files.single.path!);
_platformFile = file.files.first;
});
}
loadingController.forward();
}
@override
void initState() {
loadingController = AnimationController(
vsync: this,
duration: const Duration(seconds: 10),
)..addListener(() { setState(() {}); });
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
const SizedBox(
height: 100,
),
Image.network(
_image,
width: 300,
),
const SizedBox(
height: 50,
),
Text(
'Upload your file',
style: TextStyle(
fontSize: 25,
color: Colors.grey.shade800,
fontWeight: FontWeight.bold),
),
const SizedBox(
height: 10,
),
Text(
'File should be jpg, png',
style: TextStyle(fontSize: 15, color: Colors.grey.shade500),
),
const SizedBox(
height: 20,
),
GestureDetector(
onTap: selectFile,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0, vertical: 20.0),
child: DottedBorder(
borderType: BorderType.RRect,
radius: const Radius.circular(10),
dashPattern: const [10, 4],
strokeCap: StrokeCap.round,
color: Colors.blue.shade400,
child: Container(
width: double.infinity,
height: 150,
decoration: BoxDecoration(
color: Colors.blue.shade50.withOpacity(.3),
borderRadius: BorderRadius.circular(10)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Iconsax.folder_open, color: Colors.blue, size: 40,),
const SizedBox(height: 15,),
Text('Select your file', style: TextStyle(fontSize: 15, color: Colors.grey.shade400),),
],
),
),
)
),
),
_platformFile != null
? Container(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Selected File',
style: TextStyle(color: Colors.grey.shade400, fontSize: 15, ),),
const SizedBox(height: 10,),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.shade200,
offset: const Offset(0, 1),
blurRadius: 3,
spreadRadius: 2,
)
]
),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.file(_file!, width: 70,)
),
const SizedBox(width: 10,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_platformFile!.name,
style: const TextStyle(fontSize: 13, color: Colors.black),),
const SizedBox(height: 5,),
Text('${(_platformFile!.size / 1024).ceil()} KB',
style: TextStyle(fontSize: 13, color: Colors.grey.shade500),
),
const SizedBox(height: 5,),
Container(
height: 5,
clipBehavior: Clip.hardEdge,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.blue.shade50,
),
child: LinearProgressIndicator(
value: loadingController.value,
)
),
],
),
),
const SizedBox(width: 10,),
],
)
),
const SizedBox(height: 20,),
// MaterialButton(
// minWidth: double.infinity,
// height: 45,
// onPressed: () {},
// color: Colors.black,
// child: Text('Upload', style: TextStyle(color: Colors.white),),
// )
],
))
: Container(),
const SizedBox(height: 150,),
],
),
));
}
}
| 0
|
mirrored_repositories/flutter-file-upload
|
mirrored_repositories/flutter-file-upload/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:file_select_upload/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/My-First-Flutter-App
|
mirrored_repositories/My-First-Flutter-App/lib/main.dart
|
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: Home()
));
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My First App"),
centerTitle: true,
backgroundColor: Colors.red[600],
),
body: Row(
children: <Widget>[
Expanded(
child: Image.asset("assets/snow.jpg"),
flex: 3,
),
Expanded(
flex: 1,
child:
Container(
padding: EdgeInsets.all(30.0),
color: Colors.pinkAccent,
child: Text("1"),
)),
Expanded(
flex: 1,
child:
Container(
padding: EdgeInsets.all(30.0),
color: Colors.amber,
child: Text("2"),
)),
Expanded(
flex: 1,
child:
Container(
padding: EdgeInsets.all(30.0),
color: Colors.cyan,
child: Text("3"),
)),
],
),
// Column(
// mainAxisAlignment: MainAxisAlignment.end,
// crossAxisAlignment: CrossAxisAlignment.end,
// children: <Widget>[
// Row(
// children: <Widget>[
// Text("hello"),
// Text("World")
// ],
// ),
// Container(
// padding: EdgeInsets.all(20.0),
// color: Colors.cyan,
// child: Text("one"),
// ),
// Container(
// padding: EdgeInsets.all(30.0),
// color: Colors.pinkAccent,
// child: Text("Two"),
// ),
//
// Container(
// padding: EdgeInsets.all(40.0),
// color: Colors.amber,
// child: Text("Three"),
// ),
//
// ],
// ),
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// crossAxisAlignment: CrossAxisAlignment.end,
// children: <Widget>[
// Text("Hello World"),
// FlatButton(
// onPressed: () {},
// color: Colors.amber,
// child: Text('Click Me')),
// Container(
// color: Colors.cyan,
// padding: EdgeInsets.all(30.0),
// child: Text("Inside Container"),
// )
// ],
// ),
// Padding(
// padding: EdgeInsets.all(30.0),
// child: Text("Hello"),
// ),
// Container(
// color: Colors.grey[400],
// child: Text("Hello"),
// padding: EdgeInsets.fromLTRB(10.0, 20.0, 30.0, 40.0),
// margin: EdgeInsets.all(30.0),
// ),
// Container(
// color: Colors.grey[400],
// child: Text("Hello"),
// padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 10.0),
// ),
// Container(
// color: Colors.grey[400],
// child: Text("Hello"),
// padding: EdgeInsets.all(20.0),
// ),
// Center(
// child: Image(
// image: AssetImage("assets/images/snow.jpg"),
//// image: NetworkImage("https://images.unsplash.com/photo-1581115684447-383df67ff1ea?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjI2Njg5fQ&auto=format&fit=crop&w=934&q=80") ,
// )
// child: Image.asset("assets/snow.jpg"),
//
// child: RaisedButton(
// onPressed: () {},
// child: Text(
// "Click Me"
// ),
// color: Colors.blue,
// ),
// child: FlatButton(
// onPressed: () {},
// child: Text(
// "Click"
// ),
// color: Colors.lightBlue,
// ),
// child: RaisedButton.icon(onPressed: () {}, icon: Icon(
// Icons.mail
// ), label: Text("Mail me"),
// color: Colors.amber,),
//
// child: IconButton(
// onPressed: () {},
// icon: Icon(Icons.alternate_email),
// color: Colors.amber,
// ),
// ),
floatingActionButton: FloatingActionButton(
child: Text("click"),
onPressed: (){},
backgroundColor: Colors.red[600],
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO
|
mirrored_repositories/CleanToDO/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/lists/TasksPage.dart';
import 'package:clean_todo/settings/Themes.dart';
import 'package:clean_todo/settings/SettingsManager.dart';
import 'package:clean_todo/settings/InitManager.dart';
import 'package:clean_todo/data/DataCache.dart';
import 'package:clean_todo/settings/LoginScreen.dart';
import 'package:clean_todo/settings/SplashScreen.dart';
import 'package:quick_actions/quick_actions.dart';
import 'package:clean_todo/detail/TaskDetail.dart';
/*
void main() => runApp(
new FutureBuilder(
future: InitManager.getInstance(),
builder: (_, snapshot) {
return snapshot.hasData ?
new LoginScreen( settings: snapshot.data.settings, cache: snapshot.data.cache ) :
new SplashScreen() ;
}
)
);
*/
void main() => runApp(
new FutureBuilder(
future: InitManager.getInstance(),
builder: (_, snapshot) {
return snapshot.hasData ?
(
snapshot.data.isSignedIn ?
new CleanToDoApp( settings: snapshot.data.settings, cache: snapshot.data.cache ) :
new LoginScreen( settings: snapshot.data.settings, cache: snapshot.data.cache )
) :
new SplashScreen() ;
}
)
);
class CleanToDoApp extends StatelessWidget {
DataCache cache;
SettingsManager settings;
CleanToDoApp({this.settings, this.cache});
initAppShortcuts(BuildContext context){
final QuickActions quickActions = const QuickActions();
quickActions.initialize((String shortcutType) {
if (shortcutType == 'action_new') {
/*
runApp(
new MaterialApp(
theme: Themes.get( settings.theme ),
home: new TaskDetail(
task: cache.newTask,
categoryData: cache.categoryData,
updateTask: (task){
cache.addTask(task);
},
exitApp: true,
),
)
);
*/
Navigator.of(context).push(
new MaterialPageRoute(
builder: (_) => new MaterialApp(
theme: Themes.get(settings.theme),
home: new TaskDetail(
task: cache.newTask,
categoryData: cache.categoryData,
updateTask: (task){
cache.addTask(task);
},
),
)
),
);
}
});
quickActions.setShortcutItems(<ShortcutItem>[
const ShortcutItem(
type: 'action_new', localizedTitle: 'New Task', icon: 'qa_new'
)
]);
}
@override
Widget build(BuildContext context) {
//initAppShortcuts(context);
return new MaterialApp(
//theme: Themes.get( AppColors.BLACK ),
theme: Themes.get( settings.theme ),
home: new TasksPage(settings: this.settings, cache: this.cache),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/CTExpansionPanel.dart
|
import 'package:flutter/material.dart';
class CTExpansionPanel {
CTExpansionPanel({ this.label, this.subtitle, this.body });
String label ;
String subtitle ;
Widget body ;
ListTile build(BuildContext context){
TextStyle headerStyle = new TextStyle( color: Theme.of(context).primaryColor, fontSize: 24.0 );
return new ListTile(
title: new Card(
child: new Column(
children: <Widget>[
new ListTile(
title: new Text( label, style: headerStyle, ),
subtitle: new Text( subtitle ),
),
body,
],
)
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/MyDayTasksList.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/beans/Task.dart';
import 'package:clean_todo/lists/TaskTile.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/lists/CTExpansionPanel.dart';
import 'package:clean_todo/beans/CategoryData.dart';
class MyDayTasksList extends StatefulWidget {
MyDayTasksList({ this.todayTasks, this.dueTasks, this.pendingTasks,
this.extraTask, this.categoryData, this.toggleTask,
this.updateTask, this.deleteTask });
List<Task> todayTasks ;
List<Task> dueTasks ;
List<Task> pendingTasks ;
final Task extraTask ;
final CategoryData categoryData ;
final ValueChanged<Task> toggleTask;
final ValueChanged<Task> updateTask ;
final ValueChanged<Task> deleteTask ;
@override
_MyDayTasksListState createState() => new _MyDayTasksListState();
}
class _MyDayTasksListState extends State<MyDayTasksList> {
@override
Widget build(BuildContext context) {
List<Widget> todayTaskRowsList = [];
widget.todayTasks.forEach( (task){
todayTaskRowsList.add(
new TaskTile (
task : task,
extraTask: widget.extraTask,
categoryData: widget.categoryData,
updateTask : (task) => widget.updateTask(task),
deleteTask: (task) => widget.deleteTask(task),
),
);
todayTaskRowsList.add( new Divider( ) ); //color : Theme.of(context).primaryColor ) );
});
if (todayTaskRowsList.length > 1 ) todayTaskRowsList.removeLast();
List<Widget> dueTaskRowsList = [];
widget.dueTasks.forEach( (task){
dueTaskRowsList.add(
new TaskTile (
task : task,
extraTask: widget.extraTask,
categoryData: widget.categoryData,
updateTask : (task) => widget.updateTask(task),
deleteTask: (task) => widget.deleteTask(task),
),
);
dueTaskRowsList.add( new Divider( ) ); //color : Theme.of(context).primaryColor ) );
});
if (dueTaskRowsList.length > 1 ) dueTaskRowsList.removeLast();
List<Widget> pendingTaskRowsList = [];
widget.pendingTasks.forEach( (task){
pendingTaskRowsList.add(
new TaskTile (
task : task,
extraTask: widget.extraTask,
categoryData: widget.categoryData,
updateTask : (task) => widget.updateTask(task),
deleteTask: (task) => widget.deleteTask(task),
),
);
pendingTaskRowsList.add( new Divider( ) ); //color : Theme.of(context).primaryColor ) );
});
if (pendingTaskRowsList.length > 1 ) pendingTaskRowsList.removeLast();
List<CTExpansionPanel> _items = [
new CTExpansionPanel(
label: 'Today',
subtitle : widget.todayTasks.length == 1 ? '1 Pending' : widget.todayTasks.length.toString() + ' Pending',
body: new Column(
children: todayTaskRowsList,
),
),
new CTExpansionPanel(
label: 'Overdue',
subtitle : widget.dueTasks.length == 1 ? '1 Pending' : widget.dueTasks.length.toString() + ' Pending',
body: new Column(
children: dueTaskRowsList,
),
),
new CTExpansionPanel(
label : 'Upcoming',
subtitle: widget.pendingTasks.length == 1 ? '1 Task' : widget.pendingTasks.length.toString() + ' Tasks',
body: new Column(
children: pendingTaskRowsList,
),
)
];
return new Container(
color: Theme.of(context).primaryColor,
child: new ListView(
children: _items. map( (panel){
return panel.build(context);
}).toList(),
)
) ;
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/TaskTile.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/beans/Task.dart';
import 'package:clean_todo/detail/TaskDetail.dart';
import 'package:clean_todo/lists/LeaveBehindView.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/data/NotificationManager.dart';
import 'package:clean_todo/styles/AppIcons.dart';
class TaskTile extends StatefulWidget {
TaskTile({
this.task , this.extraTask, this.categoryData,
this.toggleTask, this.updateTask, this.deleteTask,
this.isSelected = false, this.selectTask,
});
final Task task ;
final Task extraTask ;
final CategoryData categoryData ;
final ValueChanged<Task> toggleTask;
final ValueChanged<Task> updateTask ;
final ValueChanged<Task> deleteTask ;
final bool isSelected;
final ValueChanged<Task> selectTask ;
@override
_TasksTileState createState() => new _TasksTileState();
}
class _TasksTileState extends State<TaskTile> {
final AppIcons icons = new AppIcons();
List<Widget> getSubtitleWidgets( Task task ){
List<Widget> subtitleWidgets = [];
EdgeInsets tmargin = new EdgeInsets.only( top: 10.0, );
EdgeInsets lmargin = new EdgeInsets.only( left: 10.0, top: 10.0, );
final TextStyle taskSubTitle = new TextStyle( color: ( widget.isSelected ? Theme.of(context).highlightColor : Theme.of(context).primaryColorLight ), fontWeight: FontWeight.w500 );
final TextStyle taskSubTitleDue = new TextStyle( color: Theme.of(context).errorColor, fontWeight: FontWeight.w500 );
if( task.category != null ) {
subtitleWidgets.add(
new Padding(
padding: tmargin,
child: new Row(
children: <Widget>[
new Text( task.category.text, style: taskSubTitle ),
],
)
)
);
}
if( task.deadline != null ){
subtitleWidgets.add(
new Padding(
padding: lmargin,
child: new Row(
children: <Widget>[
icons.listIconDue( widget.isSelected, context, task.isDue ),
new Text( task.isDue ? 'Due ' + task.deadline : task.deadline,
style: task.isDue ? taskSubTitleDue : taskSubTitle ),
],
)
)
);
}
if( task.reminder != null ){
subtitleWidgets.add(
new Padding(
padding: lmargin, child: icons.listIconReminder(widget.isSelected, context),
)
);
}
if( task.notes != null ){
subtitleWidgets.add(
new Padding(
padding: lmargin, child : icons.listIconNotes(widget.isSelected, context),
)
);
}
if( task.repeat != null && task.repeat != CTRepeatInterval.NONE.index){
subtitleWidgets.add(
new Padding(
padding: lmargin, child: icons.listIconRepeat(widget.isSelected, context)
)
);
}
return subtitleWidgets;
}
Map<DismissDirection, double> _dismissThresholds() {
Map<DismissDirection, double> map = new Map<DismissDirection, double>();
map.putIfAbsent(DismissDirection.horizontal, () => 0.5);
return map;
}
@override
Widget build(BuildContext context) {
final TextStyle taskTitle = new TextStyle( fontWeight: FontWeight.normal );
final TextStyle taskTitleChecked = new TextStyle( fontWeight: FontWeight.normal, decoration: TextDecoration.lineThrough );
return new Dismissible(
key: new Key( widget.task.id.toString() ),
background: new LeaveBehindViewLeft(),
secondaryBackground: new LeaveBehindViewRight(),
direction: DismissDirection.horizontal,
dismissThresholds: _dismissThresholds(),
onDismissed: ((disDir) {
widget.deleteTask(widget.task);
final snackBar = new SnackBar( content: new Text("Task Deleted") );
Scaffold.of(context).showSnackBar(snackBar);
}),
child: new ListTileTheme(
selectedColor: Theme.of(context).highlightColor,
child: new ListTile(
leading: new IconButton(
icon: widget.task.completed ? icons.taskCompletedIcon(widget.isSelected, context) : icons.taskPendingIcon(widget.isSelected, context),
onPressed: (){
this.setState((){
widget.task.completed ? widget.task.completed = false : widget.task.completed = true ;
});
widget.toggleTask( widget.task );
},
),
title: new Text( widget.task.title, style : widget.task.completed ? taskTitleChecked : taskTitle ),
subtitle: new Row(
mainAxisAlignment: MainAxisAlignment.start,
children: getSubtitleWidgets( widget.task ),
),
onTap: (){
widget.extraTask.copy(widget.task);
Navigator.push(
context,
new MaterialPageRoute( builder: (context) =>
new TaskDetail(
task: widget.extraTask,
categoryData: widget.categoryData,
updateTask: (task){
widget.updateTask(task);
},
)
)
);
},
selected: widget.isSelected,
onLongPress: ((){
print( "long press on task tile" );
widget.selectTask(widget.task);
}),
),
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/AboutView.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/data/DataCache.dart';
import 'package:clean_todo/settings/SettingsManager.dart';
import 'package:clean_todo/settings/LoginScreen.dart';
import 'package:clean_todo/styles/AppIcons.dart';
import 'package:clean_todo/settings/Themes.dart';
import 'package:clean_todo/main.dart';
class AboutView extends StatefulWidget {
String appVersion = "1.4.201806230";
DataCache cache;
SettingsManager settings;
AboutView({ this.cache, this.settings,});
@override
_AboutViewState createState() => new _AboutViewState();
}
class _AboutViewState extends State<AboutView> {
_doFixCounts(){
widget.cache.reset_category_counts()
.whenComplete(
() => showDialog(
context: context,
builder: (_) => new AlertDialog(
content: new Text('sidebar list counts\' re-calculation done'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.pop(_),
child: new Text( "OK" )
)
],
),
)
);
}
_updateShowCompletedTasks(value){
this.setState( () {
widget.cache.showCompletedTasks = value;
widget.settings.showCompleted = value;
});
}
_showSortListView(){
String sortString = widget.cache.sortTasks;
return showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return new ListView (
children: <Widget>[
new ListTile(
title: new Text( 'Sort Tasks', style: new TextStyle( fontSize: 20.0 ), ),
),
new ListTile(
leading: new Icon( Icons.sort_by_alpha ),
title: new Text( 'Albhabetically' ),
onTap: ((){
this.updateSortTasks('SORT_BY_ALPHA');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_ALPHA' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.date_range ),
title: new Text( 'Due Date' ),
onTap: ((){
this.updateSortTasks('SORT_BY_DUE');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_DUE' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.add_circle_outline ),
title: new Text( 'Creation Date' ),
onTap: ((){
this.updateSortTasks('SORT_BY_CREA');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_CREA' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.check ),
title: new Text( 'Completed' ),
onTap: ((){
this.updateSortTasks('SORT_BY_COMPLETED');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_COMPLETED' ? new Icon( Icons.check ) : null,
),
],
);
//return ;
}
);
}
updateSortTasks(value){
this.setState((){
widget.cache.sortTasks = value;
widget.settings.sortString = value;
});
}
_updateColor(value) {
this.setState(() {
widget.settings.theme = value;
});
runApp(
new CleanToDoApp(
cache: widget.cache,
settings: widget.settings,
),
);
}
IconButton colorIcon( Color btnColor, AppColors color, context ){
String themeColor = widget.settings.theme == null ? 'blue' : widget.settings.theme;
return new IconButton(
icon: new CircleAvatar(
backgroundColor: btnColor,
minRadius: 40.0,
child: color.index.toString() == themeColor ? new Icon( Icons.check, size: 30.0,) : null,
),
iconSize: 75.0,
onPressed: () => _updateColor(color.index.toString())
);
}
_showColorPopup(){
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return new ListView (
children: <Widget>[
new ListTile(
title: new Text( 'Select New Color', style: new TextStyle( fontSize: 20.0 ), ),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.blue, AppColors.BLUE, context),
colorIcon(Colors.indigo, AppColors.INDIGO, context),
colorIcon(Colors.cyan, AppColors.CYAN, context),
colorIcon(Colors.teal, AppColors.TEAL, context),
],
),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.brown, AppColors.BROWN, context),
colorIcon(Colors.purple, AppColors.PURPLE, context),
colorIcon(Colors.deepPurple, AppColors.DEEP_PURPLE, context),
colorIcon(Colors.amber, AppColors.AMBER, context),
],
),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.red, AppColors.RED, context),
colorIcon(Colors.pink, AppColors.PINK, context),
colorIcon(Colors.blueGrey, AppColors.BLUE_GREY, context),
colorIcon(Colors.black, AppColors.BLACK, context),
],
),
),
],
);
//return ;
}
);
}
@override
Widget build(BuildContext context) {
AppIcons icons = new AppIcons();
DataCache cacheN = widget.cache;
SettingsManager settingsN = widget.settings;
bool isShowCompletedTasks = cacheN.showCompletedTasks ;
bool isEnableNotificationSounds = settingsN.notification_sounds;
bool isEnableNotificationVibrations = settingsN.notification_vibrations;
return new Scaffold(
appBar: new AppBar(
title: new Text( 'About' ),
),
body: new ListView(
children: <Widget>[
new Card(
child: new ListTile(
leading: cacheN.userData.abbr == null ?
new Icon( Icons.account_circle ):
new CircleAvatar(
child: new Text( cacheN.userData.abbr, style: new TextStyle( color: Colors.white ), ),
backgroundColor: Theme.of(context).primaryColor,
),
title: new Text( cacheN.userData.userName == null ? 'User Data' : cacheN.userData.userName ),
subtitle: cacheN.userData.email == null ? null : new Text( cacheN.userData.email ),
trailing: new RaisedButton(
color: Colors.red,
child: new Text( "clear", style: new TextStyle( color: Colors.white ), ),
onPressed: ((){
cacheN.clean_all().whenComplete( ((){
cacheN.userData.userName = null;
cacheN.userData.abbr = null;
settingsN.username = null;
runApp(
new LoginScreen(
cache: cacheN,
settings: settingsN,
),
);
}) );
}),
),
),
),
new Card(
child: new Column(
children: <Widget>[
new ListTile(
leading: icons.reCaluclateCountsIcon(context),
title: new Text( "Fix Sidebar Counts" ),
onTap: () => _doFixCounts(),
),
new ListTile(
leading: new Icon( isShowCompletedTasks ? Icons.check_box : Icons.check_box_outline_blank ),
title: new Text( isShowCompletedTasks ? 'Hide Completed Tasks' : 'Show Completed Tasks' ),
onTap: () => _updateShowCompletedTasks( !isShowCompletedTasks ),
),
new ListTile(
leading: new Icon( Icons.sort ),
title: new Text( "Sort" ),
onTap: () => _showSortListView(),
),
new ListTile(
leading: new Icon( Icons.color_lens ),
title: new Text( "Color Scheme" ),
onTap: () => _showColorPopup(),
),
]
),
),
/*
new Card(
child: new Column(
children: <Widget>[
new ListTile(
leading: new Icon( Icons.notifications_active ),
title: new Text( isEnableNotificationSounds ? "Disable Notification Sounds" : "Enable Notification Sounds" ),
onTap: () => this.setState( () => settingsN.notification_sounds = !isEnableNotificationSounds ),
),
new ListTile(
leading: new Icon( Icons.notifications_paused ),
title: new Text( isEnableNotificationVibrations ? "Disable Notification Vibrations" : "Enable Notification Vibrations" ),
onTap: () => this.setState( () => settingsN.notification_vibrations = !isEnableNotificationVibrations ),
),
],
),
),
*/
new Card(
child: new Column(
children: <Widget>[
new ListTile(
title: new Text( "Application Version" ),
subtitle: new Text( settingsN.projectVersion ),
),
]
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/TasksPage.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/sidebar/AppSidebar.dart';
import 'package:clean_todo/data/DataProvider.dart';
import 'package:clean_todo/lists/TasksList.dart';
import 'package:clean_todo/data/DefaultDataGenerator.dart';
import 'package:clean_todo/data/DataCache.dart';
import 'package:clean_todo/lists/CTAppBar.dart';
import 'package:clean_todo/lists/MyDayTasksList.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/detail/TaskDetail.dart';
import 'package:clean_todo/settings/SettingsManager.dart';
import 'package:clean_todo/settings/Themes.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:clean_todo/lists/TasksList.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/styles/AppIcons.dart';
import 'package:clean_todo/main.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
import 'package:clean_todo/lists/DropdownTileSF.dart';
import 'package:quick_actions/quick_actions.dart';
class _SystemPadding extends StatelessWidget {
final Widget child;
_SystemPadding({Key key, this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
var mediaQuery = MediaQuery.of(context);
return new AnimatedContainer(
padding: mediaQuery.viewInsets,
duration: const Duration(milliseconds: 300),
child: child);
}
}
class TasksPage extends StatefulWidget {
SettingsManager settings;
DataCache cache;
TasksPage({this.settings, this.cache});
@override
_TasksPageState createState() => new _TasksPageState();
}
class _TasksPageState extends State<TasksPage> {
filter( int categoryId ){
this.setState( (){
if( categoryId == -1 ) {
widget.cache.filterCategory = null;
widget.cache.filterCategoryId = null;
widget.cache.filterGroupId = null;
widget.cache.showMyDay = true;
widget.cache.filterGroup = false;
} else if ( categoryId == -2 ) {
widget.cache.filterCategory = null;
widget.cache.filterCategoryId = null;
widget.cache.filterGroupId = null;
widget.cache.showMyDay = false;
widget.cache.filterGroup = false;
} else {
widget.cache.filterCategoryId = categoryId;
widget.cache.filterGroupId = null;
widget.cache.filterCategory =
widget.cache.categoryData.getCategoryGroup( categoryId ).text +
' / ' +
widget.cache.categoryData.getCategory( categoryId ).text;
widget.cache.showMyDay = false;
widget.cache.filterGroup = false;
}
});
Navigator.pop( context );
}
filterGroup( int groupId ){
this.setState( (){
widget.cache.filterCategoryId = null;
widget.cache.filterGroupId = groupId;
widget.cache.filterCategory = widget.cache.categoryData.getGroup( groupId ).text;
widget.cache.showMyDay = false;
widget.cache.filterGroup = true;
});
Navigator.pop( context );
}
@override
Widget build(BuildContext context) {
widget.cache.initNotifications(context);
int categoryId = widget.cache.filterCategoryId;
String categoryTxt = widget.cache.filterCategory;
CategoryData categoryData = widget.cache.categoryData;
int groupId = widget.cache.filterGroupId == null ?
( categoryId == null ? null : categoryData.getCategoryGroup(categoryId).id ) :
widget.cache.filterGroupId;
String groupTxt = widget.cache.filterGroupId == null ? null : categoryData.getGroup(groupId).text;
AppBar appBar = new CTAppBar(
filterCategoryId: categoryId,
filterCategory: categoryTxt,
groupId: groupId,
groupName: groupTxt,
deleteCategory: ((category) =>
this.setState( (){
widget.cache.deleteCategory(category);
widget.cache.filterCategory = null;
widget.cache.filterCategoryId = null;
widget.cache.filterGroupId = null;
widget.cache.filterGroup = false;
})
),
deleteCategoryGroup: ((categoryGroup) =>
this.setState( (){
widget.cache.deleteCategoryGroup(categoryGroup);
widget.cache.filterCategory = null;
widget.cache.filterCategoryId = null;
widget.cache.filterGroupId = null;
widget.cache.filterGroup = false;
})
),
isMyDay: widget.cache.showMyDay,
isSearch: widget.cache.enableSearch,
isGroup: widget.cache.filterGroup,
toggleSearch: ( (isSearch) =>
this.setState( (){
widget.cache.enableSearch = isSearch;
widget.cache.searchString = null;
})
),
searchString: widget.cache.searchString,
doSearch: ( (value) =>
this.setState( (){
widget.cache.searchString = value;
})
),
themeColor: widget.settings.theme == null ? 'blue' : widget.settings.theme,
updateColor: ( (value) {
this.setState(() {
widget.settings.theme = value;
});
runApp(
new CleanToDoApp(
cache: widget.cache,
settings: widget.settings,
),
);
}
),
isShowCompletedTasks: widget.cache.showCompletedTasks,
updateShowCompletedTasks: ((value) {
widget.cache.showCompletedTasks = value;
widget.cache.updateShowCompletedTasks()
.then( (_) {
this.setState(() {
widget.cache.showCompletedTasks = value;
widget.settings.showCompleted = value;
});
});
}),
updateSortTasks: ((value) =>
this.setState((){
widget.cache.sortTasks = value;
widget.settings.sortString = value;
})
),
sortString: widget.cache.sortTasks,
categoryName: widget.cache.filterCategoryId == null ? null : widget.cache.categoryData.getCategory( widget.cache.filterCategoryId ).text,
updateCategoryName: ((newValue) =>
this.setState((){
widget.cache.updateCategoryName(newValue);
widget.cache.filterCategory =
widget.cache.categoryData.getCategoryGroup( categoryId ).text +
' / ' +
widget.cache.categoryData.getCategory( categoryId ).text;
})
),
updateGroupName: ((newValue) =>
this.setState((){
widget.cache.updateGroupName( groupId, newValue );
groupTxt = newValue;
widget.cache.filterCategory = newValue;
})
),
isSelectedTask: widget.cache.isSelected,
unSelectTask: ( (_){
this.setState((){
widget.cache.isSelected = false;
widget.cache.selectedTaskId.clear();
});
}),
deleteSelectedTask: ( (_){
this.setState((){
widget.cache.deleteSelectedTask();
widget.cache.isSelected = false;
widget.cache.selectedTaskId.clear();
});
}),
).build(context);
AppSidebar appSidebar = new AppSidebar(
categories : widget.cache.categoryData,
addCategory : ((newCategory) =>
this.setState( (){
widget.cache.addCategory(newCategory);
})
),
addCategoryGroup : ((newGroup) =>
this.setState( (){
widget.cache.addCategoryGroup(newGroup);
})
),
filter : filter,
filterGroup: filterGroup,
userData : widget.cache.userData,
cache: widget.cache,
settings: widget.settings,
);
Widget myDayAppBody = new MyDayTasksList(
todayTasks: widget.cache.todayTasks,
dueTasks: widget.cache.dueTasks,
pendingTasks: widget.cache.pendingTasks,
extraTask: widget.cache.newTask,
categoryData: widget.cache.categoryData,
toggleTask: widget.cache.toggleTask,
updateTask: ( (task){
this.setState( (){
widget.cache.updateTask(task);
});
}),
deleteTask: widget.cache.deleteTask,
);
Widget listAppBody = new TasksList(
tasks: widget.cache.tasks,
extraTask: widget.cache.newTask,
categoryData: widget.cache.categoryData,
toggleTask: ( (task){
this.setState( (){
widget.cache.toggleTask(task);
});
}),
updateTask: ( (task){
this.setState( (){
widget.cache.updateTask(task);
});
}),
deleteTask: widget.cache.deleteTask,
isSelected: widget.cache.isSelected,
selectedTask: widget.cache.selectedTaskId,
selectTask: ( (task){
this.setState((){
widget.cache.selectedTaskId.contains( task.id ) ?
widget.cache.selectedTaskId.remove( task.id ):
widget.cache.selectedTaskId.add(task.id);
widget.cache.selectedTaskId.length > 0 ?
widget.cache.isSelected = true :
widget.cache.isSelected = false;
});
}),
);
Widget appBody = widget.cache.showMyDay ? myDayAppBody : listAppBody ;
AppIcons icons = new AppIcons();
FloatingActionButton appFabFilter = new FloatingActionButton(
child: icons.newTaskFabIcon(context),
//backgroundColor: Theme.of(context).primaryColor,
onPressed: (){
TextEditingController tecNewTask = new TextEditingController();
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return new _SystemPadding(
child: new Container(
child: new Padding(
padding: const EdgeInsets.all(5.0),
child: new ListTile(
leading: icons.newTaskModal(context),
title: new TextField(
autofocus: true,
controller: tecNewTask,
decoration: new InputDecoration(
hintText: 'Add task title',
hintStyle: new TextStyle( color: Colors.grey ),
border: InputBorder.none,
),
onSubmitted: (value){
if( value != null && value.length > 0 ) {
this.setState(() {
widget.cache.newTask.clear();
widget.cache.newTask.id = widget.cache.tasksData.length == 0 ? 1 : widget.cache.tasksData.last.id + 1;
widget.cache.newTask.title = value;
widget.cache.newTask.category = widget.cache.categoryData.getCategory( widget.cache.filterCategoryId );
widget.cache.addTask(widget.cache.newTask);
Navigator.pop(context);
});
}
},
),
trailing: new IconButton(
icon: icons.newTaskModalArrow(context),
onPressed: (){
if( tecNewTask.text != null && tecNewTask.text.length > 0 ) {
this.setState(() {
widget.cache.newTask.clear();
widget.cache.newTask.id = widget.cache.tasksData.length == 0 ? 1 : widget.cache.tasksData.last.id + 1;
widget.cache.newTask.title = tecNewTask.text;
widget.cache.newTask.category = widget.cache.categoryData.getCategory( widget.cache.filterCategoryId );
widget.cache.addTask(widget.cache.newTask);
Navigator.pop(context);
});
} else {
showDialog(
context: context,
builder: (_) => new AlertDialog(
content: new Text('Title is required'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.pop(_),
child: new Text( "OK" )
)
],
),
);
}
}
),
)
)
)
);
},
);
}
);
FloatingActionButton appFabGroup = new FloatingActionButton(
child: icons.newTaskFabIcon(context),
onPressed: (){
widget.cache.newTask.clear();
TextEditingController tecNewTask = new TextEditingController();
showModalBottomSheet<void>(
context: context,
builder: (BuildContext bcontext){
return new _SystemPadding(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new DropdownTileSF(
icon: Icons.list,
text: widget.cache.newTask.category == null ? null : widget.cache.newTask.category.id.toString(),
hint: 'Select a list',
options: widget.cache.filterGroupId == null ?
widget.cache.categoryData.user.map((Category pCategory) {
CategoryGroup categoryGroup =
widget.cache.categoryData.getCategoryGroup( pCategory.id );
return new DropdownMenuItem<String>(
value: pCategory.id.toString(),
child: new Text(categoryGroup.text + " / " + pCategory.text),
);
}).toList()
:
widget.cache.categoryData.getGroupMembers(
widget.cache.categoryData.getGroup( widget.cache.filterGroupId )
).map((Category pCategory) {
return new DropdownMenuItem<String>(
value: pCategory.id.toString(),
child: new Text(pCategory.text),
);
}).toList(),
updateContent: (content) {
this.setState(() {
if (content == null)
widget.cache.newTask.category = null;
else
widget.cache.newTask.category = widget.cache.categoryData.getCategory( int.parse( content ) );
});
},
),
new ListTile(
dense: true,
leading: icons.newTaskModal(context),
title: new TextField(
autofocus: false,
controller: tecNewTask,
decoration: new InputDecoration(
hintText: 'Add task title',
hintStyle: new TextStyle( color: Colors.grey ),
border: InputBorder.none,
),
),
trailing: new IconButton(
icon: icons.newTaskModalArrow(context),
onPressed: (){
if( widget.cache.newTask.category == null ){
showDialog(
context: context,
builder: (_) => new AlertDialog(
content: new Text('Select a list for the task'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.pop(_),
child: new Text( "OK" )
)
],
),
);
} else if( tecNewTask.text != null && tecNewTask.text.length > 0 ) {
this.setState(() {
widget.cache.newTask.id = widget.cache.tasksData.length == 0 ? 1 : widget.cache.tasksData.last.id + 1;
widget.cache.newTask.title = tecNewTask.text;
widget.cache.addTask(widget.cache.newTask);
Navigator.pop(context);
});
} else {
showDialog(
context: context,
builder: (_) => new AlertDialog(
content: new Text('Add a title for the task'),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.pop(_),
child: new Text( "OK" )
)
],
),
);
}
}
),
),
],
),
);
},
);
}
);
FloatingActionButton appFabGeneric = new FloatingActionButton(
child: icons.newTaskFabIcon(context),
//backgroundColor: Theme.of(context).primaryColor,
onPressed: (){
widget.cache.newTask.clear();
widget.cache.newTask.id = widget.cache.tasksData.length == 0 ? 1 : widget.cache.tasksData.last.id + 1;
Navigator.push(
context,
new MaterialPageRoute( builder: (context) =>
new TaskDetail(
task: widget.cache.newTask,
categoryData: widget.cache.categoryData,
updateTask: (task){
widget.cache.addTask(task);
},
)
)
);
}
);
FloatingActionButton appFab = ( widget.cache.showMyDay || widget.cache.isSelected )? null :
( ( widget.cache.filterCategory == null ) || widget.cache.filterGroup ? appFabGroup : appFabFilter );
return new Scaffold(
appBar: appBar,
drawer: appSidebar,
body: appBody,
floatingActionButton: appFab,
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/TasksList.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/beans/Task.dart';
import 'package:clean_todo/lists/TaskTile.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/styles/AppIcons.dart';
class TasksList extends StatefulWidget {
TasksList({
this.tasks, this.extraTask, this.categoryData,
this.toggleTask, this.updateTask, this.deleteTask,
this.selectedTask, this.selectTask, this.isSelected,
});
final List<Task> tasks ;
final Task extraTask ;
final CategoryData categoryData ;
final ValueChanged<Task> toggleTask;
final ValueChanged<Task> updateTask ;
final ValueChanged<Task> deleteTask ;
final ValueChanged<Task> selectTask ;
final bool isSelected ;
final List<int> selectedTask ;
@override
_TasksListState createState() => new _TasksListState();
}
class _TasksListState extends State<TasksList> {
AppIcons icons = new AppIcons();
_getTextForEmpty(context){
return new Container(
child: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
icons.noTasksIcon(context),
new Text(
"There are no items in this list, \n add something to start",
style: new TextStyle( color: Theme.of(context).iconTheme.color.withAlpha( 170 ), ),
),
],
),
),
);
}
_getAsList(){
return new ListView(
children: ListTile.divideTiles(
tiles: widget.tasks.map(
(task) => new TaskTile (
task : task,
extraTask: widget.extraTask,
categoryData: widget.categoryData,
toggleTask: (task) => widget.toggleTask(task),
updateTask : (task) => widget.updateTask(task),
deleteTask: (task) => widget.deleteTask(task),
isSelected: widget.isSelected ? widget.selectedTask.where( (id) => id == task.id ).length > 0 : false,
selectTask: widget.selectTask,
)
).toList(),
color: Colors.grey,
).toList(),
);
}
@override
Widget build(BuildContext context) {
if( widget.tasks.isEmpty )
return _getTextForEmpty(context);
else
return _getAsList();
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/IconText.dart
|
import 'package:flutter/material.dart';
class IconText extends StatelessWidget {
IconData icon;
String label;
IconText({ this.icon, this.label });
@override
Widget build(BuildContext context) {
return new Row(
children: <Widget>[
new Icon( icon, color: Theme.of(context).iconTheme.color ),
new Padding(
padding: new EdgeInsets.only(left: 10.0,),
child: new Text(label, style: new TextStyle( color: Theme.of(context).accentColor ),),
),
],
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/DropdownTileSF.dart
|
import 'package:flutter/material.dart';
class DropdownTileSF extends StatefulWidget{
DropdownTileSF({ this.text, this.hint, this.icon, this.updateContent, this.options });
String text ;
final String hint ;
final IconData icon ;
final ValueChanged<String> updateContent ;
final List<DropdownMenuItem<String>> options ;
@override
_DropdownTileState createState() => new _DropdownTileState();
}
class _DropdownTileState extends State<DropdownTileSF> {
@override
Widget build(BuildContext context) {
return new ListTile(
key: widget.key,
dense: false,
leading: new Icon( widget.icon, color: Theme.of(context).iconTheme.color, size: 28.0 ,),
title : new DropdownButtonHideUnderline(
child: new DropdownButton<String>(
value: widget.text,
hint: new Text(widget.hint),
iconSize: 0.0,
items: widget.options,
style: new TextStyle( color: Theme.of(context).accentColor ),
onChanged: (String value){
this.setState( ((){
widget.text = value;
widget.updateContent( value );
}) );
},
),
),
trailing: widget.text == null ? null :
new IconButton(
icon : new Icon( Icons.clear, color: Theme.of(context).iconTheme.color, ),
onPressed: (){
this.setState( ((){
widget.text = null;
widget.updateContent( null );
}) );
},
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/CTAppBar.dart
|
import 'package:flutter/material.dart';
//import 'package:color/color.dart';
import 'package:clean_todo/lists/IconText.dart';
import 'package:clean_todo/settings/Themes.dart';
class CTAppBar {
CTAppBar({ this.filterCategoryId, this.filterCategory,
this.groupId, this.groupName,
this.deleteCategory, this.deleteCategoryGroup,
this.updateCategoryName, this.isSearch, this.isGroup,
this.isMyDay, this.toggleSearch,
this.searchString, this.doSearch,
this.themeColor, this.updateColor,
this.isShowCompletedTasks, this.updateShowCompletedTasks,
this.sortString, this.updateSortTasks, this.categoryName, this.updateGroupName,
this.isSelectedTask, this.unSelectTask, this.deleteSelectedTask,
});
final String appDefaultTitle = 'To-Do';
final int filterCategoryId;
final String filterCategory ;
final int groupId;
final String groupName ;
final ValueChanged<int> deleteCategory ;
final ValueChanged<int> deleteCategoryGroup ;
final bool isSelectedTask ;
final bool isSearch ;
final bool isMyDay ;
final bool isGroup ;
final ValueChanged<bool> toggleSearch ;
final String searchString ;
final ValueChanged<String> doSearch ;
final String themeColor ;
final ValueChanged<String> updateColor ;
final bool isShowCompletedTasks ;
final ValueChanged<bool> updateShowCompletedTasks ;
final String sortString;
final ValueChanged<String> updateSortTasks ;
final String categoryName ;
final ValueChanged<String> updateCategoryName;
final ValueChanged<String> updateGroupName;
final ValueChanged<bool> unSelectTask;
final ValueChanged<bool> deleteSelectedTask;
IconButton colorIcon( Color btnColor, AppColors color, context ){
return new IconButton(
icon: new CircleAvatar(
backgroundColor: btnColor,
minRadius: 40.0,
child: color.index.toString() == themeColor ? new Icon( Icons.check, size: 30.0,) : null,
),
iconSize: 75.0,
onPressed: () => updateColor( color.index.toString()) ,
);
}
_appBarActions( int actionId, BuildContext context ) {
switch (actionId) {
case 0: showDialog(
context: context,
builder: (_) => new AlertDialog(
content: new Text('delete list ' + categoryName + ' ?'),
actions: <Widget>[
new FlatButton(
child: new Text( 'CANCEL' ),
onPressed: () => Navigator.pop( context ),
),
new FlatButton(
child: new Text( 'OK' ),
onPressed: ((){
this.deleteCategory(filterCategoryId);
Navigator.pop(context);
//final snackBar = new SnackBar(content: new Text('List Deleted'));
//Scaffold.of(_).showSnackBar(snackBar);
}),
),
],
),
);
break;
case 1: showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return new ListView (
children: <Widget>[
new ListTile(
title: new Text( 'Select New Color', style: new TextStyle( fontSize: 20.0 ), ),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.blue, AppColors.BLUE, context),
colorIcon(Colors.indigo, AppColors.INDIGO, context),
colorIcon(Colors.cyan, AppColors.CYAN, context),
colorIcon(Colors.teal, AppColors.TEAL, context),
],
),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.brown, AppColors.BROWN, context),
colorIcon(Colors.purple, AppColors.PURPLE, context),
colorIcon(Colors.deepPurple, AppColors.DEEP_PURPLE, context),
colorIcon(Colors.amber, AppColors.AMBER, context),
],
),
),
new ListTile(
title: new Row(
children: <Widget>[
colorIcon(Colors.red, AppColors.RED, context),
colorIcon(Colors.pink, AppColors.PINK, context),
colorIcon(Colors.blueGrey, AppColors.BLUE_GREY, context),
colorIcon(Colors.black, AppColors.BLACK, context),
],
),
),
],
);
//return ;
}
);
break;
case 2: updateShowCompletedTasks( !isShowCompletedTasks );
break;
case 3: showModalBottomSheet<void>(
context: context,
builder: (BuildContext context){
return new ListView (
children: <Widget>[
new ListTile(
title: new Text( 'Sort Tasks', style: new TextStyle( fontSize: 20.0 ), ),
),
new ListTile(
leading: new Icon( Icons.sort_by_alpha ),
title: new Text( 'Albhabetically' ),
onTap: ((){
this.updateSortTasks('SORT_BY_ALPHA');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_ALPHA' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.date_range ),
title: new Text( 'Due Date' ),
onTap: ((){
this.updateSortTasks('SORT_BY_DUE');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_DUE' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.add_circle_outline ),
title: new Text( 'Creation Date' ),
onTap: ((){
this.updateSortTasks('SORT_BY_CREA');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_CREA' ? new Icon( Icons.check ) : null,
),
new ListTile(
leading: new Icon( Icons.check ),
title: new Text( 'Completed' ),
onTap: ((){
this.updateSortTasks('SORT_BY_COMPLETED');
Navigator.pop(context);
}),
trailing: sortString == 'SORT_BY_COMPLETED' ? new Icon( Icons.check ) : null,
),
],
);
//return ;
}
);
break;
case 4:
TextEditingController tecRenameList = new TextEditingController( text: this.categoryName );
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: new Text( 'Rename List', style: new TextStyle( fontWeight: FontWeight.bold ), ),
content: new TextField(
controller: tecRenameList,
),
actions: <Widget>[
new FlatButton(
child: new Text( 'CANCEL' ),
onPressed: () => Navigator.pop( context ),
),
new FlatButton(
child: new Text( 'OK' ),
onPressed: ((){
this.updateCategoryName (tecRenameList.text);
Navigator.pop(context);
}),
),
],
),
);
break;
case 5: showDialog(
context: context,
builder: (_) => new AlertDialog(
content: new Text('delete list group ' + groupName + ' and all lists and tasks ?'),
actions: <Widget>[
new FlatButton(
child: new Text( 'CANCEL' ),
onPressed: () => Navigator.pop( context ),
),
new FlatButton(
child: new Text( 'OK' ),
onPressed: ((){
this.deleteCategoryGroup(groupId);
Navigator.pop(context);
//final snackBar = new SnackBar(content: new Text('List Deleted'));
//Scaffold.of(_).showSnackBar(snackBar);
}),
),
],
),
);
break;
case 6:
TextEditingController tecRenameGroup = new TextEditingController( text: this.groupName );
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: new Text( 'Rename Group', style: new TextStyle( fontWeight: FontWeight.bold ), ),
content: new TextField(
controller: tecRenameGroup,
),
actions: <Widget>[
new FlatButton(
child: new Text( 'CANCEL' ),
onPressed: () => Navigator.pop( context ),
),
new FlatButton(
child: new Text( 'OK' ),
onPressed: ((){
this.updateGroupName (tecRenameGroup.text);
Navigator.pop(context);
}),
),
],
),
);
break;
}
}
AppBar mydayAppBar(){
return new AppBar(
title: new Text( 'My Day' ),
elevation: 0.0,
);
}
AppBar homeAppBar(){
return new AppBar(
title: new Text( appDefaultTitle),
actions: [
new IconButton(
icon: new Icon( Icons.search ),
onPressed: (){
toggleSearch(true);
},
),
],
);
}
AppBar selectedAppBar(){
return new AppBar(
leading: new IconButton(
icon: new Icon( Icons.arrow_back ),
onPressed: (){
unSelectTask(true);
},
),
title: new Text( "Selected" ),
actions: [
new IconButton(
icon: new Icon( Icons.delete ),
onPressed: (){
deleteSelectedTask(true);
},
),
],
);
}
AppBar searchAppBar(){
return new AppBar(
leading: new IconButton(
icon: new Icon( Icons.arrow_back ),
onPressed: (){
toggleSearch(false);
},
),
title: new TextField(
autofocus: true,
style: new TextStyle(color: Colors.white),
controller: new TextEditingController(text: searchString),
decoration: new InputDecoration( hintText: 'Search', hintStyle: new TextStyle( color: Colors.white70 ) ),
onSubmitted: (value) => doSearch( value ),
),
actions: [
new IconButton(
icon: new Icon( Icons.clear ),
onPressed: (){
toggleSearch(false);
},
),
],
);
}
AppBar filterAppBar(context){
return new AppBar(
title: new Text(filterCategory),
actions: [
new IconButton(
icon: new Icon( Icons.search ),
onPressed: (){
toggleSearch(true);
},
),
new PopupMenuButton<int>(
onSelected: (value) => _appBarActions(value, context),
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
new PopupMenuItem<int>(
value: 4,
child: new IconText( icon: Icons.edit, label: 'Rename List'),
),
new PopupMenuItem<int>(
value: 3,
child: new IconText( icon: Icons.sort, label: 'Sort'),
),
new PopupMenuItem<int>(
value: 2,
child: new IconText(
icon: isShowCompletedTasks ? Icons.check_box : Icons.check_box_outline_blank,
label: isShowCompletedTasks ? 'Hide Completed Tasks' : 'Show Completed Tasks'
),
),
new PopupMenuItem<int>(
value: 1,
child: new IconText( icon: Icons.color_lens, label: 'Color Scheme'),
),
new PopupMenuItem<int>(
value: 0,
child: new IconText( icon: Icons.delete_sweep, label: 'Delete List'),
),
];
},
)
],
);
}
AppBar groupAppBar(context){
return new AppBar(
title: new Text(filterCategory),
actions: [
new IconButton(
icon: new Icon( Icons.search ),
onPressed: (){
toggleSearch(true);
},
),
new PopupMenuButton<int>(
onSelected: (value) => _appBarActions(value, context),
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
new PopupMenuItem<int>(
value: 6,
child: new IconText( icon: Icons.edit, label: 'Rename Group'),
),
new PopupMenuItem<int>(
value: 3,
child: new IconText( icon: Icons.sort, label: 'Sort'),
),
new PopupMenuItem<int>(
value: 2,
child: new IconText(
icon: isShowCompletedTasks ? Icons.check_box : Icons.check_box_outline_blank,
label: isShowCompletedTasks ? 'Hide Completed Tasks' : 'Show Completed Tasks'
),
),
new PopupMenuItem<int>(
value: 1,
child: new IconText( icon: Icons.color_lens, label: 'Change Color'),
),
new PopupMenuItem<int>(
value: 5,
child: new IconText( icon: Icons.delete_forever, label: 'Delete Group'),
),
];
},
)
],
);
}
AppBar build(context) {
if( isSelectedTask )
return selectedAppBar();
if( isGroup )
return groupAppBar(context);
if( isMyDay )
return mydayAppBar();
if( isSearch )
return searchAppBar();
else if( filterCategory == null )
return homeAppBar();
else
return filterAppBar(context);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/lists/LeaveBehindView.dart
|
import 'package:flutter/material.dart';
class LeaveBehindViewLeft extends StatelessWidget {
LeaveBehindViewLeft({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Container(
padding: const EdgeInsets.all(16.0),
color: Theme.of(context).primaryColor.withAlpha( 75 ),
child: new Row (
children: <Widget>[
new Icon(Icons.delete, color: Colors.white,),
new Expanded(
child: new Text(''),
),
],
),
);
}
}
class LeaveBehindViewRight extends StatelessWidget {
LeaveBehindViewRight({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Container(
padding: const EdgeInsets.all(16.0),
color: Theme.of(context).primaryColor.withAlpha( 75 ),
child: new Row (
children: <Widget>[
new Expanded(
child: new Text(''),
),
new Icon(Icons.delete, color: Colors.white,),
],
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/sidebar/NewCategoryDialog.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/styles/AppIcons.dart';
class NewCategoryDialog extends StatefulWidget {
NewCategoryDialog({Key key, this.categoryData, this.addCategory, this.addCategoryGroup }) : super(key: key);
final CategoryData categoryData;
final ValueChanged<Category> addCategory ;
final ValueChanged<CategoryGroup> addCategoryGroup ;
int selectedGroupId ;
bool newGroup ;
@override
_NewCategoryDialogState createState() => new _NewCategoryDialogState();
}
class _NewCategoryDialogState extends State<NewCategoryDialog> {
List<DropdownMenuItem<String>> getCatagoryGroups(){
var icons = new AppIcons();
List<DropdownMenuItem<String>> listCategoryGroups = [];
listCategoryGroups.add(
new DropdownMenuItem<String>(
value: "-1",
child: new SizedBox(
width: 330.0,
child: new ListTile(
leading: new Padding(
padding: new EdgeInsets.only( bottom: 10.0 ),
child: icons.groupOpenIcon(context),
),
title: new Padding(
padding: new EdgeInsets.only( bottom: 10.0 ),
child: new Text( 'Select List Group', style: new TextStyle( fontSize: 20.0 ) ),
),
),
),
)
);
listCategoryGroups.addAll(
widget.categoryData.userGroups.map( (categoryData){
return new DropdownMenuItem<String>(
value: categoryData.id.toString(),
child: new SizedBox(
width: 330.0,
child: new ListTile(
leading: new Padding(
padding: new EdgeInsets.only( bottom: 10.0 ),
child: icons.groupIcon(context),
),
title: new Padding(
padding: new EdgeInsets.only( bottom: 10.0 ),
child: new Text( categoryData.text, style: new TextStyle( fontSize: 20.0 ) ),
),
),
),
);
})
);
listCategoryGroups.add(
new DropdownMenuItem<String>(
value: "-2",
child: new SizedBox(
width: 330.0,
child: new ListTile(
leading: new Padding(
padding: new EdgeInsets.only( bottom: 10.0 ),
child: icons.newGroupIcon(context),
),
title: new Padding(
padding: new EdgeInsets.only( bottom: 10.0 ),
child: new Text( 'New List Group', style: new TextStyle( fontSize: 20.0 ) ),
),
),
),
)
);
//print( "listCategoryGroups :: " + listCategoryGroups.toString() );
return listCategoryGroups;
}
final TextEditingController _newCatCont = new TextEditingController();
final TextEditingController _newCaCGrpCont = new TextEditingController();
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
Widget build(BuildContext context) {
widget.selectedGroupId = widget.categoryData.newCategoryGroup.id;
widget.newGroup = widget.categoryData.newGroup;
//print( "new value to dpd ::" + widget.selectedGroupId.toString() );
return new Scaffold(
appBar: new AppBar(
leading: new IconButton(
icon: new Icon( Icons.clear, color: Theme.of(context).iconTheme.color, ),
onPressed: () => Navigator.of(context).pop(),
),
title: new Text( 'New List', style: new TextStyle( color: Theme.of(context).accentColor ), ),
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
elevation: 0.0,
actions: <Widget>[
new FlatButton(
onPressed: () {
this.setState((){
final FormState form = _formKey.currentState;
if( form.validate() ) {
if (widget.selectedGroupId > 0) {
widget.addCategory(
new Category (
groupId: widget.selectedGroupId,
text: _newCatCont.text,
icon: Icons.list,
count: 0,
)
);
Navigator.of(context).pop();
} else if (widget.selectedGroupId == -2) {
int newGroupId = widget.categoryData.userGroups.last.id + 1;
widget.addCategoryGroup(
new CategoryGroup(
text: _newCaCGrpCont.text,
id: newGroupId,
)
);
widget.addCategory(
new Category (
groupId: newGroupId,
text: _newCatCont.text,
icon: Icons.list,
count: 0,
)
);
Navigator.of(context).pop();
} else {
showDialog(
context: context,
builder: ((context){
return new AlertDialog(
title: new Text( 'please select a list group' ),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.of(context).pop(),
child: new Text( 'OK' )
)
],
);
}),
);
}
}
});
},
child: new Text('SAVE', style: new TextStyle( color: Theme.of(context).accentColor) )
),
],
),
body: new Form(
key: _formKey,
child: new Padding(
padding: new EdgeInsets.all( 20.0 ),
child: new ListView(
children: <Widget>[
new TextFormField(
autofocus: true,
controller: _newCatCont,
style: new TextStyle( fontSize: 20.0, color: Theme.of(context).accentColor ),
//maxLines: 10,
textAlign: TextAlign.start,
decoration: new InputDecoration(
hintText: 'untitled',
hintStyle: new TextStyle( fontSize: 20.0, color: Colors.grey ),
labelText: 'List Name',
//border: InputBorder.none,
),
validator: (valueListName){
if( valueListName.isEmpty ){
return 'please enter list name';
}
},
),
new Padding(
padding: new EdgeInsets.only( top: 40.0 ),
child: new Text('List Group', textDirection: TextDirection.ltr,
style: new TextStyle( color: Theme.of(context).accentColor ),
),
),
new DropdownButton<String>(
value: widget.selectedGroupId.toString(),
iconSize: 0.0,
items: getCatagoryGroups(),
onChanged: ((_){
this.setState((){
widget.selectedGroupId = int.parse(_);
widget.categoryData.newCategoryGroup.id = int.parse(_);
if( _ == "-1" ){
widget.newGroup = false;
widget.categoryData.newGroup = false;
} else if ( _ == "-2" ){
widget.newGroup = true;
widget.categoryData.newGroup = true;
} else {
widget.newGroup = false;
widget.categoryData.newGroup = false;
}
});
}),
),
new Padding(
padding: new EdgeInsets.only( top: 20.0 ),
),
widget.newGroup ? new TextFormField(
autofocus: true,
controller: _newCaCGrpCont,
style: new TextStyle( fontSize: 20.0, color: Theme.of(context).accentColor ),
//maxLines: 10,
textAlign: TextAlign.start,
decoration: new InputDecoration(
hintText: 'untitled',
hintStyle: new TextStyle( fontSize: 20.0, color: Colors.grey ),
labelText: 'List Group Name',
//border: InputBorder.none,
),
validator: (valueGroupName){
if( widget.selectedGroupId == -2 && valueGroupName.isEmpty ){
return 'please enter list group name';
}
},
) : new Text(' '),
],
)
),
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/sidebar/AppSidebar.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/sidebar/NewCategoryDialog.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
import 'package:clean_todo/beans/UserData.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/settings/SettingsManager.dart';
import 'package:clean_todo/data/DataCache.dart';
import 'package:clean_todo/lists/AboutView.dart';
import 'package:clean_todo/styles/AppIcons.dart';
class AppSidebar extends StatefulWidget {
AppSidebar(
{ Key key, this.categories, this.addCategory, this.addCategoryGroup,
this.filter, this.filterGroup, this.userData, this.cache, this.settings,
})
: super(key: key);
final UserData userData;
final CategoryData categories;
final DataCache cache;
final SettingsManager settings;
final ValueChanged<Category> addCategory;
final ValueChanged<CategoryGroup> addCategoryGroup;
final ValueChanged<int> filter;
final ValueChanged<int> filterGroup;
@override
_AppSidebarState createState() => new _AppSidebarState();
}
class _AppSidebarState extends State<AppSidebar> {
var icons = new AppIcons();
ListTile getAsSystemListTile( context, Category categoryData ){
return new ListTile(
dense: false,
title: new Row (
children: <Widget>[
icons.systemIcon( categoryData.icon, context),
new Padding(padding: new EdgeInsets.all( 7.0 ) ),
new SidebarTextBold( textContent : categoryData.text ),
],
),
onTap: () {
this.widget.filter( categoryData.id );
}
);
}
ListTile getAsListTile( context, Category categoryData ){
return new ListTile(
dense: false,
title: new Row (
children: <Widget>[
icons.listIcon(context),
new Padding(padding: new EdgeInsets.all( 7.0 ) ),
new SidebarText( textContent : categoryData.text ),
],
),
trailing: categoryData.count == null || categoryData.count == 0 ? null :
new Text( categoryData.count.toString(), style: new TextStyle( color: Theme.of(context).accentColor ), ),
onTap: () {
this.widget.filter( categoryData.id );
}
);
}
Widget getAsGroupPanel2( context, CategoryGroup categoryGroup ){
return new Column(
children: [
new Divider(),
new ListTile(
title: new Row (
children: <Widget>[
( categoryGroup.isExpanded == null || categoryGroup.isExpanded ) ?
icons.groupOpenIcon(context) : icons.groupIcon(context),
new Padding(padding: new EdgeInsets.all( 7.0 ) ),
new SidebarTextBold( textContent: categoryGroup.text ),
],
),
trailing: new IconButton(
icon: ( categoryGroup.isExpanded == null || categoryGroup.isExpanded ) ?
icons.groupOpenArrowIcon(context) : icons.groupArrowIcon(context),
onPressed: () {
this.setState(() {
categoryGroup.isExpanded = !categoryGroup.isExpanded;
});
}
),
onTap: () {
this.widget.filterGroup( categoryGroup.id );
}
),
new Column(
children: categoryGroup.isExpanded ?
this.widget.categories
.getGroupMembers(categoryGroup)
.map( (category){
return new Padding(
padding: new EdgeInsets.only( left: 20.0 ),
child: getAsListTile( context, category )
);
}).toList()
: [ ],
)
]
);
}
@override
Widget build(BuildContext context) {
return new Drawer(
child: new ListView(
padding: new EdgeInsets.only(top: 30.0),
children: <Widget>[
new ListTile(
title: new Row(
children: <Widget>[
this.widget.userData.abbr == null ?
new Icon( Icons.settings, color: Theme.of(context).iconTheme.color, ) :
new CircleAvatar( child: new Text( this.widget.userData.abbr, style: new TextStyle( color: Colors.white ), ),
backgroundColor: Theme.of(context).primaryColor, ),
new Padding(padding: new EdgeInsets.all( 7.0 ) ),
new Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: this.widget.userData.email == null ?
<Widget>[
new SidebarText( textContent : this.widget.userData.userName == null ? 'Settings' : this.widget.userData.userName ) ,
]
:
<Widget>[
new SidebarText( textContent : this.widget.userData.userName == null ? 'Settings' : this.widget.userData.userName ) ,
new Text( this.widget.userData.email, style: new TextStyle( color: Theme.of(context).accentColor ), ),
],
),
],
),
onTap: () => Navigator.of(context).push(
new MaterialPageRoute(
builder: (context) => new AboutView(
cache: widget.cache,
settings: widget.settings,
)
),
),
),
new Divider(),
new Column(
children: this.widget.categories.system.map( (category){
return getAsSystemListTile(context, category);
}).toList(),
),
new ListTile(
dense: false,
title: new Row (
children: <Widget>[
icons.newListIcon(context),
new Padding(padding: new EdgeInsets.all( 7.0 ) ),
new SidebarTextBold( textContent : 'New List' ),
],
),
onTap: (){
widget.cache.categoryData.newCategoryGroup.id = -1;
widget.cache.categoryData.newGroup = false;
Navigator.of(context).push(
new MaterialPageRoute(
builder: (context) =>
new NewCategoryDialog(
categoryData: widget.cache.categoryData,
addCategory: widget.addCategory,
addCategoryGroup: widget.addCategoryGroup,
),
maintainState: true,
fullscreenDialog: true,
)
);
},
),
new Padding(
padding: new EdgeInsets.only(left: 10.0, right: 10.0),
child: new Column(
children: this.widget.categories.userGroups.map( (categoryGroup){
return getAsGroupPanel2(context, categoryGroup);
}).toList(),
),
),
],
),
);
}
}
class SidebarText extends StatelessWidget {
SidebarText({this.textContent});
final String textContent;
@override
Widget build(BuildContext context) {
return new Text(
this.textContent,
style: new TextStyle( fontSize: 16.0, fontWeight: FontWeight.w300,color: Theme.of(context).accentColor ),
);
}
}
class SidebarTextBold extends StatelessWidget {
SidebarTextBold({this.textContent});
final String textContent;
@override
Widget build(BuildContext context) {
return new Text(
this.textContent,
style: new TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, color: Theme.of(context).accentColor ),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/detail/TitleDetailTile.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/styles/AppIcons.dart';
class TitleDetailTile extends StatelessWidget {
TitleDetailTile({ this.completed, this.update_completed, this.title, this.update_title });
final bool completed ;
final ValueChanged<bool> update_completed ;
final String title ;
final ValueChanged<String> update_title ;
final AppIcons icons = new AppIcons();
@override
Widget build(BuildContext context) {
return new ListTile(
leading: new IconButton(
icon: this.completed ? icons.taskCompletedIcon( false, context) : icons.taskPendingIcon( false, context),
onPressed: (){
this.completed ? this.update_completed( false ): this.update_completed( true );
},
),
title: new TextField(
autofocus: true,
controller: new TextEditingController( text: this.title ),
onSubmitted: (value) => update_title( value ),
//onChanged: (value) => update_title( value ),
style: new TextStyle( fontSize: 24.0, color: Theme.of(context).accentColor ),
decoration: new InputDecoration(
border: InputBorder.none,
hintText: 'Enter Title',
hintStyle: new TextStyle( fontSize: 24.0, color: Colors.grey ),
labelText: 'Title',
labelStyle: new TextStyle( fontSize: 18.0, color: Colors.grey ),
),
),
trailing: new IconButton(
icon: new Icon( Icons.clear, color: this.title == null ? Colors.white : Theme.of(context).iconTheme.color, ),
onPressed: () => update_title( null ),
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/detail/NoteDetailDialog.dart
|
import 'package:flutter/material.dart';
class NoteDetailDialog extends StatelessWidget {
NoteDetailDialog({ this.title, this.note, this.updateNote });
final String title ;
final String note ;
final ValueChanged<String> updateNote ;
TextEditingController noteController ;
@override
Widget build(BuildContext context) {
noteController = new TextEditingController( text: note );
return new Scaffold(
appBar: new AppBar(
leading: new IconButton(
icon: new Icon( Icons.clear, color: Theme.of(context).iconTheme.color, ),
onPressed: () => Navigator.of(context).pop(),
),
title: new Text( title == null ? 'Add a note' : title, style: new TextStyle( color: Theme.of(context).accentColor ), ),
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
elevation: 0.0,
actions: <Widget>[
new FlatButton(
onPressed: () {
updateNote(noteController.text);
Navigator.of(context).pop();
},
child: new Text('SAVE', style: new TextStyle( color: Theme.of(context).accentColor) )
),
],
),
body: new Padding(
padding: new EdgeInsets.all( 20.0 ),
child: new TextField(
autofocus: true,
controller: noteController,
style: new TextStyle( fontSize: 20.0, color: Theme.of(context).accentColor ),
maxLines: 10,
textAlign: TextAlign.start,
decoration: new InputDecoration(
hintText: 'Add a note',
hintStyle: new TextStyle( fontSize: 20.0, color: Colors.grey ),
border: InputBorder.none,
),
),
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/detail/NoteDetailTile.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/detail/NoteDetailDialog.dart';
class NoteDetailTile extends StatelessWidget{
NoteDetailTile({ this.title, this.text, this.hint, this.icon, this.updateContent });
final String title ;
final String text ;
final String hint ;
final IconData icon ;
final ValueChanged<String> updateContent ;
@override
Widget build(BuildContext context) {
return new ListTile(
leading: new Icon( icon, color: Theme.of(context).iconTheme.color, size: 28.0 ,),
title: this.text == null ?
new Text( this.hint, style: new TextStyle( color: Colors.grey ), ) :
new Text( this.text, style: new TextStyle( color: Theme.of(context).accentColor ), ),
trailing: this.text == null ? null :
new IconButton(
icon : new Icon( Icons.clear, color: Theme.of(context).iconTheme.color, ),
onPressed: () => this.updateContent( null ),
),
onTap: (){
Navigator.of(context).push(
new MaterialPageRoute(
builder: (context) =>
new NoteDetailDialog(
title: this.title,
note: this.text,
updateNote: (noteText) => this.updateContent(noteText),
),
maintainState: true,
fullscreenDialog: true,
)
);
},
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/detail/DropdownTile.dart
|
import 'package:flutter/material.dart';
class DropdownTile extends StatelessWidget{
DropdownTile({ this.text, this.hint, this.icon, this.updateContent, this.options });
final String text ;
final String hint ;
final IconData icon ;
final ValueChanged<String> updateContent ;
final List<DropdownMenuItem<String>> options ;
@override
Widget build(BuildContext context) {
return new ListTile(
leading: new Icon( icon, color: Theme.of(context).iconTheme.color, size: 28.0 ,),
title : new DropdownButtonHideUnderline(
child: new DropdownButton<String>(
value: this.text,
hint: new Text(this.hint),
iconSize: 0.0,
items: options,
style: new TextStyle( color: Theme.of(context).accentColor ),
onChanged: (String value){
this.updateContent( value );
},
),
),
trailing: this.text == null ? null :
new IconButton(
icon : new Icon( Icons.clear, color: Theme.of(context).iconTheme.color, ),
onPressed: (){
this.updateContent( null );
},
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/detail/TaskDetail.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/beans/Task.dart';
import 'package:clean_todo/detail/NoteDetailTile.dart';
import 'package:clean_todo/detail/DropdownTile.dart';
import 'package:clean_todo/detail/TitleDetailTile.dart';
import 'package:clean_todo/calender/DateUtil.dart';
import 'package:clean_todo/calender/TimeUtil.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'dart:async';
import 'package:clean_todo/data/NotificationManager.dart';
import 'dart:io';
class TaskDetail extends StatefulWidget {
TaskDetail({ this.task, this.updateTask, this.categoryData, this.exitApp = false });
final Task task ;
final ValueChanged<Task> updateTask ;
final CategoryData categoryData ;
final bool exitApp ;
_TaskDetailState createState() => new _TaskDetailState();
}
class _TaskDetailState extends State<TaskDetail> {
final List<String> _deadlines = ['Today', 'Tomorrow', 'Next Week'];
final List<String> _reminders = ['Later Today @ 09:00', 'Later Today @ 21:00', 'Tomorrow @ 09:00', 'Next Week @ 09:00'];
String getValueForCustom( deadline ){
if( deadline == null ){
return 'Custom';
} else if ( _deadlines.contains(deadline) ) {
return 'Custom';
} else {
return deadline;
}
}
String getTitleForCustom( deadlineVal ){
if( deadlineVal == null ){
return 'Custom';
} else if ( _deadlines.contains(deadlineVal) ) {
return 'Custom';
} else {
return deadlineVal;
}
}
String getReminderValueForCustom( reminder ){
if( reminder == null ){
return 'Custom';
} else if ( _reminders.contains(reminder) ) {
return 'Custom';
} else {
return reminder;
}
}
String getReminderTitleForCustom( reminderVal ){
if( reminderVal == null ){
return 'Custom';
} else if ( _reminders.contains(reminderVal) ) {
return 'Custom';
} else {
return reminderVal;
}
}
_update_deadline(content){
if( !_deadlines.contains(content) && content != null ){
Future<DateTime> picked = showDatePicker(
context: context,
firstDate: DateUtil.today,
initialDate: content == 'Custom' ? DateUtil.today : DateTime.parse( widget.task.deadline_val ),
lastDate: new DateTime.now().add( new Duration( days: 365 ) ),
);
picked.then( (pickedValue){
if ( pickedValue != null )
this.setState( (){
widget.task.deadline_val = DateUtil.parse(pickedValue);
});
});
} else {
this.setState( (){
widget.task.deadline_val = DateUtil.parse_string(content);
});
}
}
_update_reminder(String content) {
if (!_reminders.contains(content) && content != null) {
Future<DateTime> pickedDate = showDatePicker(
context: context,
firstDate: DateUtil.today,
initialDate: content == 'Custom' ? DateUtil.today : DateTime.parse(widget.task.reminder_date),
lastDate: new DateTime.now().add(new Duration(days: 365)),
);
pickedDate.then((pickedDateValue) {
Future<TimeOfDay> pickedTime = showTimePicker(
context: context,
initialTime: content == 'Custom' ? TimeUtil.now : TimeUtil.parse_back(widget.task.reminder_time),
);
pickedTime.then((pickedTimeValue) {
if (pickedDateValue != null && pickedTimeValue != null)
this.setState(() {
widget.task.reminder_date = DateUtil.parse(pickedDateValue);
widget.task.reminder_time = TimeUtil.parse(pickedTimeValue);
});
});
});
} else if (content != null) {
this.setState(() {
List<String> date_time = content.split('@');
widget.task.reminder_date = DateUtil.parse_string( date_time[0].trim() );
widget.task.reminder_time = date_time[1].trim();
});
} else {
this.setState(() {
widget.task.reminder_date = null;
widget.task.reminder_time = null;
});
}
}
_update_repeat(content){
if( content == null ) {
this.setState(() {
widget.task.repeat = null;
});
} else {
this.setState(() {
widget.task.repeat = int.parse(content);
});
}
}
_update_note(String content) {
this.setState( (){
widget.task.notes = content;
});
}
@override
Widget build(BuildContext context) {
BuildContext scaffoldContext;
return new Scaffold(
appBar: new AppBar(
title: widget.task.title == null ?
new Text( 'Create New Task' ) :
new Text( 'Update Task' ),
),
body: new Builder(builder: (BuildContext bodyContext) {
scaffoldContext = bodyContext;
return new Column(
children: <Widget>[
new Card(
child: new Column(
children: <Widget>[
new TitleDetailTile(
title: widget.task.title,
update_title: ((content) {
this.setState(() {
widget.task.title = content;
});
}),
completed: widget.task.completed,
update_completed: ((content) {
this.setState(() {
widget.task.completed = content;
});
}),
),
],
),
),
new Card(
child: new Column(
children: <Widget>[
new DropdownTile(
text: widget.task.category == null ? null : widget.task.category.id.toString(),
hint: 'Add to a List',
icon: Icons.list,
options: widget.categoryData.user.map((Category pCategory) {
Category category = widget.categoryData.getCategory( pCategory.id );
CategoryGroup categoryGroup = widget.categoryData.getCategoryGroup( pCategory.id );
return new DropdownMenuItem<String>(
value: pCategory.id.toString(),
child: new Text(categoryGroup.text + " / " + category.text ),
);
}).toList(),
updateContent: (content) {
this.setState(() {
if (content == null)
widget.task.category = null;
else
widget.task.category = widget.categoryData.getCategory( int.parse( content ) );
});
},
),
],
),
),
new Card(
child: new Column(
children: <Widget>[
new DropdownTile(
text: _deadlines.contains(widget.task.deadline) ? widget
.task.deadline : widget.task.deadline_val,
hint: 'Add Due Date',
icon: Icons.calendar_today,
options: <DropdownMenuItem<String>>[
new DropdownMenuItem<String>(
value: 'Today', child: new Text('Today'),),
new DropdownMenuItem<String>(
value: 'Tomorrow', child: new Text('Tomorrow'),),
new DropdownMenuItem<String>(
value: 'Next Week', child: new Text('Next Week'),),
new DropdownMenuItem<String>(
value: getValueForCustom(widget.task.deadline_val),
child: new Text(
getTitleForCustom(widget.task.deadline)),),
],
updateContent: _update_deadline,
),
new Divider(),
new DropdownTile(
text: widget.task.reminder,
hint: 'Remind Me',
icon: Icons.alarm_on,
options: <DropdownMenuItem<String>>[
new DropdownMenuItem<String>(
value: 'Later Today @ ' + TimeUtil.reminder_time_val,
child: new Text('Later Today @' + TimeUtil.reminder_time),),
new DropdownMenuItem<String>(
value: 'Tomorrow @ 09:00',
child: new Text('Tomorrow @9'),),
new DropdownMenuItem<String>(
value: 'Next Week @ 09:00',
child: new Text('Next Week @9'),),
new DropdownMenuItem<String>(
value: getReminderValueForCustom(widget.task.reminder),
child: new Text(getReminderTitleForCustom(widget.task.reminder)),),
],
updateContent: _update_reminder,
),
widget.task.reminder_date == null ? new Container() : new Divider(),
widget.task.reminder_date == null ? new Container() : new DropdownTile(
text: ( widget.task.repeat == null || widget.task.repeat == CTRepeatInterval.NONE.index ) ?
null :
widget.task.repeat.toString(),
hint: 'Repeat',
icon: Icons.repeat,
options: <DropdownMenuItem<String>>[
new DropdownMenuItem<String>(
value: CTRepeatInterval.DAILY.index.toString(),
child: new Text('daily'),
),
new DropdownMenuItem<String>(
value: CTRepeatInterval.WEEKLY.index.toString(),
child: new Text('weekly'),
),
new DropdownMenuItem<String>(
value: CTRepeatInterval.WEEKDAYS.index.toString(),
child: new Text('weekdays'),
),
new DropdownMenuItem<String>(
value: CTRepeatInterval.WEEKENDS.index.toString(),
child: new Text('weekends'),
),
new DropdownMenuItem<String>(
value: CTRepeatInterval.MONTHLY.index.toString(),
child: new Text('monthly'),
),
],
updateContent: _update_repeat,
),
],
),
),
new Card(
child: new Padding(
padding: new EdgeInsets.only(bottom: 40.0),
child: new NoteDetailTile(
title: widget.task.title,
text: widget.task.notes,
hint: 'Add a note',
icon: Icons.chat_bubble_outline,
updateContent: _update_note,
),
)
),
],
);
},
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.save),
onPressed: (){
if( widget.exitApp ){
exit(0);
} else if( widget.task.title == null ){
final snackBar = new SnackBar(content: new Text('please enter a title'), backgroundColor: Colors.red,);
Scaffold.of(scaffoldContext).showSnackBar(snackBar);
} else if ( widget.task.category == null ){
final snackBar = new SnackBar(content: new Text('please select a list'), backgroundColor: Colors.red,);
Scaffold.of(scaffoldContext).showSnackBar(snackBar);
} else {
widget.updateTask(widget.task);
Navigator.pop(context);
}
},
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/TaskProvider.dart
|
import 'dart:async';
import 'package:clean_todo/beans/Task.dart';
import 'dart:io' as io;
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:clean_todo/beans/CategoryData.dart';
class TaskProvider {
static final String table = "task";
static final String columnId = "_id";
static final String columnTitle = "title";
static final String columnCompleted = "completed";
static final String columnCategoryId = "categoryId";
static final String columnDeadlineVal = "deadlineVal";
static final String columnReminderDate = "reminderData";
static final String columnReminderTime = "reminderTime";
static final String columnRepeat = "repeat";
static final String columnNotes = "notes";
Database _db;
Future<Database> get db async {
if(_db != null)
return _db;
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "CleanToDoTasks.db");
await documentsDirectory.create(recursive: true);
var theDb = await openDatabase(
path,
version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
create table $table (
$columnId integer primary key autoincrement,
$columnTitle text not null,
$columnCompleted integer not null,
$columnCategoryId integer not null,
$columnDeadlineVal text,
$columnReminderDate text,
$columnReminderTime text,
$columnRepeat integer,
$columnNotes text
)
''');
}
);
return theDb;
}
insert(Task task) async {
var dbClient = await db;
Map<String, dynamic> ohThatMap = task.toMap();
await dbClient.insert(table, ohThatMap);
return true;
}
Future<List<Task>> allTasksPending( CategoryData categoryData ) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnTitle, columnCompleted, columnCategoryId,
columnDeadlineVal, columnReminderDate, columnReminderTime, columnRepeat, columnNotes],
where: "$columnCompleted = ?",
whereArgs: [0]
);
List<Task> allTasks = [];
maps.forEach(
(mapItem) => allTasks.add( Task.fromMap(mapItem, categoryData ) )
);
return allTasks;
}
Future<List<Task>> allTasks( CategoryData categoryData ) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnTitle, columnCompleted, columnCategoryId,
columnDeadlineVal, columnReminderDate, columnReminderTime, columnRepeat, columnNotes]
);
List<Task> allTasks = [];
maps.forEach(
(mapItem) => allTasks.add( Task.fromMap(mapItem, categoryData ) )
);
return allTasks;
}
Future<Task> getTask(int id, CategoryData categoryData ) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnTitle, columnCompleted, columnCategoryId,
columnDeadlineVal, columnReminderDate, columnReminderTime,
columnRepeat, columnNotes],
where: "$columnId = ?",
whereArgs: [id]
);
if (maps.length > 0) {
return new Task.fromMap(maps.first, categoryData);
}
return null;
}
delete(int id) async {
var dbClient = await db;
await dbClient.delete(
table,
where: "$columnId = ?",
whereArgs: [id]
);
}
delete_all() async {
var dbClient = await db;
await dbClient.delete(table, where: "1");
}
update(Task task) async {
var dbClient = await db;
await dbClient.update(
table,
task.toMap(),
where: "$columnId = ?",
whereArgs: [task.id]
);
}
Future close() async => _db.close();
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/CategoryGroupProvider.dart
|
import 'dart:async';
import 'dart:io' as io;
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
class CategoryGroupProvider {
static final String table = "categoryGroup";
static final String columnId = "_id";
static final String columnText = "text";
Database _db;
Future<Database> get db async {
if(_db != null)
return _db;
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "CleanToDoCategoryGroup.db");
await documentsDirectory.create(recursive: true);
var theDb = await openDatabase(
path,
version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
create table $table (
$columnId integer primary key autoincrement,
$columnText text not null
)
''');
}
);
return theDb;
}
insertAll(List<CategoryGroup> categoryGroups) {
categoryGroups.forEach( (categoryGroup) => insert( categoryGroup.clone() ) );
}
insert(CategoryGroup categoryGroup) async {
var dbClient = await db;
await dbClient.insert(table, categoryGroup.toMap());
}
Future<CategoryGroup> getCategoryGroup(int id) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnText],
where: "$columnId = ?",
whereArgs: [id]
);
if (maps.length > 0) {
return new CategoryGroup.fromMap(maps.first);
}
return null;
}
Future<List<CategoryGroup>> allCategoryGroups() async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnText]
);
List<CategoryGroup> allCategoryGroups = [];
maps.forEach(
(mapItem) => allCategoryGroups.add( CategoryGroup.fromMap(mapItem) )
);
return allCategoryGroups;
}
Future<CategoryGroup> getCategoryByText(String text) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnText],
where: "$columnText = ?",
whereArgs: [text]
);
if (maps.length > 0) {
return new CategoryGroup.fromMap(maps.first);
}
return null;
}
delete(int id) async {
var dbClient = await db;
await dbClient.delete(table, where: "$columnId = ?", whereArgs: [id]);
}
delete_all() async {
var dbClient = await db;
await dbClient.delete(table, where: "1");
}
update(CategoryGroup categoryGroup) async {
var dbClient = await db;
await dbClient.update(
table,
categoryGroup.toMap(),
where: "$columnId = ?", whereArgs: [categoryGroup.id]
);
}
Future close() async => _db.close();
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/DataProvider.dart
|
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/beans/UserData.dart';
import 'package:clean_todo/beans/Task.dart';
abstract class DataProvider {
CategoryData getSidebarData();
UserData getUserData();
List<Task> getAllTasks();
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/DataCache.dart
|
import 'package:clean_todo/beans/UserData.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/beans/Task.dart';
import 'package:clean_todo/calender/DateUtil.dart';
import 'package:clean_todo/data/CategoryProvider.dart';
import 'package:clean_todo/data/CategoryGroupProvider.dart';
import 'package:clean_todo/data/TaskProvider.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:clean_todo/data/NotificationManager.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
import 'package:clean_todo/data/NotificationManager.dart';
class DataCache {
CategoryData categoryData = new CategoryData();
UserData userData = null;
List<Task> tasksData = [];
Task newTask = new Task();
String filterCategory ;
int filterCategoryId ;
int filterGroupId ;
bool isCached = false;
bool enableSearch = false;
String searchString = '';
bool showMyDay = false;
bool filterGroup = false;
bool enableQuickAdd = false;
bool showCompletedTasks = true;
String sortTasks = "";
List<int> selectedTaskId = new List<int>();
bool isSelected = false;
final String dbName = "CleanToDoDB.db";
TaskProvider taskProvider = new TaskProvider();
CategoryProvider categoryProvider = new CategoryProvider();
CategoryGroupProvider categoryGroupProvider = new CategoryGroupProvider();
NotificationManager notifications = new NotificationManager();
static Future<DataCache> getInstance() async {
DataCache cache = new DataCache();
await cache.initDb(false);
return cache;
}
DataCache() {
newTask.id = tasksData.length + 1;
newTask.completed = false;
}
initNotifications( context ){
notifications.init(context, categoryData, this);
}
Future<bool> initCategoriesDb() async {
categoryData.user = await categoryProvider.allCategories();
categoryData.userGroups = await categoryGroupProvider.allCategoryGroups();
//print( "userGroups - " + categoryData.userGroups.length.toString() );
if( categoryData.userGroups == null || categoryData.userGroups.length == 0 ){
await add_default_userlists();
}
categoryData.system = [
new Category( id: -1, text: 'My Day', icon: Icons.lightbulb_outline ),
new Category( id: -2, text: 'To-Do', icon: Icons.check )
];
return true;
}
Future<bool> initDb( bool showCompleted ) async {
categoryData.user = await categoryProvider.allCategories();
categoryData.userGroups = await categoryGroupProvider.allCategoryGroups();
tasksData = ( showCompleted == null || showCompleted == true ) ?
await taskProvider.allTasks( categoryData ):
await taskProvider.allTasksPending( categoryData );
//print( "userGroups - " + categoryData.userGroups.length.toString() );
if( categoryData.userGroups == null || categoryData.userGroups.length == 0 ){
await add_default_userlists();
}
categoryData.system = [
new Category( id: -1, text: 'My Day', icon: Icons.lightbulb_outline ),
new Category( id: -2, text: 'To-Do', icon: Icons.check )
];
return true;
}
add_default_userlists() async {
categoryData.userGroups = [];
await addCategoryGroup(
new CategoryGroup( id: 1, text: 'Personal' )
);
await addCategoryGroup(
new CategoryGroup( id: 2, text: 'Office' )
);
categoryData.user = [];
await addCategories(
[
new Category( id: 1, groupId: 1, text: 'Home', count: 0 ),
new Category( id: 2, groupId: 2, text: 'Work', count: 0 ),
new Category( id: 3, groupId: 1, text: 'Shopping', count: 0 ),
]
);
}
List<Task> _filterGroup( List<Task> tasks, int groupId ){
if( groupId == null )
return tasks;
else
return tasks.where( (task) =>(
task != null &&
task.category != null &&
task.category.groupId == groupId )
).toList();
}
List<Task> _filterCategories( List<Task> tasks, int categoryId ){
if( categoryId == null )
return tasks;
else
return tasks.where( (task) =>(
task != null &&
task.category != null &&
task.category.id == categoryId )
).toList();
}
List<Task> _filterCompleted( List<Task> tasks ){
if( showCompletedTasks == true )
return tasks;
else
return tasks.where( (task) =>(
task != null &&
task.completed != null &&
task.completed == false )
).toList();
}
List<Task> _sortTasks( List<Task> tasks ){
tasks.sort( (task1, task2){
if( sortTasks == "SORT_BY_CREA" ){
return task1.id.compareTo(task2.id);
} else if( sortTasks == "SORT_BY_DUE" ){
var task1Deadline = "";
if( task1.deadline_val != null ) task1Deadline = task1.deadline_val;
var task2Deadline = "";
if( task2.deadline_val != null ) task2Deadline = task2.deadline_val;
return task1Deadline.compareTo(task2Deadline);
} else if( sortTasks == "SORT_BY_ALPHA" ){
return task1.title.compareTo(task2.title);
}else if( sortTasks == "SORT_BY_COMPLETED" ){
return task2.completed.toString().compareTo(task1.completed.toString());
} else {
return task1.id.compareTo(task2.id);
}
});
return tasks;
}
List<Task> _filterSearch( List<Task> tasks, String search ){
if( search == null )
return tasks;
else
return tasks.where( (task) => (
task != null &&
task.title != null &&
task.title.toLowerCase().contains(search) )
).toList();
}
List<Task> get tasks {
if( enableSearch )
return _filterSearch(
_filterCategories(
_filterGroup( tasksData, filterGroupId ),
filterCategoryId ),
searchString == null ? searchString : searchString.toLowerCase(),
);
else
return _sortTasks(
_filterCompleted(
_filterCategories(
_filterGroup( tasksData, filterGroupId ),
filterCategoryId )
)
);
}
Future<bool> addCategories( List<Category> newCategories ) async {
await categoryProvider.insertAll(newCategories);
newCategories.forEach( (newCategory){
this.categoryData.user.add( newCategory );
});
return true;
}
addCategoryGroup( CategoryGroup newCategoryGroup ) {
this.categoryData.userGroups.add( newCategoryGroup );
categoryGroupProvider.insert( newCategoryGroup );
}
addCategory( Category newCategoryLT ) {
newCategoryLT.id = categoryData.user.last.id + 1;
this.categoryData.user.add( newCategoryLT );
categoryProvider.insert( newCategoryLT.clone() );
}
deleteCategory( categoryId ) {
if( categoryId != null ) {
List<Task> toDelete = [];
this.tasksData.forEach((task) {
if (task != null &&
task.category != null &&
task.category.id == categoryId)
toDelete.add(task);
});
toDelete.forEach( (task){
deleteTask(task);
});
int indexToDelete = -1;
this.categoryData.user.asMap().forEach( (i, cat){
if( cat.id == categoryId ) indexToDelete = i;
});
int deleteId = this.categoryData.user[indexToDelete].id;
this.categoryData.user.removeAt(indexToDelete);
filterCategory = null;
categoryProvider.delete( deleteId );
}
}
deleteCategoryGroup( groupId ){
if( groupId != null ){
List<Category> toDelete = [];
this.categoryData.user.forEach( (category){
if( category != null &&
category.groupId == groupId){
toDelete.add(category);
}
});
toDelete.forEach( (category){
deleteCategory(category.id);
});
int indexToDelete = -1;
this.categoryData.userGroups.asMap().forEach( (i, catGr){
if( catGr.id == groupId ) indexToDelete = i;
});
int deleteId = this.categoryData.userGroups[indexToDelete].id;
this.categoryData.userGroups.removeAt(indexToDelete);
filterCategory = null;
categoryGroupProvider.delete( deleteId );
}
}
updateCategoryName( newValue ){
this.categoryData.getCategory( filterCategoryId ).text = newValue;
this.tasksData.forEach((task) {
if (task != null &&
task.category != null &&
task.category.id == filterCategoryId)
task.category.text = newValue;
taskProvider.update(task);
});
}
updateGroupName( groupId, newGroupName ){
CategoryGroup group = this.categoryData.getGroup(groupId);
group.text = newGroupName;
categoryGroupProvider.update(group);
}
toggleTask( Task task ) {
tasksData.elementAt( tasksData.indexOf( task ) ).completed = task.completed;
taskProvider.update(task.clone());
task.completed ? _update_category_count(task, -1) : _update_category_count(task, 1);
if( task.completed )
notifications.cancelReminder( task.clone() );
else
notifications.updateReminder( task.clone() );
}
addTask( Task task ){
Task newTaskC = task.clone();
taskProvider.insert(newTaskC);
tasksData.add(newTaskC);
if(! newTaskC.completed )
notifications.addReminder(newTaskC);
_update_category_count(newTaskC, 1);
newTask = new Task();
newTask.id = tasksData.length == 0 ? 1 : tasksData.last.id + 1;
newTask.completed = false;
}
updateTask( Task task ) {
if (tasksData.indexOf(task) < 0) {
addTask( task );
} else {
Task dirtyData = tasksData.elementAt(tasksData.indexOf(task));
if( dirtyData.completed != task.completed ) {
if( dirtyData.category.text == task.category.text ) {
if (task.completed)
_update_category_count(task, -1);
else
_update_category_count(task, 1);
} else {
if (task.completed) {
_update_category_count(task, -1);
_update_category_count(dirtyData, 1);
} else {
_update_category_count(task, 1);
_update_category_count(dirtyData, -1);
}
}
} else if( !dirtyData.completed && !task.completed ){
_update_category_count(dirtyData, -1);
_update_category_count(task, 1);
}
dirtyData.title = task.title;
dirtyData.category = task.category;
dirtyData.deadline_val = task.deadline_val;
dirtyData.reminder_date = task.reminder_date;
dirtyData.reminder_time = task.reminder_time;
dirtyData.completed = task.completed;
dirtyData.repeat = task.repeat;
dirtyData.notes = task.notes;
taskProvider.update(task.clone());
notifications.updateReminder(dirtyData);
}
}
_update_category_count( Task task, int change ) {
//print( "category:" + task.category.text + ", change:" + change.toString() );
categoryData.user.forEach( (category) {
if( category.text == task.category.text ) {
category.count += change;
categoryProvider.update(category.clone());
}
}
);
}
deleteSelectedTask() {
this.selectedTaskId.forEach( (id) =>
deleteTask(
tasksData.firstWhere( (_task) => _task.id == id )
)
);
}
deleteTask(Task task) {
tasksData.remove( task );
taskProvider.delete( task.id );
if(! task.completed ) {
notifications.cancelReminder(newTask);
_update_category_count(task.clone(), -1);
}
}
List<Task> get todayTasks {
return tasksData
.where( (task) => task.deadline_val == DateUtil.parse( DateUtil.today ) )
.toList();
}
List<Task> get dueTasks {
return tasksData
.where( (task) => task.isDue && task.deadline_val != DateUtil.parse( DateUtil.today ) )
.toList();
}
List<Task> get pendingTasks {
return tasksData
.where( (task) => !task.isDue && !task.completed )
.toList();
}
bool get showFab {
return isCached && filterCategory != null ;
}
Future<bool> updateShowCompletedTasks() async {
tasksData = ( showCompletedTasks == null || showCompletedTasks == true ) ?
await taskProvider.allTasks( categoryData ):
await taskProvider.allTasksPending( categoryData );
return true;
}
Future<bool> reset_category_counts() async {
categoryData.user.forEach( (category) async {
var cntCate = tasksData.where( (task) => task.category.id == category.id ).length;
if( cntCate != category.count ){
category.count = cntCate;
await categoryProvider.update( category );
}
});
return true;
}
Future<bool> clean_all() async {
categoryData.clear();
await categoryProvider.delete_all();
await categoryGroupProvider.delete_all();
add_default_userlists();
tasksData.clear();
await taskProvider.delete_all();
await notifications.cancelAll();
return true;
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/NotificationManager.dart
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_local_notifications/initialization_settings.dart';
import 'package:flutter_local_notifications/notification_details.dart';
import 'package:flutter_local_notifications/platform_specifics/android/initialization_settings_android.dart';
import 'package:flutter_local_notifications/platform_specifics/android/notification_details_android.dart';
import 'package:flutter_local_notifications/platform_specifics/ios/initialization_settings_ios.dart';
import 'package:flutter_local_notifications/platform_specifics/ios/notification_details_ios.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:clean_todo/lists/TasksPage.dart';
import 'package:clean_todo/beans/Task.dart';
import 'package:clean_todo/calender/TimeUtil.dart';
import 'dart:typed_data';
import 'package:clean_todo/data/NotificationProvider.dart';
import 'package:clean_todo/beans/Notification.dart';
import 'package:clean_todo/calender/DateUtil.dart';
import 'dart:convert';
import 'package:clean_todo/detail/TaskDetail.dart';
import 'package:clean_todo/data/DataCache.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/settings/Themes.dart';
import 'package:clean_todo/settings/SettingsManager.dart';
enum CTRepeatInterval { NONE, DAILY, WEEKLY, WEEKDAYS, WEEKENDS, MONTHLY }
class NotificationManager {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
NotificationDetails platformChannelSpecifics;
BuildContext context;
NotificationProvider notificationProvider = new NotificationProvider();
CategoryData categoryData ;
DataCache cache ;
init( context, CategoryData pCategoryData, DataCache pCache ) {
this.cache = pCache;
this.categoryData = pCategoryData;
// initialise the plugin
InitializationSettingsAndroid initializationSettingsAndroid = new InitializationSettingsAndroid('notification');
InitializationSettingsIOS initializationSettingsIOS = new InitializationSettingsIOS();
InitializationSettings initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings, selectNotification: onSelectNotification);
var vibrationPattern = new Int64List(4);
vibrationPattern[0] = 0;
vibrationPattern[1] = 1000;
vibrationPattern[2] = 5000;
vibrationPattern[3] = 2000;
NotificationDetailsAndroid androidPlatformChannelSpecifics =
new NotificationDetailsAndroid(
'com.babanomania.cleantodo',
'Task Reminders',
'reminders to keep you motivated for the tasks',
icon: 'notification',
playSound: true,
sound: 'slow_spring_board',
enableVibration: true,
vibrationPattern: vibrationPattern
);
NotificationDetailsIOS iOSPlatformChannelSpecifics = new NotificationDetailsIOS();
platformChannelSpecifics =
new NotificationDetails(
androidPlatformChannelSpecifics,
iOSPlatformChannelSpecifics
);
}
Future onSelectNotification(String payload) async {
if( payload != null ){
Task task = Task.fromMap( json.decode( payload ), this.categoryData );
DataCache thisCache = new DataCache();
SettingsManager settings = new SettingsManager();
await settings.init();
await thisCache.initDb( settings.showCompleted );
await thisCache.initNotifications(null);
runApp(
new MaterialApp(
theme: Themes.get( settings.theme ),
home: new TaskDetail(
task: task,
updateTask: (taskU) => thisCache.updateTask(taskU),
categoryData: thisCache.categoryData,
exitApp: true,
),
)
);
} else {
await Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new TasksPage()),
);
}
}
addReminder( Task task ) async {
DateTime targetDateTime = _getTargetDate(task);
if( targetDateTime == null || task.completed ){
return;
}
bool isTargetFuture = targetDateTime.isAfter( DateUtil.today );
DateTime deadline = task.deadline_val == null ? null : DateTime.parse( task.deadline_val );
if( task.repeat == null || task.repeat == CTRepeatInterval.NONE.index ) {
if (isTargetFuture) {
int newId = await _newId();
await notificationProvider.insert( new NotificationData( id: newId, taskId: task.id ) );
await flutterLocalNotificationsPlugin.schedule(
newId,
task.title,
'Incomplete Task Reminder',
targetDateTime,
platformChannelSpecifics,
payload: json.encode( task.toMap() ),
);
}
} else if ( deadline == null ){
//this is absurd
return ;
} else if( task.repeat == CTRepeatInterval.DAILY.index ){
int newId = await _newId();
await notificationProvider.insert( new NotificationData( id: newId, taskId: task.id ) );
await flutterLocalNotificationsPlugin.periodicallyShowTill(
newId,
task.title,
'Incomplete Task Reminder',
isTargetFuture ? targetDateTime : DateUtil.today,
deadline,
RepeatInterval.Daily,
platformChannelSpecifics,
payload: json.encode( task.toMap() ),
);
} else if( task.repeat == CTRepeatInterval.WEEKLY.index ){
int newId = await _newId();
await notificationProvider.insert( new NotificationData( id: newId, taskId: task.id ) );
await flutterLocalNotificationsPlugin.periodicallyShowTill(
newId,
task.title,
'Incomplete Task Reminder',
isTargetFuture ? targetDateTime : DateUtil.today,
deadline,
RepeatInterval.Weekly,
platformChannelSpecifics,
payload: json.encode( task.toMap() ),
);
} else if( task.repeat == CTRepeatInterval.WEEKDAYS.index ){
List<DateTime> days = _getWeekdays( isTargetFuture ? targetDateTime : DateUtil.today, deadline );
int newId = await _newId();
days.asMap().forEach( (i, targetDT) async {
int newerId = newId + i;
await notificationProvider.insert( new NotificationData( id: newerId, taskId: task.id ) );
await flutterLocalNotificationsPlugin.periodicallyShowTill(
newerId,
task.title,
'Incomplete Task Reminder',
targetDT,
deadline,
RepeatInterval.Weekly,
platformChannelSpecifics,
payload: json.encode( task.toMap() ),
);
});
} else if( task.repeat == CTRepeatInterval.WEEKENDS.index ){
List<DateTime> days = _getWeekends( isTargetFuture ? targetDateTime : DateUtil.today, deadline );
int newId = await _newId();
days.asMap().forEach( (i, targetDT) async {
int newerId = newId + i;
await notificationProvider.insert( new NotificationData( id: newerId, taskId: task.id ) );
await flutterLocalNotificationsPlugin.periodicallyShowTill(
newerId,
task.title,
'Incomplete Task Reminder',
targetDT,
deadline,
RepeatInterval.Weekly,
platformChannelSpecifics,
payload: json.encode( task.toMap() ),
);
});
} else if( task.repeat == CTRepeatInterval.MONTHLY.index ){
List<DateTime> days = _getMonthDays( targetDateTime, deadline );
int newId = await _newId();
days.asMap().forEach( (i, targetDT)async {
int newerId = newId + i;
await notificationProvider.insert( new NotificationData( id: newerId, taskId: task.id ) );
await flutterLocalNotificationsPlugin.schedule(
newerId,
task.title,
'Incomplete Task Reminder',
targetDT,
platformChannelSpecifics,
payload: json.encode( task.toMap() ),
);
});
}
}
DateTime _getTargetDate( Task task ){
if( task.reminder_date != null && task.reminder_time != null ) {
DateTime targetDate = DateTime.parse(task.reminder_date);
TimeOfDay targetTime = TimeUtil.parse_back(task.reminder_time);
return targetDate
.add(new Duration(hours: targetTime.hour))
.add(new Duration(minutes: targetTime.minute));
} else {
return null;
}
}
Future<bool> cancelReminder( Task task ) async {
List<NotificationData> notifications = await notificationProvider.getNotificationsForTask( task.id );
notifications.forEach( (notification) async {
await flutterLocalNotificationsPlugin.cancel( notification.id );
await notificationProvider.delete( notification );
});
return true;
}
Future<bool> cancelAll() async {
await flutterLocalNotificationsPlugin.cancelAll();
await notificationProvider.delete_all();
return true;
}
updateReminder( Task task ) async {
await cancelReminder( task );
await addReminder( task );
}
Future<int> _newId() async {
int maxId = await notificationProvider.getMaxId();
return maxId + 1;
}
List<DateTime> _getWeekdays( DateTime start, DateTime end ){
List<DateTime> calculated = [];
for( int i = 0; i < 7 ; i++ ){
DateTime newDT2 = start.add( new Duration( days: i ) );
if( newDT2.weekday != 6 && newDT2.weekday != 7 ){
calculated.add( newDT2 );
}
}
return calculated;
}
List<DateTime> _getWeekends( DateTime start, DateTime end ){
List<DateTime> calculated = [];
for( int i = 0; i < 7 ; i++ ){
DateTime newDT2 = start.add( new Duration( days: i ) );
if( newDT2.weekday == 6 || newDT2.weekday == 7 ){
calculated.add( newDT2 );
}
}
return calculated;
}
List<DateTime> _getMonthDays( DateTime start, DateTime end ){
List<DateTime> calculated = [];
var idx = 0;
DateTime newDT = new DateTime( start.year, start.month, start.day, start.hour, start.minute );
while( newDT.isBefore( end ) || !newDT.isAtSameMomentAs( end ) ){
DateTime newDT2 = new DateTime( newDT.year, newDT.month + idx, newDT.day, newDT.hour, newDT.minute );
calculated.add( newDT2 );
idx += 1;
}
return calculated;
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/NotificationProvider.dart
|
import 'dart:async';
import 'dart:io' as io;
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:clean_todo/beans/Notification.dart';
class NotificationProvider {
static final String table = "notifications";
static final String columnId = "_id";
static final String columnTaskId = "taskId";
Database _db;
Future<Database> get db async {
if(_db != null)
return _db;
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "CleanToDoNotifications.db");
await documentsDirectory.create(recursive: true);
var theDb = await openDatabase(
path,
version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
create table $table (
$columnId integer primary key autoincrement,
$columnTaskId integer
)
''');
}
);
return theDb;
}
Future<List<NotificationData>> allNotifications() async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnTaskId]
);
List<NotificationData> allNotifications = [];
maps.forEach(
(mapItem) => allNotifications.add( NotificationData.fromMap(mapItem) )
);
return allNotifications;
}
insert(NotificationData notification) async {
var dbClient = await db;
await dbClient.insert(table, notification.toMap());
}
delete(NotificationData notification) async {
var dbClient = await db;
await dbClient.delete(
table,
where: "$columnId = ?",
whereArgs: [notification.id]
);
}
delete_all() async {
var dbClient = await db;
await dbClient.delete( table, where: "1", );
}
Future<int> getMaxId() async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId],
orderBy: columnId + " DESC",
limit: 1
);
return ( maps == null || maps.length == 0 )?
0 : maps.first[columnId];
}
Future<NotificationData> getNotification(int id) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnTaskId],
where: "$columnId = ?",
whereArgs: [id]
);
if (maps.length > 0) {
return new NotificationData.fromMap(maps.first);
}
return null;
}
Future<List<NotificationData>> getNotificationsForTask( int taskId ) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnTaskId],
where: "$columnTaskId = ?",
whereArgs: [taskId]
);
List<NotificationData> notifications = [];
if (maps.length > 0) {
maps.forEach(
(entry) => notifications.add( new NotificationData.fromMap(entry) )
);
}
return notifications;
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/DefaultDataGenerator.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/beans/UserData.dart';
import 'package:clean_todo/beans/Task.dart';
import 'package:clean_todo/data/DataProvider.dart';
class DefaultDataGenerator implements DataProvider {
CategoryData getSidebarData(){
return new CategoryData(
system: [
new Category( id: -1, text: 'My Day', icon: Icons.lightbulb_outline ),
new Category( id: -2, text: 'To-Do', icon: Icons.check ),
],
userGroups: [
new CategoryGroup( id: 1, text: 'Personal' ),
new CategoryGroup( id: 2, text: 'Work' ),
],
user: [
new Category( id: 1, groupId: 1, text: 'Home', count: 3 ),
new Category( id: 2, groupId: 1, text: 'Shopping', count: 2 ),
new Category( id: 3, groupId: 2, text: 'Work', count: 2 ),
],
);
}
UserData getUserData(){
return new UserData( 'Sandra Smith', 'Sandra.Smith@example.com' );
}
List<Task> getAllTasks() {
return [];
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/CategoryProvider.dart
|
import 'dart:async';
import 'dart:io' as io;
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:clean_todo/beans/Category.dart';
class CategoryProvider {
static final String table = "catagory";
static final String columnId = "_id";
static final String columnGroupId = "groupId";
static final String columnText = "text";
static final String columnCount = "count";
Database _db;
Future<Database> get db async {
if(_db != null)
return _db;
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "CleanToDoCategories.db");
await documentsDirectory.create(recursive: true);
var theDb = await openDatabase(
path,
version: 1,
onCreate: (Database db, int version) async {
await db.execute('''
create table $table (
$columnId integer primary key autoincrement,
$columnGroupId integer,
$columnText text not null,
$columnCount integer not null
)
''');
}
);
return theDb;
}
insertAll(List<Category> categories) {
categories.forEach( (category) => insert( category.clone() ) );
}
insert(Category category) async {
var dbClient = await db;
await dbClient.insert(table, category.toMap());
}
Future<Category> getCategory(int id) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnGroupId, columnText, columnCount],
where: "$columnId = ?",
whereArgs: [id]
);
if (maps.length > 0) {
return new Category.fromMap(maps.first);
}
return null;
}
Future<List<Category>> allCategories() async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnGroupId, columnText, columnCount]
);
List<Category> allCategories = [];
maps.forEach(
(mapItem) => allCategories.add( Category.fromMap(mapItem) )
);
return allCategories;
}
Future<Category> getCategoryByText(String text) async {
var dbClient = await db;
List<Map> maps = await dbClient.query(
table,
columns: [columnId, columnGroupId, columnText, columnCount],
where: "$columnText = ?",
whereArgs: [text]
);
if (maps.length > 0) {
return new Category.fromMap(maps.first);
}
return null;
}
delete(int id) async {
var dbClient = await db;
await dbClient.delete(table, where: "$columnId = ?", whereArgs: [id]);
}
delete_all() async {
var dbClient = await db;
await dbClient.delete(table, where: "1");
}
update(Category category) async {
var dbClient = await db;
await dbClient.update(
table,
category.toMap(),
where: "$columnId = ?", whereArgs: [category.id]
);
}
Future close() async => _db.close();
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/data/FakeDataGenerator.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/beans/CategoryData.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/beans/UserData.dart';
import 'package:clean_todo/beans/Task.dart';
import 'package:clean_todo/data/DataProvider.dart';
import 'package:clean_todo/calender/DateUtil.dart';
import 'package:clean_todo/calender/DateToString.dart';
import 'package:clean_todo/data/NotificationManager.dart';
class FakeDataGenerator implements DataProvider {
CategoryData getSidebarData(){
return new CategoryData(
system: [
new Category( id: -1, groupId: -1, text: 'My Day', icon: Icons.lightbulb_outline ),
new Category( id: -2, groupId: -1, text: 'To-Do', icon: Icons.check ),
],
userGroups: [
new CategoryGroup( id: 1, text: 'Personal' ),
new CategoryGroup( id: 2, text: 'Work' ),
],
user: [
new Category( id: 1, groupId: 1, text: 'Home', count: 3 ),
new Category( id: 2, groupId: 1, text: 'Shopping', count: 2 ),
new Category( id: 3, groupId: 2, text: 'Work', count: 2 ),
],
);
}
UserData getUserData(){
return new UserData( 'John Doe', 'John.Doe@example.com' );
}
List<Task> getAllTasks(){
String yesterday = '20180505';
String today = DateUtil.parse( DateToString.today );
String tomorrow = DateUtil.parse( DateToString.tomorrow );
String next_week = DateUtil.parse( DateToString.next_week );
return [
new Task( id : 0, completed : false, title: 'fix the lightbulb', category: new Category( id: 1, groupId: 1, text: 'Home' ) , deadline_val: yesterday, reminder_date: '20190519', reminder_time: '0900', notes: 'yes', repeat: CTRepeatInterval.WEEKLY.index ),
new Task( id : 1, completed : false, title: 'clean the garden', category: new Category( id: 1, groupId: 1, text: 'Home'), repeat: CTRepeatInterval.NONE.index ),
new Task( id : 2, completed : false, title: 'fix the fire hose', category: new Category( id: 1, groupId: 1, text: 'Home' ), deadline_val: next_week, reminder_date: '20190520', reminder_time: '0900', repeat: CTRepeatInterval.NONE.index ),
new Task( id : 3, completed : true, title: 'finish the annual reports', category: new Category( id: 3, groupId: 2, text: 'Work' ), repeat: CTRepeatInterval.NONE.index ),
new Task( id : 4, completed : false, title: 'come up with ideas for the pre-sales task', category: new Category( id: 3, groupId: 2, text: 'Work' ), deadline_val: next_week, repeat: CTRepeatInterval.NONE.index ),
new Task( id : 5, completed : false, title: 'buy ring for aniversary', category: new Category( id: 2, groupId: 1, text: 'Shopping' ), repeat: CTRepeatInterval.NONE.index ),
new Task( id : 6, completed : false, title: 'buy shirts for presentation', category: new Category( id: 2, groupId: 1, text: 'Shopping' ), reminder_date: '20190522', reminder_time: '0900', repeat: CTRepeatInterval.NONE.index ),
];
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/styles/AppIcons.dart
|
import 'package:flutter/material.dart';
class AppIcons {
Color _iconColor( context ){
return Theme.of(context).iconTheme.color;
}
newGroupIcon( context ) =>
new Icon( Icons.create_new_folder, color: _iconColor(context), );
groupIcon( context ) =>
new Icon( Icons.folder, color: _iconColor(context), );
groupOpenIcon( context ) =>
new Icon( Icons.folder_open, color: _iconColor(context), );
groupArrowIcon( context ) =>
new Icon( Icons.keyboard_arrow_down, color: _iconColor(context) );
groupOpenArrowIcon( context ) =>
new Icon( Icons.keyboard_arrow_right, color: _iconColor(context), );
newListIcon( context ) =>
new Icon( Icons.add, color: _iconColor(context), );
systemIcon( IconData icon, context ) =>
new Icon( icon, color: _iconColor(context), );
listIcon( context ) =>
new Icon( Icons.list, color: _iconColor(context), );
taskCompletedIcon( selected, context ) =>
new CircleAvatar(
child: new Icon( Icons.check, color: selected ? Theme.of(context).highlightColor : Theme.of(context).scaffoldBackgroundColor, size: 14.0, ),
backgroundColor: _iconColor(context),
radius: 12.0,
);
taskPendingIcon( selected, context ) =>
new Icon( Icons.radio_button_unchecked, size: 28.0, color: selected ? Theme.of(context).highlightColor : _iconColor(context), );
var listIconSize = 14.0;
listIconDue( selected, context, isDue ) =>
new Icon( Icons.calendar_today,
color: selected ? Theme.of(context).highlightColor :
( isDue ? Theme.of(context).errorColor : _iconColor(context) ), size: listIconSize, );
listIconReminder( selected, context ) =>
new Icon( Icons.alarm_on, color: selected ? Theme.of(context).highlightColor : _iconColor(context), size: listIconSize, );
listIconNotes( selected, context ) =>
new Icon( Icons.chat_bubble_outline, color: selected ? Theme.of(context).highlightColor : _iconColor(context), size: listIconSize, );
listIconRepeat( selected, context ) =>
new Icon( Icons.repeat, color: selected ? Theme.of(context).highlightColor : _iconColor(context), size: listIconSize, );
newTaskModal( context ) =>
new Icon( Icons.radio_button_unchecked, size: 28.0, color: _iconColor(context), );
newTaskModalArrow( context ) =>
new CircleAvatar( child: new Icon( Icons.keyboard_arrow_right, color: Colors.white,), backgroundColor: Theme.of(context).primaryColorLight, );
newTaskFabIcon(context) =>
new Icon(Icons.add);
reCaluclateCountsIcon(context) =>
new Icon( Icons.format_list_numbered );
noTasksIcon(context) =>
new Icon( Icons.list, size: 150.0, color: _iconColor(context).withAlpha( 70 ), );
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/beans/UserData.dart
|
class UserData {
String userName;
String email;
String abbr;
UserData( String pUsername, String pEmail ){
this.userName = pUsername;
this.email = pEmail;
if( userName == null ){
abbr = null;
} else {
List<String> userNameLst = userName.split(" ");
if (userNameLst.length == 1) {
abbr = userName.substring(0, 1).toUpperCase();
} else {
abbr = userNameLst.first.substring(0, 1).toUpperCase() +
userNameLst.last.substring(0, 1).toUpperCase();
}
}
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/beans/Notification.dart
|
import 'package:clean_todo/data/NotificationProvider.dart';
class NotificationData {
NotificationData({ this.id, this.taskId });
int id;
int taskId;
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
NotificationProvider.columnId: id,
NotificationProvider.columnTaskId: taskId,
};
return map;
}
NotificationData.fromMap( Map map ) {
id = map[NotificationProvider.columnId];
taskId = map[NotificationProvider.columnTaskId];
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/beans/CategoryData.dart
|
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/beans/CategoryGroup.dart';
class CategoryData {
CategoryData({ this.system, this.userGroups, this.user });
List<Category> system = [];
List<CategoryGroup> userGroups = [];
List<Category> user = [];
CategoryGroup newCategoryGroup = new CategoryGroup( id: -1 );
bool newGroup = false;
List<Category> getGroupMembers ( CategoryGroup group ){
List<Category> groupCategories = user.map( (userCategory) {
if( userCategory.groupId == group.id ){
return userCategory;
}
}).toList();
groupCategories.removeWhere( (category) => category == null );
return groupCategories;
}
CategoryGroup getCategoryGroupReal( int groupId ){
return userGroups.where( (categoryGroup) => categoryGroup.id == groupId ).first;
}
Category getCategory( int categoryId ){
if( categoryId == null )
return null;
return user.where( (category) => category.id == categoryId ).first;
}
CategoryGroup getCategoryGroup( int categoryId ){
if( categoryId == null )
return null;
Category category = getCategory(categoryId);
return userGroups.where( (categoryGroup) => categoryGroup.id == category.groupId ).first;
}
CategoryGroup getGroup( int groupId ){
if( groupId == null )
return null;
return userGroups.where( (categoryGroup) => categoryGroup.id == groupId ).first;
}
clear(){
userGroups.clear();
user.clear();
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/beans/Category.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/data/CategoryProvider.dart';
class Category {
Category ({ this.id, this.groupId, this.text, this.icon, this.count });
int id;
int groupId;
String text ;
IconData icon ;
int count ;
Category clone(){
return new Category( id: id, groupId: this.groupId, text: text, icon: icon, count: count );
}
int get hashCode => ( groupId.toString() + "_" + text ).hashCode;
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
CategoryProvider.columnId: id,
CategoryProvider.columnGroupId: groupId,
CategoryProvider.columnText: text,
CategoryProvider.columnCount: count
} ;
return map;
}
Category.fromMap(Map map) {
id = map[CategoryProvider.columnId];
groupId = map[CategoryProvider.columnGroupId];
text = map[CategoryProvider.columnText];
count = map[CategoryProvider.columnCount];
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/beans/CategoryGroup.dart
|
import 'package:clean_todo/data/CategoryGroupProvider.dart';
class CategoryGroup {
int id;
String text ;
bool isExpanded ;
CategoryGroup({ this.id, this.text, this.isExpanded = true });
CategoryGroup clone(){
return new CategoryGroup( id: id, text: text, isExpanded: isExpanded );
}
int get hashCode => text.hashCode;
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
CategoryGroupProvider.columnId: id,
CategoryGroupProvider.columnText: text,
} ;
return map;
}
CategoryGroup.fromMap(Map map) {
id = map[CategoryGroupProvider.columnId];
text = map[CategoryGroupProvider.columnText];
isExpanded = true;
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/beans/Task.dart
|
import 'package:clean_todo/beans/Category.dart';
import 'package:clean_todo/calender/DateUtil.dart';
import 'package:clean_todo/data/TaskProvider.dart';
import 'package:clean_todo/beans/CategoryData.dart';
class Task {
Task({ this.id, this.completed, this.title, this.category,
this.deadline_val, this.reminder_date, this.reminder_time,
this.repeat, this.notes });
int id;
bool completed ;
String title ;
Category category ;
get deadline{
return DateUtil.detect_desc( deadline_val );
}
String deadline_val ;
get reminder {
if( reminder_date == null ) return null;
else return DateUtil.detect_desc( reminder_date ) + ' @ ' + reminder_time;
}
String reminder_date ;
String reminder_time ;
int repeat ;
String notes ;
bool get isDue{
if( completed )
return false;
else if ( deadline_val == null )
return false;
else if ( DateTime.parse( deadline_val ).isBefore( DateUtil.tomorrow ) )
return true;
else
return false;
}
copy( Task from ){
this.id = from.id;
this.title = from.title;
this.completed = from.completed;
this.category = from.category.clone();
this.deadline_val = from.deadline_val;
this.reminder_date = from.reminder_date;
this.reminder_time = from.reminder_time;
this.repeat = from.repeat;
this.notes = from.notes;
}
clear(){
this.id = null;
this.title = null;
this.completed = false;
this.category = null;
this.deadline_val = null;
this.reminder_date = null;
this.reminder_time = null;
this.repeat = null;
this.notes = null;
}
Task clone(){
return new Task( id: id,
title: title,
completed: completed,
category: category.clone(),
deadline_val: deadline_val,
reminder_date: reminder_date,
reminder_time: reminder_time,
repeat: repeat,
notes: notes,
);
}
bool operator ==(o) => o.id == this.id;
int get hashCode => this.id.toString().hashCode;
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
//TaskProvider.columnId: id,
TaskProvider.columnTitle: title,
TaskProvider.columnCompleted: completed == true ? 1 : 0,
TaskProvider.columnCategoryId: category.id,
TaskProvider.columnDeadlineVal: deadline_val,
TaskProvider.columnReminderDate: reminder_date,
TaskProvider.columnReminderTime: reminder_time,
TaskProvider.columnRepeat: repeat,
TaskProvider.columnNotes: notes,
};
if (id != null) {
map[TaskProvider.columnId] = id;
}
//print( "map => " + map.type.reflectedType.toString() );
return map;
}
Task.fromMap( Map map, CategoryData categoryData ) {
id = map[TaskProvider.columnId];
title = map[TaskProvider.columnTitle];
completed = map[TaskProvider.columnCompleted] == 1;
category = categoryData.getCategory( map[TaskProvider.columnCategoryId] );
deadline_val = map[TaskProvider.columnDeadlineVal];
reminder_date = map[TaskProvider.columnReminderDate];
reminder_time = map[TaskProvider.columnReminderTime];
repeat = map[TaskProvider.columnRepeat];
notes = map[TaskProvider.columnNotes];
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/calender/TimeUtil.dart
|
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class TimeUtil {
static get now {
return new TimeOfDay.now();
}
static get reminder_time_val{
if( (new TimeOfDay.now()).hour > 9 ){
return '21:00';
} else {
return '09:00';
}
}
static get reminder_time{
if( (new TimeOfDay.now()).hour > 9 ){
return '21';
} else {
return '09';
}
}
static parse( TimeOfDay val ){
return val.hour.toString().padLeft(2, '0') +
':' +
val.minute.toString().padLeft(2, '0');
}
static TimeOfDay parse_string( String val ){
//print( "parsing -" + val + " ~ part1:" + val.substring(0,2) + " ~ part2:" + val.substring(3,5) );
return new TimeOfDay( hour: int.parse(val.substring(0,2)),
minute: int.parse(val.substring(3,5))
);
}
static TimeOfDay parse_back( String val ){
return parse_string(val);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/calender/DateToString.dart
|
class DateToString {
static final DateTime today = new DateTime.now();
static final DateTime tomorrow = new DateTime.now().add( new Duration( days: 1 ) );
static final DateTime next_week = new DateTime.now().add( new Duration( days: 7 ) );
static parse( DateTime pVar ){
if( pVar == today ) return 'Today';
else if ( pVar == tomorrow ) return 'Tomorrow';
else if ( pVar == next_week ) return 'Next Week';
else return 'Unknown';
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/calender/DateUtil.dart
|
import "package:intl/intl.dart";
class DateUtil {
static DateTime get today{
DateTime timeIsNow = new DateTime.now();
return new DateTime( timeIsNow.year, timeIsNow.month, timeIsNow.day, 0, 0, 0, 0, 0 );
}
static get tomorrow{
DateTime timeIsNow = new DateTime.now().add( new Duration(days: 1) );
return new DateTime( timeIsNow.year, timeIsNow.month, timeIsNow.day, 0, 0, 0, 0, 0 );
}
static get yesterday{
DateTime timeIsNow = new DateTime.now().add( new Duration(days: -1) );
return new DateTime( timeIsNow.year, timeIsNow.month, timeIsNow.day, 0, 0, 0, 0, 0 );
}
static get next_week{
DateTime timeIsNow = new DateTime.now();
int daysToNextMonday = 8 - timeIsNow.weekday;
timeIsNow = timeIsNow.add( new Duration(days: daysToNextMonday) );
return new DateTime( timeIsNow.year, timeIsNow.month, timeIsNow.day, 0, 0, 0, 0, 0 );
}
static get last_week_start{
DateTime timeIsNow = new DateTime.now();
int daysToNextMonday = 8 - timeIsNow.weekday;
timeIsNow = timeIsNow.add( new Duration(days: daysToNextMonday) );
DateTime timeWeekStart = timeIsNow.subtract( new Duration( days: 14 ) );
return new DateTime( timeWeekStart.year, timeWeekStart.month, timeWeekStart.day, 0, 0, 0, 0, 0 );
}
static get last_week_end{
DateTime timeIsNow = new DateTime.now();
int daysToNextMonday = 8 - timeIsNow.weekday;
timeIsNow = timeIsNow.add( new Duration(days: daysToNextMonday) );
DateTime timeWeekEnd = timeIsNow.subtract( new Duration( days: 8 ) );
return new DateTime( timeWeekEnd.year, timeWeekEnd.month, timeWeekEnd.day, 0, 0, 0, 0, 0 );
}
static parse( DateTime val ){
return val.year.toString() +
val.month.toString().padLeft(2, '0') +
val.day.toString().padLeft(2, '0') ;
}
static format( DateTime val ){
return new DateFormat( DateFormat.ABBR_MONTH_DAY ).format( val );
}
static parse_string( String val ){
if( val != null && val.startsWith('Due ') ){
val = val.replaceFirst( 'Due ', '');
}
if( 'Later Today' == val ) {
return parse(today);
}else if( 'Today' == val ){
return parse( today );
} else if( 'Tomorrow' == val ) {
return parse(tomorrow);
}else if( 'Yesterday' == val ){
return parse( yesterday );
} else if( 'Next Week' == val ){
return parse( next_week );
} else {
return val;
}
}
static detect_desc( String formatted ){
if( parse( today ) == formatted ){
return 'Today';
} else if( parse( tomorrow) == formatted ){
return 'Tomorrow';
} else if( parse( yesterday ) == formatted ){
return 'Yesterday';
} else if( parse( next_week) == formatted ){
return 'Next Week';
} else if ( formatted != null ){
return format( DateTime.parse( formatted ) );
} else {
return null;
}
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/settings/InitManager.dart
|
import 'package:clean_todo/settings/SettingsManager.dart';
import 'package:clean_todo/data/DataCache.dart';
import 'package:clean_todo/data/DefaultDataGenerator.dart';
import 'package:clean_todo/data/DataProvider.dart';
import 'package:clean_todo/beans/UserData.dart';
import 'dart:async';
import 'package:clean_todo/data/FakeDataGenerator.dart';
import 'package:quick_actions/quick_actions.dart';
class InitManager {
SettingsManager settings;
DataCache cache;
static Future<InitManager> getInstance() async {
InitManager init = new InitManager();
init.settings = new SettingsManager();
init.cache = new DataCache();
await init.settings.init();
await init.cache.initDb( init.settings.showCompleted );
if( init.settings.showCompleted != null ) {
init.cache.showCompletedTasks = init.settings.showCompleted;
} else {
init.cache.showCompletedTasks = true;
}
if( init.settings.sortString != null ) {
init.cache.sortTasks = init.settings.sortString;
} else {
init.cache.sortTasks = 'SORT_BY_CREA';
}
if( init.isSignedIn ) {
init.cache.userData = new UserData(init.settings.username, init.settings.email);
} else {
DataProvider provider = new DefaultDataGenerator();
init.cache.userData = provider.getUserData();
}
init.cache.isCached = true;
bool demoMode = false;
if( demoMode ) {
DataProvider mockProvider = new FakeDataGenerator();
init.cache.tasksData = mockProvider.getAllTasks();
init.cache.userData = mockProvider.getUserData();
init.cache.categoryData = mockProvider.getSidebarData();
}
return init;
}
bool get isSignedIn {
return (
( settings.username != null && settings.username.length > 0 ) ||
settings.isLoggedIn
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/settings/LoginScreen.dart
|
import 'package:flutter/material.dart';
import 'package:clean_todo/data/DataCache.dart';
import 'package:clean_todo/settings/SettingsManager.dart';
import 'package:clean_todo/settings/Themes.dart';
import 'package:clean_todo/lists/TasksPage.dart';
import 'package:clean_todo/beans/UserData.dart';
class LoginScreen extends StatelessWidget {
DataCache cache;
SettingsManager settings;
LoginScreen({this.settings, this.cache});
bool autoValidate = false;
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>(debugLabel: 'inputForm');
_handleEmailLogin(context, name, email) {
final FormState form = _formKey.currentState;
if (form.validate()) {
settings.username = name;
settings.email = email;
settings.isLoggedIn = true;
cache.userData = new UserData(name, email);
runApp(
new MaterialApp(
theme: Themes.get(settings.theme),
home: new TasksPage(
settings: this.settings, cache: this.cache),
),
);
/*
Navigator.of(context).push(
new MaterialPageRoute(
builder: (_) => new MaterialApp(
theme: Themes.get(settings.theme),
home: new TasksPage(
settings: this.settings, cache: this.cache),
)),
);
*/
}
}
_handleNoLogin(context) {
settings.username = null;
settings.email = null;
settings.isLoggedIn = true;
cache.userData = new UserData(null, null);
runApp(
new MaterialApp(
theme: Themes.get(settings.theme),
home: new TasksPage(
settings: this.settings, cache: this.cache),
),
);
/*
Navigator.of(context).push(
new MaterialPageRoute(
builder: (_) => new MaterialApp(
theme: Themes.get(settings.theme),
home: new TasksPage(
settings: this.settings, cache: this.cache),
)),
);
*/
}
@override
Widget build(BuildContext context) {
TextEditingController tecEmail = new TextEditingController();
TextEditingController tecName = new TextEditingController();
TextStyle brandLight =
new TextStyle(
color: Colors.blue,
fontSize: 38.0,
fontWeight: FontWeight.w200);
TextStyle brandBold =
new TextStyle(
color: Colors.blue,
fontSize: 30.0,
fontWeight: FontWeight.normal);
TextStyle lightSmall =
new TextStyle(
color: Colors.grey,
decoration: TextDecoration.none,
fontSize: 20.0);
return new MaterialApp(
home: new Builder(builder: (BuildContext bodyContext) {
return new Scaffold(
body: new Form(
key: _formKey,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text( 'Welcome to', style: brandLight ),
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Image.asset( 'images/logo.png', height: 30.0, ),
new Padding(
padding: new EdgeInsets.only(left: 10.0),
child: new Text( 'Clean To-Do', style: brandBold ),
),
],
),
new Padding(
padding: new EdgeInsets.only( top: 20.0, left: 50.0, right: 50.0, ),
child: new TextFormField(
decoration: new InputDecoration(
labelText: 'Email',
),
controller: tecEmail,
autovalidate: autoValidate,
keyboardType: TextInputType.emailAddress,
validator: (valueEmail) {
if (valueEmail.isEmpty) {
return 'please enter your email';
}
},
),
),
new Padding(
padding: new EdgeInsets.only( top: 20.0, bottom: 75.0, left: 50.0, right: 50.0, ),
child: new TextFormField(
decoration: new InputDecoration(
labelText: 'Name',
),
controller: tecName,
autovalidate: autoValidate,
validator: (valueName) {
if (valueName.isEmpty) {
return 'please enter your name';
}
},
)
),
new RaisedButton(
child: new Text( 'Sign Up', style: new TextStyle(fontSize: 20.0, color: Colors.white), ),
elevation: 5.0,
color: Colors.blue,
padding: new EdgeInsets.only( top: 18.0, bottom: 18.0, left: 80.0, right: 80.0),
onPressed: () => _handleEmailLogin(
bodyContext, tecName.text, tecEmail.text),
),
new Padding(
padding: new EdgeInsets.all( 20.0 ),
),
new FlatButton(
child: new Text( 'skip', style: lightSmall, ),
padding: new EdgeInsets.only( top: 18.0, bottom: 18.0, left: 80.0, right: 80.0),
onPressed: () => _handleNoLogin(bodyContext),
)
],
),
));
}),
);
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/settings/SettingsManager.dart
|
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'package:get_version/get_version.dart';
import 'package:flutter/services.dart';
class SettingsManager {
SharedPreferences prefs ;
String projectVersion;
static Future<SettingsManager> getInstance() async {
SettingsManager newSM = new SettingsManager();
newSM.prefs = await SharedPreferences.getInstance();
return newSM;
}
Future<bool> init() async {
prefs = await SharedPreferences.getInstance();
// Platform messages may fail, so we use a try/catch PlatformException.
try {
projectVersion = await GetVersion.projectVersion;
} on PlatformException {
projectVersion = 'Failed to get project version.';
}
return true;
}
String get theme {
return prefs.get( "theme" );
}
set theme ( String pTheme ){
prefs.setString( "theme" , pTheme );
}
String get email {
return prefs.get( "email" );
}
set email ( String pTheme ){
prefs.setString( "email" , pTheme );
}
String get username {
return prefs.get( "username" );
}
set username ( String pTheme ){
prefs.setString( "username" , pTheme );
}
bool get showCompleted {
return prefs.get( "showCompleted" );
}
set showCompleted ( bool showCompleted ){
prefs.setBool( "showCompleted" , showCompleted );
}
String get sortString {
return prefs.get( "sortString" );
}
set sortString ( String pSortString ){
prefs.setString( "sortString" , pSortString );
}
set notification_sounds ( bool enable ){
prefs.setString( "notification_sounds" , enable ? "true" : "false" );
}
bool get notification_sounds {
return prefs.get( "notification_sounds" ) == null ? true :
prefs.get( "notification_sounds" ).toString() == "true";
}
set notification_vibrations ( bool enable ){
prefs.setString( "notification_vibrations" , enable ? "true" : "false" );
}
bool get notification_vibrations {
return prefs.get( "notification_vibrations" ) == null ? true :
prefs.get( "notification_vibrations" ).toString() == "true";
}
bool get isLoggedIn {
return prefs.get( "isLoggedIn" ) == null ? false :
prefs.get( "isLoggedIn" ).toString() == "true";
}
set isLoggedIn ( bool pIsLoggedIn ){
prefs.setString( "isLoggedIn" , pIsLoggedIn ? "true" : "false" );
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/settings/Themes.dart
|
import 'package:flutter/material.dart';
enum AppColors {
BLUE, INDIGO, CYAN, TEAL,
BROWN, PURPLE, DEEP_PURPLE, AMBER,
RED, PINK, GREY, BLUE_GREY,
BLACK
}
class Themes {
static get( colorId ){
Iterable<AppColors> provided = AppColors.values.where( (AppColors color) => color.index.toString() == colorId );
if( provided == null || provided.length == 0 ) return all[ AppColors.BLUE ];
return all[provided.first];
}
static ThemeData _createTheme( Color primary, Color error ){
return new ThemeData (
primaryColor: primary,
buttonColor: primary,
accentColor: primary,
primaryColorLight: primary,
errorColor: error,
highlightColor: primary.withOpacity( 0.7 ),
iconTheme: new IconThemeData(
color: primary,
),
);
}
static get all {
return {
AppColors.BLUE : _createTheme( Colors.blue, Colors.red ),
AppColors.INDIGO : _createTheme( Colors.indigo, Colors.red ),
AppColors.CYAN : _createTheme( Colors.cyan, Colors.red ),
AppColors.TEAL : _createTheme( Colors.teal, Colors.red ),
AppColors.BROWN : _createTheme( Colors.brown, Colors.red ),
AppColors.PURPLE : _createTheme( Colors.purple, Colors.red ),
AppColors.DEEP_PURPLE : _createTheme( Colors.deepPurple, Colors.red ),
AppColors.AMBER : _createTheme( Colors.amber, Colors.red ),
AppColors.RED : _createTheme( Colors.red, Colors.pink ),
AppColors.PINK : _createTheme( Colors.pink, Colors.red ),
AppColors.GREY : _createTheme( Colors.grey, Colors.red ),
AppColors.BLUE_GREY : _createTheme( Colors.blueGrey, Colors.red ),
AppColors.BLACK : ThemeData.dark().copyWith( accentColor: Colors.white ),
};
}
}
| 0
|
mirrored_repositories/CleanToDO/lib
|
mirrored_repositories/CleanToDO/lib/settings/SplashScreen.dart
|
import 'package:flutter/material.dart';
class SplashScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new DecoratedBox(
decoration: new BoxDecoration(
color: Colors.white,
image: new DecorationImage(
image: new AssetImage('images/logo.png'),
),
),
);
}
}
| 0
|
mirrored_repositories/CleanToDO
|
mirrored_repositories/CleanToDO/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:clean_todo/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(new CleanToDoApp());
// 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/Favorite-Place
|
mirrored_repositories/Favorite-Place/lib/main.dart
|
import 'package:favorite_place/screen/homescreen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
final colorScheme = ColorScheme.fromSeed(
brightness: Brightness.dark,
seedColor: const Color.fromARGB(255, 102, 6, 247),
background: const Color.fromARGB(255, 56, 49, 66),
);
final theme = ThemeData().copyWith(
useMaterial3: true,
scaffoldBackgroundColor: colorScheme.background,
colorScheme: colorScheme,
textTheme: GoogleFonts.ubuntuCondensedTextTheme().copyWith(
titleSmall: GoogleFonts.ubuntuCondensed(
fontWeight: FontWeight.bold,
),
titleMedium: GoogleFonts.ubuntuCondensed(
fontWeight: FontWeight.bold,
),
titleLarge: GoogleFonts.ubuntuCondensed(
fontWeight: FontWeight.bold,
),
),
);
void main() {
runApp(
ProviderScope(child: MyApp()),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Great Places',
theme: theme,
home: const HomeScreen(),
// home: AddPlace(),
);
}
}
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/model/place.dart
|
import 'dart:io';
import 'package:uuid/uuid.dart';
const uuid = Uuid();
class PlaceLocation {
const PlaceLocation(
{required this.latitude, required this.longitude, required this.address});
final double latitude;
final double longitude;
final String address;
}
class Place {
Place({
required this.location,
required this.title,
required this.image,
String? id,
}) : id = id ?? uuid.v4();
final String id;
final String title;
final File image;
final PlaceLocation location;
}
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/screen/places_detail.dart
|
import 'package:favorite_place/model/place.dart';
import 'package:favorite_place/screen/map.dart';
import 'package:flutter/material.dart';
class PlaceDetailScreen extends StatelessWidget {
const PlaceDetailScreen({super.key, required this.place});
final Place place;
String get locationImage {
final lat = place.location.latitude;
final lng = place.location.longitude;
return 'https://maps.googleapis.com/maps/api/staticmap?center=$lat,$lng=&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C$lat,$lng&key=YOUR_API_KEY';
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(place.title)),
body: Stack(children: [
Image.file(
place.image,
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Column(children: [
GestureDetector(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => MapScreen(location: place.location,isSelected: false,),
));
},
child: CircleAvatar(
radius: 70,
backgroundImage: NetworkImage(locationImage),
),
),
Container(
alignment: Alignment.center,
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 16,
),
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.transparent,
Colors.black,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Text(place.location.address,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.titleLarge!.copyWith(
color: Theme.of(context).colorScheme.onBackground)),
)
]),
)
]),
);
}
}
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/screen/addplace.dart
|
import 'dart:io';
import 'package:favorite_place/model/place.dart';
import 'package:favorite_place/provider/user_place.dart';
import 'package:favorite_place/widget/image_input.dart';
import 'package:favorite_place/widget/location_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class AddPlace extends ConsumerStatefulWidget {
const AddPlace({super.key});
@override
ConsumerState<AddPlace> createState() => _AddPlaceState();
}
class _AddPlaceState extends ConsumerState<AddPlace> {
final _titleController = TextEditingController();
File? _selectedImage;
PlaceLocation? _selectedLocation;
void _savePlace() {
final enteredTitel = _titleController.text;
if (enteredTitel.isEmpty || _selectedImage == null || _selectedLocation == null) {
return;
}
ref
.read(UserPlacesProvider.notifier)
.addPlace(enteredTitel, _selectedImage!,_selectedLocation!);
Navigator.of(context).pop();
}
@override
void dispose() {
_titleController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Add new Place')),
body: SingleChildScrollView(
padding: const EdgeInsets.all(10),
child: Column(children: [
TextField(
decoration: const InputDecoration(label: Text('Title')),
controller: _titleController,
style: TextStyle(
color: Theme.of(context).colorScheme.onBackground,
),
),
const SizedBox(height: 20),
ImageInput(
onPickImage: (image) {
_selectedImage = image;
},
),
const SizedBox(height: 20),
LocationInput(
onSelectLocation: (location) {
_selectedLocation = location;
},
),
const SizedBox(height: 20),
ElevatedButton.icon(
onPressed: _savePlace,
icon: const Icon(Icons.add),
label: const Text('Add Place'))
]),
),
);
}
}
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/screen/homescreen.dart
|
import 'package:favorite_place/provider/user_place.dart';
import 'package:favorite_place/screen/addplace.dart';
import 'package:favorite_place/widget/places_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class HomeScreen extends ConsumerStatefulWidget {
const HomeScreen({super.key});
@override
ConsumerState<ConsumerStatefulWidget> createState() {
return _HomeScreenState();
}
}
class _HomeScreenState extends ConsumerState<HomeScreen> {
late Future<void> _placesFuture;
@override
void initState() {
super.initState();
_placesFuture = ref.read(UserPlacesProvider.notifier).loadPlace();
}
@override
Widget build(BuildContext context) {
final userPlaces = ref.watch(UserPlacesProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Your Places'),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const AddPlace(),
));
},
icon: const Icon(Icons.add),
)
],
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: FutureBuilder(
future: _placesFuture,
builder: (context, snapshot) {
return snapshot.connectionState == ConnectionState.waiting
? const Center(
child: CircularProgressIndicator(),
)
: PlacesList(places: userPlaces);
},
),
),
);
}
}
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/screen/map.dart
|
import 'package:favorite_place/model/place.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class MapScreen extends StatefulWidget {
const MapScreen(
{super.key,
this.isSelected = true,
this.location = const PlaceLocation(
latitude: 37.422,
longitude: -122.084,
address: '',
)});
final PlaceLocation location;
final bool isSelected;
@override
State<MapScreen> createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
LatLng? _pickedLocation;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.isSelected ? 'Pick your location' : 'Your location'),
actions: [
if (widget.isSelected)
IconButton(
onPressed: () {
Navigator.of(context).pop(_pickedLocation);
},
icon: const Icon(Icons.save),
)
],
),
body: GoogleMap(
onTap: !widget.isSelected ? null: (position) {
setState(() {
_pickedLocation = position;
});
},
initialCameraPosition: CameraPosition(
target: LatLng(widget.location.latitude, widget.location.longitude),
zoom: 16,
),
markers: (_pickedLocation == null && widget.isSelected)
? {}
: {
Marker(
markerId: const MarkerId('m1'),
position: _pickedLocation ??
LatLng(
widget.location.latitude, widget.location.longitude),
)
},
),
);
}
}
/*
position: _pickedLocation != null
? _pickedLocation!
: LatLng(widget.location.latitude, widget.location.longitude)
position: _pickedLocation ?? LatLng(widget.location.latitude, widget.location.longitude),
(it is the short version of the above A?c:d code if c is null d will be used else c will be used)
*/
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/widget/location_input.dart
|
import 'dart:convert';
import 'package:favorite_place/model/place.dart';
import 'package:favorite_place/screen/map.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:http/http.dart' as http;
class LocationInput extends StatefulWidget {
const LocationInput({super.key, required this.onSelectLocation});
final void Function(PlaceLocation location) onSelectLocation;
@override
State<LocationInput> createState() => _LocationInputState();
}
class _LocationInputState extends State<LocationInput> {
PlaceLocation? _pickedLocation;
var _isGettingLocation = false;
String get locationImage {
if (_pickedLocation == null) {
return '';
}
final lat = _pickedLocation!.latitude;
final lng = _pickedLocation!.longitude;
return 'https://maps.googleapis.com/maps/api/staticmap?center=$lat,$lng=&zoom=13&size=600x300&maptype=roadmap&markers=color:blue%7Clabel:S%7C$lat,$lng&key=YOUR_API_KEY';
}
void _savedPlace(double lat, double lng) async {
final url = Uri.parse(
'https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&key=YOUR_API_KEY');
final response = await http.get(url);
final resData = json.decode(response.body);
final address = resData['result'][0]['formatted_address'];
setState(() {
_pickedLocation = PlaceLocation(
latitude: lat,
longitude: lng,
address: address,
);
_isGettingLocation = false;
});
widget.onSelectLocation(_pickedLocation!);
}
void _getCurrentLocation() async {
Location location = Location();
bool serviceEnabled;
PermissionStatus permissionGranted;
LocationData locationData;
serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
return;
}
}
permissionGranted = await location.hasPermission();
if (permissionGranted == PermissionStatus.denied) {
permissionGranted = await location.requestPermission();
if (permissionGranted != PermissionStatus.granted) {
return;
}
}
setState(() {
_isGettingLocation = true;
});
locationData = await location.getLocation();
final lat = locationData.latitude;
final lng = locationData.longitude;
if (lat == null || lng == null) {
return;
}
_savedPlace(lat, lng);
}
void _selectOnMap() async {
final pickedLocation =
await Navigator.of(context).push<LatLng>(MaterialPageRoute(
builder: (context) => MapScreen(),
));
if (pickedLocation == null) {
return;
}
_savedPlace(pickedLocation.latitude, pickedLocation.longitude);
}
@override
Widget build(BuildContext context) {
Widget content = Text(
'No location chosen',
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: Theme.of(context).colorScheme.onBackground,
),
textAlign: TextAlign.center,
);
if (_pickedLocation != null) {
content = Image.network(
locationImage,
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
);
}
if (_isGettingLocation) {
content = const CircularProgressIndicator();
}
return Column(
children: [
Container(
alignment: Alignment.center,
height: 170,
width: double.infinity,
decoration: BoxDecoration(
border: Border.all(
width: 1,
color: Theme.of(context).colorScheme.primary.withOpacity(0.2),
),
),
child: content,
),
Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
TextButton.icon(
onPressed: _getCurrentLocation,
icon: const Icon(Icons.location_on),
label: const Text('Get Current Location')),
TextButton.icon(
onPressed: _selectOnMap,
icon: const Icon(Icons.map),
label: const Text('Select Location')),
]),
],
);
}
}
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/widget/places_list.dart
|
import 'package:favorite_place/model/place.dart';
import 'package:favorite_place/screen/places_detail.dart';
import 'package:flutter/material.dart';
class PlacesList extends StatelessWidget {
const PlacesList({super.key, required this.places});
final List<Place> places;
@override
Widget build(BuildContext context) {
if (places.isEmpty) {
return Center(
child: Text(
'No places added yet',
style: Theme.of(context)
.textTheme
.bodyLarge!
.copyWith(color: Theme.of(context).colorScheme.onBackground),
));
}
return ListView.builder(
itemCount: places.length,
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(
radius: 26,
backgroundImage: FileImage(places[index].image),
),
title: Text(
places[index].title,
style: Theme.of(context)
.textTheme
.titleMedium!
.copyWith(color: Theme.of(context).colorScheme.onBackground),
),
subtitle: Text(
places[index].location.address,
style: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(color: Theme.of(context).colorScheme.onBackground),
),
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => PlaceDetailScreen(place: places[index]),
));
},
),
);
}
}
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/widget/image_input.dart
|
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class ImageInput extends StatefulWidget {
const ImageInput({super.key, required this.onPickImage});
final void Function(File image) onPickImage;
@override
State<ImageInput> createState() => _ImageInputState();
}
class _ImageInputState extends State<ImageInput> {
File? _selectedImage;
void _takepicture() async {
final imagepicker = ImagePicker();
final pickedImage =
await imagepicker.pickImage(source: ImageSource.camera, maxWidth: 600);
if (pickedImage == null) {
return;
}
setState(() {
_selectedImage = File(pickedImage.path);
});
widget.onPickImage(_selectedImage!);
}
@override
Widget build(BuildContext context) {
Widget content = TextButton.icon(
onPressed: _takepicture,
icon: const Icon(Icons.camera_alt_outlined),
label: const Text('Take Picture'));
if (_selectedImage != null) {
content = GestureDetector(
onTap: _takepicture,
child: Image.file(
_selectedImage!,
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
);
}
return Container(
decoration: BoxDecoration(
border: Border.all(
width: 1,
color: Theme.of(context).colorScheme.primary.withOpacity(0.2),
),
),
alignment: Alignment.center,
height: 250,
width: double.infinity,
child: content,
);
}
}
| 0
|
mirrored_repositories/Favorite-Place/lib
|
mirrored_repositories/Favorite-Place/lib/provider/user_place.dart
|
import 'dart:io';
import 'package:riverpod/riverpod.dart';
import 'package:path_provider/path_provider.dart' as syspaths;
import 'package:path/path.dart' as path;
import 'package:sqflite/sqflite.dart' as sql;
import 'package:sqflite/sqlite_api.dart';
import 'package:favorite_place/model/place.dart';
Future<Database> _getDatabase() async {
final dbPath = await sql.getDatabasesPath();
final db = await sql.openDatabase(
path.join(dbPath, 'places.db'),
onCreate: (db, version) {
return db.execute(
'CREATE TABLE user_places(id TEXT PRIMARY KEY, title TEXT, image TEXT, lat REAL, lng REAL, address TEXT)');
},
version: 1,
);
return db;
}
class UserPlacesNotifier extends StateNotifier<List<Place>> {
UserPlacesNotifier() : super(const []);
Future<void> loadPlace() async {
final db = await _getDatabase();
final data = await db.query('user_places');
final places = data
.map((row) => Place(
id: row['id'] as String,
title: row['title'] as String,
image: File(row['image'] as String),
location: PlaceLocation(
latitude: row['lat'] as double,
longitude: row['lng'] as double,
address: row['address'] as String),
))
.toList();
state = places;
}
void addPlace(String title, File image, PlaceLocation location) async {
final appDir = await syspaths.getApplicationDocumentsDirectory();
final filename = path.basename(image.path);
final copiedImage = await image.copy('${appDir.path}/$filename');
final newPlace =
Place(title: title, image: copiedImage, location: location);
final db = await _getDatabase();
db.insert('user_places', {
'id': newPlace.id,
'title': newPlace.title,
'image': newPlace.image.path,
'lat': newPlace.location.latitude,
'lng': newPlace.location.longitude,
'address': newPlace.location.address,
});
state = [newPlace, ...state];
}
}
final UserPlacesProvider =
StateNotifierProvider<UserPlacesNotifier, List<Place>>(
(ref) => UserPlacesNotifier(),
);
| 0
|
mirrored_repositories/Favorite-Place
|
mirrored_repositories/Favorite-Place/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:favorite_place/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/Bill-Splitter
|
mirrored_repositories/Bill-Splitter/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:split_bill/src/components/group/grouppage.dart';
import 'package:split_bill/src/home/homepage.dart';
import 'package:split_bill/src/components/splash/intro_pages.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: 'Flutter Demo',
theme: ThemeData(
textTheme: GoogleFonts.robotoTextTheme(),
),
home: Introduction());
}
}
| 0
|
mirrored_repositories/Bill-Splitter/lib/src/components
|
mirrored_repositories/Bill-Splitter/lib/src/components/expense/expenses.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:developer';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../home/homepage.dart';
import '../helper/neubox.dart';
class ExpenseTile extends StatefulWidget {
final String groupname;
final String des;
final String Total;
final String received;
final Function(BuildContext)? settings;
final Function(BuildContext)? onEdit;
final Function(BuildContext)? onDelete;
const ExpenseTile({
Key? key,
required this.groupname,
required this.des,
required this.Total,
required this.received,
required this.settings,
required this.onEdit,
required this.onDelete,
}) : super(key: key);
@override
State<ExpenseTile> createState() => _ExpenseTileState();
}
class _ExpenseTileState extends State<ExpenseTile> {
@override
Widget build(BuildContext context) {
return Container(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: GestureDetector(
onTap: (() {
Navigator.push(
context, MaterialPageRoute(builder: (_) => const Homepage()));
}),
child: NeuBox(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Container(
// ignore: sort_child_properties_last
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
// ignore: prefer_const_literals_to_create_immutables
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
// ignore: prefer_const_literals_to_create_immutables
children: [
Text(
widget.groupname,
style: const TextStyle(
fontSize: 35,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 18, 17, 17)),
),
Text(widget.des),
],
),
InkWell(
onTap: () => widget.settings,
child: const Icon(Icons.more_vert))
],
),
const SizedBox(
height: 30,
),
// ignore: prefer_const_constructors
SizedBox(
height: 30,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
// ignore: prefer_const_literals_to_create_immutables
children: [
const Text(
"In Total",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 8, 8, 8)),
),
Text(
widget.Total,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 34, 34, 34)),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
// ignore: prefer_const_literals_to_create_immutables
children: [
const Text(
"Received",
style: TextStyle(
fontSize: 15,
color: Color.fromARGB(255, 66, 66, 66)),
),
Text(
widget.received,
style: const TextStyle(
fontSize: 15,
color: Color.fromARGB(255, 66, 66, 66)),
)
],
),
],
)
],
))),
)),
),
),
);
}
}
| 0
|
mirrored_repositories/Bill-Splitter/lib/src/components
|
mirrored_repositories/Bill-Splitter/lib/src/components/helper/neubox.dart
|
import 'package:flutter/material.dart';
class NeuBox extends StatelessWidget {
final child;
const NeuBox({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(8),
child: Center(child: child),
decoration: BoxDecoration(
color: Color.fromARGB(255, 231, 230, 230),
borderRadius: BorderRadius.circular(15),
boxShadow: [
// darker shadow on the bottom right
BoxShadow(
color: Colors.grey.shade500,
blurRadius: 15,
offset: Offset(5, 5),
),
// lighter shadow on the top left
const BoxShadow(
color: Colors.white,
blurRadius: 15,
offset: Offset(-5, -5),
),
],
),
);
}
}
| 0
|
mirrored_repositories/Bill-Splitter/lib/src/components
|
mirrored_repositories/Bill-Splitter/lib/src/components/helper/friends.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'neubox.dart';
class Friends extends StatefulWidget {
final String name;
final String percentage;
final String toPay;
final String slider;
const Friends({
Key? key,
required this.name,
required this.percentage,
required this.toPay,
required this.slider,
}) : super(key: key);
@override
State<Friends> createState() => _FriendsState();
}
class _FriendsState extends State<Friends> {
@override
Widget build(BuildContext context) {
return Container(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: NeuBox(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Column(
children: [
CircleAvatar(
backgroundImage: AssetImage("assets/images/boy.png"),
radius: 35,
),
SizedBox(
height: 10,
),
Text("John",
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 45, 191, 244)))
],
),
Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(
width: 10,
),
Text("40%",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 66, 66, 66))),
SizedBox(
width: 100,
),
Text("Rs 500",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 66, 66, 66))),
],
),
Row(
children: [
Slider(
min: 0,
max: 10,
activeColor:
const Color.fromARGB(255, 45, 191, 244),
inactiveColor: Colors.grey,
value: 7,
onChanged: ((value) {})),
],
)
],
)
],
),
),
)),
),
);
}
}
| 0
|
mirrored_repositories/Bill-Splitter/lib/src/components
|
mirrored_repositories/Bill-Splitter/lib/src/components/splash/intro_pages.dart
|
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:introduction_screen/introduction_screen.dart';
import 'package:split_bill/src/components/group/grouppage.dart';
import 'package:split_bill/src/home/homepage.dart';
class Introduction extends StatelessWidget {
const Introduction({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 245, 110, 89),
body: SafeArea(
child: IntroductionScreen(
pages: [
PageViewModel(
image: Center(
child: Padding(
padding: const EdgeInsets.only(top: 12.0),
child: Image.asset("assets/images/billlady.jpg"),
),
),
title: "Splitting Bill",
body: "Now splitting bill is super easy",
decoration: PageDecoration(
pageColor: Colors.white,
titleTextStyle:
TextStyle(fontSize: 35, fontWeight: FontWeight.w500))),
PageViewModel(
image: Center(
child: Padding(
padding: const EdgeInsets.only(top: 12.0),
child: Image.asset("assets/images/2nd.jpg"),
),
),
title: "Split Bills equally or unequally",
body: "Low on budget? Ask your friends to help you out",
decoration: PageDecoration(
pageColor: Colors.white,
titleTextStyle:
TextStyle(fontSize: 35, fontWeight: FontWeight.w500))),
PageViewModel(
image: Center(
child: Padding(
padding: const EdgeInsets.only(top: 12.0),
child: Image.asset("assets/images/3rd.jpg"),
),
),
title: "Make Groups",
body: "Split bills without any hesitation among your friends",
decoration: PageDecoration(
pageColor: Colors.white,
titleTextStyle:
TextStyle(fontSize: 35, fontWeight: FontWeight.w500))),
],
dotsDecorator: DotsDecorator(activeColor: Colors.orange),
onDone: () {
Navigator.push(
context, MaterialPageRoute(builder: (_) => Groupage()));
},
done: Text(
"Get Started",
style: TextStyle(color: Color.fromARGB(255, 255, 99, 32)),
),
next: Text(
"Next",
style: TextStyle(color: Color.fromARGB(255, 255, 99, 32)),
),
skip: Text(
"Skip",
style: TextStyle(color: Color.fromARGB(255, 255, 99, 32)),
),
// back: Text("Back"),
showNextButton: true,
showDoneButton: true,
showSkipButton: true,
// showBackButton: true,
),
),
);
}
}
| 0
|
mirrored_repositories/Bill-Splitter/lib/src/components
|
mirrored_repositories/Bill-Splitter/lib/src/components/group/grouppage.dart
|
import 'package:flutter/material.dart';
import 'package:split_bill/src/components/expense/expenses.dart';
import 'package:split_bill/src/home/homepage.dart';
import '../helper/neubox.dart';
class Groupage extends StatefulWidget {
const Groupage({Key? key}) : super(key: key);
@override
State<Groupage> createState() => _GroupageState();
}
class _GroupageState extends State<Groupage> {
// final _controller;
List expenses = [
["Restaurant", "Bill splitting", "15000", "700"],
["Trip", "Went with Friends", "15000", "700"],
];
final _newgroupcontroller = TextEditingController();
final _newdescontroller = TextEditingController();
final _newamountcontroller = TextEditingController();
final _newreceivedcontroller = TextEditingController();
void deleteExpense(int index) {
setState(() {
expenses.removeAt(index);
});
}
void _showDialog() {
showDialog(
context: context,
builder: ((context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
backgroundColor: Colors.grey[300],
title: Text("ADD EXPENSES"),
content: SingleChildScrollView(
child: Expanded(
child: Container(
// decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(45),
// color: Colors.grey),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 5.0),
child: Text("Group Name"),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: TextField(
decoration: InputDecoration(
contentPadding: EdgeInsetsDirectional.all(10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
BorderSide(color: Colors.black54))),
controller: _newgroupcontroller,
),
),
//des
Padding(
padding: const EdgeInsets.only(left: 5.0),
child: Text("Add description"),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: TextFormField(
controller: _newdescontroller,
decoration: InputDecoration(
contentPadding: EdgeInsetsDirectional.all(10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
BorderSide(color: Colors.black54)))),
),
//total amount
Padding(
padding: const EdgeInsets.only(left: 5.0),
child: Text("Total Amount"),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: TextFormField(
decoration: InputDecoration(
contentPadding: EdgeInsetsDirectional.all(10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
BorderSide(color: Colors.black54))),
keyboardType: TextInputType.number,
controller: _newamountcontroller),
),
//receieved
Padding(
padding: const EdgeInsets.only(left: 5.0),
child: Text("Received Amount"),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: TextFormField(
keyboardType: TextInputType.number,
controller: _newreceivedcontroller,
decoration: InputDecoration(
contentPadding: EdgeInsetsDirectional.all(12),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
BorderSide(color: Colors.black54)))),
),
const SizedBox(
height: 12,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: savenewexpense,
child: Text(
"Save",
style: TextStyle(color: Colors.white),
),
style: ElevatedButton.styleFrom(
primary: Color.fromARGB(255, 241, 123, 80),
minimumSize: Size(80, 40)),
),
const SizedBox(
width: 12,
),
ElevatedButton(
onPressed: () {
_newgroupcontroller.clear();
_newdescontroller.clear();
_newamountcontroller.clear();
_newreceivedcontroller.clear();
Navigator.of(context).pop();
},
child: Text("Cancel"),
style: ElevatedButton.styleFrom(
primary: Color.fromARGB(255, 241, 123, 80),
minimumSize: Size(80, 40))),
],
)
]),
),
),
),
);
}));
}
void savenewexpense() {
setState(() {
expenses.add([
_newgroupcontroller.text,
_newdescontroller.text,
_newamountcontroller.text,
_newreceivedcontroller.text
]);
});
_newgroupcontroller.clear();
_newdescontroller.clear();
_newamountcontroller.clear();
_newreceivedcontroller.clear();
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color.fromARGB(255, 241, 123, 80),
title: const Text("Bill Splitter"),
centerTitle: true,
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: expenses.length,
itemBuilder: (context, index) {
return ExpenseTile(
groupname: expenses[index][0],
des: expenses[index][1],
// ignore: prefer_interpolation_to_compose_strings
Total: "\Rs ${expenses[index][2]}",
received: "\Rs ${expenses[index][3]}",
settings: (context) {},
onEdit: (context) {},
onDelete: (context) => deleteExpense(index),
);
},
),
),
Padding(
padding: const EdgeInsets.all(25.0),
child: ElevatedButton(
onPressed: () {
//show a dialog box
_showDialog();
},
child: Text(
"Add Expense",
style: TextStyle(fontSize: 20),
),
style: ElevatedButton.styleFrom(
fixedSize: Size(180, 45),
primary: Color.fromARGB(255, 241, 123, 80)),
),
)
],
),
);
}
}
| 0
|
mirrored_repositories/Bill-Splitter/lib/src
|
mirrored_repositories/Bill-Splitter/lib/src/home/homepage.dart
|
import 'package:flutter/material.dart';
import 'package:split_bill/src/components/helper/friends.dart';
import 'package:split_bill/src/components/helper/neubox.dart';
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
@override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color.fromARGB(255, 241, 123, 80),
title: const Text("Bill Splitter"),
centerTitle: true,
),
floatingActionButton:
///floating button
FloatingActionButton(
onPressed: () {},
backgroundColor: const Color.fromARGB(255, 241, 123, 80),
child: const Icon(Icons.add)),
body: Container(
color: Color.fromARGB(255, 239, 238, 238),
child: ListView(children: [
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.all(15.0),
child: NeuBox(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Container(
// ignore: sort_child_properties_last
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
// ignore: prefer_const_literals_to_create_immutables
children: [
const Text(
"Total bill",
// ignore: prefer_const_constructors
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 82, 80, 80)),
),
const Text(
"Rs 1000",
// ignore: unnecessary_const
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
// ignore: prefer_const_constructors
color: Color.fromARGB(255, 82, 80, 80)),
)
],
),
const SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text("Tip",
// ignore: unnecessary_const
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 75, 75, 75))),
Slider(
min: 0,
max: 10,
activeColor: const Color.fromARGB(255, 241, 123, 80),
inactiveColor: Colors.grey,
value: 5,
onChanged: ((value) {})),
const SizedBox(
width: 0,
),
const Text("20%"),
const Text("200")
],
),
// ignore: prefer_const_constructors
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
// ignore: prefer_const_literals_to_create_immutables
children: [
const Text(
"Total To Split",
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Color.fromARGB(255, 8, 8, 8)),
),
const Text(
"Rs 1200",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: const Color.fromARGB(255, 0, 0, 0)),
)
],
),
],
))),
)),
),
Friends(
name: "John", percentage: "40%", toPay: "Rs 500", slider: "4"),
Friends(
name: "Neha", percentage: "70%", toPay: "Rs 1500", slider: "7"),
Friends(
name: "Eren", percentage: "30%", toPay: "Rs 300", slider: "3"),
// Padding(
// padding: const EdgeInsets.all(12.0),
// child: NeuBox(
// child: Padding(
// padding: const EdgeInsets.all(8.0),
// child: Container(
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// Column(
// children: [
// CircleAvatar(
// backgroundImage:
// AssetImage("assets/images/boy.png"),
// radius: 35,
// ),
// SizedBox(
// height: 10,
// ),
// Text("John",
// style: const TextStyle(
// fontSize: 15,
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 45, 191, 244)))
// ],
// ),
// Column(
// children: [
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// children: [
// SizedBox(
// width: 10,
// ),
// Text("40%",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 66, 66, 66))),
// SizedBox(
// width: 100,
// ),
// Text("Rs 500",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 66, 66, 66))),
// ],
// ),
// Row(
// children: [
// Slider(
// min: 0,
// max: 10,
// activeColor:
// const Color.fromARGB(255, 45, 191, 244),
// inactiveColor: Colors.grey,
// value: 5,
// onChanged: ((value) {})),
// ],
// )
// ],
// )
// ],
// ),
// ),
// )),
// ),
// Padding(
// padding: const EdgeInsets.all(12.0),
// child: NeuBox(
// child: Padding(
// padding: const EdgeInsets.all(8.0),
// child: Container(
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// Column(
// children: [
// CircleAvatar(
// backgroundImage:
// AssetImage("assets/images/child.png"),
// radius: 35,
// ),
// SizedBox(
// height: 10,
// ),
// Text("Neha",
// style: const TextStyle(
// fontSize: 15,
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 235, 190, 25)))
// ],
// ),
// Column(
// children: [
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// children: [
// SizedBox(
// width: 10,
// ),
// Text("70%",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 66, 66, 66))),
// SizedBox(
// width: 100,
// ),
// Text("Rs 500",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 66, 66, 66))),
// ],
// ),
// Row(
// children: [
// Slider(
// min: 0,
// max: 10,
// activeColor:
// const Color.fromARGB(255, 235, 190, 25),
// inactiveColor: Colors.grey,
// value: 7,
// onChanged: ((value) {})),
// ],
// )
// ],
// )
// ],
// ),
// ),
// )),
// ),
// Padding(
// padding: const EdgeInsets.all(12.0),
// child: NeuBox(
// child: Padding(
// padding: const EdgeInsets.all(8.0),
// child: Container(
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// Column(
// children: [
// CircleAvatar(
// backgroundImage:
// AssetImage("assets/images/man.png"),
// radius: 35,
// ),
// SizedBox(
// height: 10,
// ),
// Text("Eren",
// style: const TextStyle(
// fontSize: 15,
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 168, 20, 163)))
// ],
// ),
// Column(
// children: [
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// children: [
// SizedBox(
// width: 10,
// ),
// Text(
// "30%",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 66, 66, 66)),
// ),
// SizedBox(
// width: 100,
// ),
// Text("Rs 500",
// style: TextStyle(
// fontWeight: FontWeight.bold,
// color: Color.fromARGB(255, 66, 66, 66))),
// ],
// ),
// Row(
// children: [
// Slider(
// min: 0,
// max: 10,
// activeColor:
// const Color.fromARGB(255, 168, 20, 163),
// inactiveColor: Colors.grey,
// value: 3,
// onChanged: ((value) {})),
// ],
// )
// ],
// )
// ],
// ),
// ),
// )),
// ),
// ListView(
// children: [
// Friends(
// name: "John", percentage: "40%", toPay: "Rs 500", slider: "7")
// ],
// )
]),
),
);
}
}
| 0
|
mirrored_repositories/Bill-Splitter
|
mirrored_repositories/Bill-Splitter/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:split_bill/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/Tip-Calculator/tip_calculator
|
mirrored_repositories/Tip-Calculator/tip_calculator/lib/main.dart
|
import 'package:flutter/material.dart';
void main() {
runApp(Homepage());
}
class Homepage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Tip Calculator',
home: FirstRoute(),
);
}
}
class FirstRoute extends StatefulWidget {
@override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
final myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is disposed.
myController.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blueGrey,
title: Text('Tip Calculator'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
TextField(
controller: myController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter the amount in Rupees",
labelText: "Amount",
),
keyboardType: TextInputType.number,
),
Align(
alignment: Alignment.centerRight,
child: RaisedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
SecondRoute(value: myController.text)),
);
},
child: const Text('Next', style: TextStyle(fontSize: 20)),
color: Colors.orange,
textColor: Colors.black,
elevation: 5,
),
),
],
),
),
);
}
}
class SecondRoute extends StatelessWidget {
String value;
double finalamount;
SecondRoute({Key key, this.value}) : super(key: key);
final controller2 = TextEditingController();
String tippercent(String bill) {
double tip = double.parse(controller2.text);
finalamount = (tip / 100) * double.parse(value) + double.parse(value);
return finalamount.toString();
}
createalertdialog(BuildContext context) {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Total bill'),
content: Text(tippercent("bill")),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tip Calculator'),
backgroundColor: Colors.grey,
),
body: Column(
children: [
Text("Amount entered is " + value),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: controller2,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Percentage tip You want to give ",
labelText: "% tip",
),
keyboardType: TextInputType.number,
),
),
RaisedButton(
onPressed: () {
createalertdialog(context);
},
child: const Text('Total Amount', style: TextStyle(fontSize: 20)),
color: Colors.blue,
textColor: Colors.black,
elevation: 5,
),
],
),
);
}
}
| 0
|
mirrored_repositories/Tip-Calculator/tip_calculator
|
mirrored_repositories/Tip-Calculator/tip_calculator/integration_test/driver.dart
|
// This file is provided as a convenience for running integration tests via the
// flutter drive command.
//
// flutter drive --driver integration_test/driver.dart --target integration_test/app_test.dart
import 'package:integration_test/integration_test_driver.dart';
Future<void> main() => integrationDriver();
| 0
|
mirrored_repositories/Tip-Calculator/tip_calculator
|
mirrored_repositories/Tip-Calculator/tip_calculator/integration_test/app_test.dart
|
// This is a basic Flutter integration 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:integration_test/integration_test.dart';
import 'package:tip_calculator/main.dart' as app;
void main() => run(_testMain);
void _testMain() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
// Trigger a frame.
await tester.pumpAndSettle();
// 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/Tip-Calculator/tip_calculator
|
mirrored_repositories/Tip-Calculator/tip_calculator/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:tip_calculator/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(Homepage());
// 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-Radio-App
|
mirrored_repositories/Flutter-Radio-App/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:radio_app/radio/radio_list.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const RadioList()
);
}
}
| 0
|
mirrored_repositories/Flutter-Radio-App/lib
|
mirrored_repositories/Flutter-Radio-App/lib/radio/radio.dart
|
import 'dart:async';
import 'package:radio_player/radio_player.dart';
class RadioClass {
final RadioPlayer radioPlayer = RadioPlayer();
bool isPlaying = false;
Future<void> setChannel(item) async {
radioPlayer.stop();
await radioPlayer.setChannel(
title: item['name'],
url: item['streamURL'],
);
}
void play() {
radioPlayer.play();
}
void pause() {
radioPlayer.pause();
}
void stop() {
radioPlayer.stop();
}
}
| 0
|
mirrored_repositories/Flutter-Radio-App/lib
|
mirrored_repositories/Flutter-Radio-App/lib/radio/radio_list.dart
|
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:radio_app/radio/radio.dart';
import 'package:radio_app/radio/widgets/expandable.dart';
import 'package:radio_app/radio/widgets/player.dart';
import 'package:radio_app/radio/widgets/radio_card.dart';
class RadioList extends StatefulWidget {
const RadioList({super.key});
@override
State<RadioList> createState() => _RadioListState();
}
class _RadioListState extends State<RadioList> {
dynamic radioClass;
bool isPlaying = false;
final _controller = ScrollController();
double offset = 0;
late double _percentageOpen = 0;
String radioTitle = '';
String radioListener = '';
String radioImageURl = '';
bool isPlayCardVisible = false;
dynamic currentlyPlaying;
List<dynamic> stationList = [];
List<String>? metadata;
@override
void initState() {
super.initState();
_controller.addListener(moveOffset);
radioClass = RadioClass();
readJson();
}
@override
void dispose() {
super.dispose();
radioClass.stop();
}
moveOffset() {
setState(() {
offset = min(max(0, _controller.offset / 6 - 16), 32);
});
}
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/json/station.json');
List<dynamic> data = json.decode(response);
setState(() {
stationList.addAll(data);
});
}
Future<void> radioPlayer(item) async {
currentlyPlaying = item;
radioClass.stop();
setState(() {
radioClass.setChannel(item);
});
radioClass.radioPlayer.stateStream.listen((value) {
setState(() {
isPlaying = value;
});
});
radioClass.radioPlayer.metadataStream.listen((value) {
setState(() {
metadata = value;
});
});
setState(() {
isPlayCardVisible = true;
radioTitle = item['name'];
radioImageURl = item['imageURL'];
radioListener = item['listener'];
stationList.asMap().forEach((index, items) {
if (items == item) {
if(item['isPlay'] == true) {
stationList[index]['isPlay'] = false;
radioClass.pause();
} else {
stationList[index]['isPlay'] = true;
Future.delayed(
const Duration(seconds: 1),
() => radioClass.play(),
);
}
} else {
stationList[index]['isPlay'] = false;
}
});
});
}
Future<void> play() async {
radioClass.play();
checkStation();
}
Future<void> pause() async {
radioClass.pause();
checkStation();
}
void checkStation() {
stationList.asMap().forEach((index, items) {
if (items == currentlyPlaying) {
if(currentlyPlaying['isPlay'] == true) {
stationList[index]['isPlay'] = false;
radioClass.pause();
} else {
stationList[index]['isPlay'] = true;
Future.delayed(
const Duration(seconds: 1),
() => radioClass.play(),
);
}
} else {
stationList[index]['isPlay'] = false;
}
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
backgroundColor: Colors.black,
body: ExpandableBottomSheet(
background: CustomScrollView(
controller: _controller,
physics: const BouncingScrollPhysics(),
slivers: <Widget>[
const SliverAppBar(
backgroundColor: Colors.black,
title: Text('Radio List', style: TextStyle(color: Colors.white)),
primary: true,
pinned: true,
centerTitle: true,
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 16),
child: Text('Recently played', style: theme.textTheme.headlineSmall!.copyWith(fontWeight: FontWeight.w600, color: Colors.white)),
),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final item = stationList[index];
return RadioCard(
onTab: () => radioPlayer(item),
item: item
);
},
childCount: stationList.length,
),
),
const SliverToBoxAdapter(
child: SizedBox(
height: 70,
),
),
],
),
onIsContractedCallback: () => print('contracted'),
onIsExtendedCallback: () => print('extended'),
persistentContentHeight: 64,
expandableContent: isPlayCardVisible ? Player(
title: radioTitle,
listener: radioListener,
imageURL: radioImageURl,
percentageOpen: _percentageOpen,
onTab: () => isPlaying ? pause() : play(),
icon: isPlaying ? Icons.pause_rounded : Icons.play_arrow_rounded,
metadata: metadata,
) : const SizedBox(),
onOffsetChanged: (offset, minOffset, maxOffset) {
if(isPlayCardVisible) {
if (maxOffset == null || offset == null || minOffset == null) {
return;
}
final range = maxOffset - minOffset;
final currentOffset = offset - minOffset;
setState(() {
_percentageOpen = max(0, 1 - (currentOffset / range));
});
}
},
enableToggle: true,
isDraggable: true,
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Radio-App/lib/radio
|
mirrored_repositories/Flutter-Radio-App/lib/radio/widgets/expandable.dart
|
import 'package:flutter/material.dart';
class ExpandableBottomSheet extends StatefulWidget {
/// [expandableContent] is the widget which you can hide and show by dragging.
/// It has to be a widget with a constant height. It is required for the [ExpandableBottomSheet].
final Widget expandableContent;
/// [background] is the widget behind the [expandableContent] which holds
/// usually the content of your page. It is required for the [ExpandableBottomSheet].
final Widget background;
/// [persistentContentHeight] is the height of the content which will never
/// been contracted. It only relates to [expandableContent]. [persistentHeader]
/// and [persistentFooter] will not be affected by this.
final double persistentContentHeight;
/// [animationDurationExtend] is the duration for the animation if you stop
/// dragging with high speed.
final Duration animationDurationExtend;
/// [animationDurationContract] is the duration for the animation to bottom
/// if you stop dragging with high speed. If it is `null` [animationDurationExtend] will be used.
final Duration animationDurationContract;
/// [animationCurveExpand] is the curve of the animation for expanding
/// the [expandableContent] if the drag ended with high speed.
final Curve animationCurveExpand;
/// [animationCurveContract] is the curve of the animation for contracting
/// the [expandableContent] if the drag ended with high speed.
final Curve animationCurveContract;
/// [onIsExtendedCallback] will be executed if the extend reaches its maximum.
final Function()? onIsExtendedCallback;
/// [onIsContractedCallback] will be executed if the extend reaches its minimum.
final Function()? onIsContractedCallback;
/// [onOffsetChanged] will be executed if the offset changes.
final Function(double?, double?, double?)? onOffsetChanged;
/// [enableToggle] will enable tap to toggle option on header.
final bool enableToggle;
/// [isDraggable] will make the [ExpandableBottomSheet] draggable by the user or not.
final bool isDraggable;
/// Creates the [ExpandableBottomSheet].
///
/// [persistentContentHeight] has to be greater 0.
const ExpandableBottomSheet({
Key? key,
required this.expandableContent,
required this.background,
this.persistentContentHeight = 0.0,
this.animationCurveExpand = Curves.ease,
this.animationCurveContract = Curves.ease,
this.animationDurationExtend = const Duration(milliseconds: 350),
this.animationDurationContract = const Duration(milliseconds: 350),
this.onIsExtendedCallback,
this.onOffsetChanged,
this.onIsContractedCallback,
this.enableToggle = false,
this.isDraggable = true,
}) : assert(persistentContentHeight >= 0),
super(key: key);
@override
ExpandableBottomSheetState createState() => ExpandableBottomSheetState();
}
class ExpandableBottomSheetState extends State<ExpandableBottomSheet>
with TickerProviderStateMixin {
final GlobalKey _contentKey = GlobalKey(debugLabel: 'contentKey');
late AnimationController _controller;
double _draggableHeight = 0;
double? _positionOffset;
double _startOffsetAtDragDown = 0;
double? _startPositionAtDragDown = 0;
double _minOffset = 0;
double _maxOffset = 0;
double _animationMinOffset = 0;
AnimationStatus _oldStatus = AnimationStatus.dismissed;
bool _useDrag = true;
bool _callCallbacks = false;
/// Expands the content of the widget.
void expand() {
_afterUpdateWidgetBuild(false);
_callCallbacks = true;
_animateToTop();
}
/// Contracts the content of the widget.
void contract() {
_afterUpdateWidgetBuild(false);
_callCallbacks = true;
_animateToBottom();
}
/// The status of the expansion.
ExpansionStatus get expansionStatus {
if (_positionOffset == null) return ExpansionStatus.contracted;
if (_positionOffset == _maxOffset) return ExpansionStatus.contracted;
if (_positionOffset == _minOffset) return ExpansionStatus.expanded;
return ExpansionStatus.middle;
}
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
lowerBound: 0.0,
upperBound: 1.0,
);
_controller.addStatusListener(_handleAnimationStatusUpdate);
WidgetsBinding.instance.addPostFrameCallback((_) => _afterUpdateWidgetBuild(true));
}
@override
Widget build(BuildContext context) {
WidgetsBinding.instance
.addPostFrameCallback((_) => _afterUpdateWidgetBuild(false));
return Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Expanded(
child: Stack(
clipBehavior: Clip.hardEdge,
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: widget.background,
),
AnimatedBuilder(
animation: _controller,
builder: (_, Widget? child) {
if (_controller.isAnimating) {
_positionOffset = _animationMinOffset +
_controller.value * _draggableHeight;
WidgetsBinding.instance.addPostFrameCallback((_) {
widget.onOffsetChanged
?.call(_positionOffset, _minOffset, _maxOffset);
});
}
return Positioned(
top: _positionOffset,
right: 0.0,
left: 0.0,
child: child!,
);
},
child: GestureDetector(
onTap: _toggle,
onVerticalDragDown: widget.isDraggable ? _dragDown : (_) {},
onVerticalDragUpdate:
widget.isDraggable ? _dragUpdate : (_) {},
onVerticalDragEnd: widget.isDraggable ? _dragEnd : (_) {},
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
key: _contentKey,
child: widget.expandableContent,
),
],
),
),
)
],
),
),
],
);
}
void _handleAnimationStatusUpdate(AnimationStatus status) {
if (status == AnimationStatus.completed) {
if (_oldStatus == AnimationStatus.forward) {
setState(() {
_draggableHeight = _maxOffset - _minOffset;
_positionOffset = _minOffset;
});
if (widget.onIsExtendedCallback != null && _callCallbacks) {
widget.onIsExtendedCallback!();
}
}
if (_oldStatus == AnimationStatus.reverse) {
setState(() {
_draggableHeight = _maxOffset - _minOffset;
_positionOffset = _maxOffset;
});
if (widget.onIsContractedCallback != null && _callCallbacks) {
widget.onIsContractedCallback!();
}
}
}
}
void _afterUpdateWidgetBuild(bool isFirstBuild) {
double contentHeight = _contentKey.currentContext!.size!.height;
double checkedPersistentContentHeight =
(widget.persistentContentHeight < contentHeight)
? widget.persistentContentHeight
: contentHeight;
final newMinOffset = context.size!.height - contentHeight;
final newMaxOffset = context.size!.height - checkedPersistentContentHeight;
if (_minOffset == newMinOffset && _maxOffset == newMaxOffset) return;
_minOffset = newMinOffset;
_maxOffset = newMaxOffset;
if (!isFirstBuild) {
_positionOutOfBounds();
} else {
setState(() {
_positionOffset = _maxOffset;
_draggableHeight = _maxOffset - _minOffset;
});
}
widget.onOffsetChanged?.call(_positionOffset, _minOffset, _maxOffset);
}
void _positionOutOfBounds() {
if (_positionOffset! < _minOffset) {
//the extend is larger than contentHeight
_callCallbacks = false;
_animateToMin();
} else {
if (_positionOffset! > _maxOffset) {
//the extend is smaller than persistentContentHeight
_callCallbacks = false;
_animateToMax();
} else {
_draggableHeight = _maxOffset - _minOffset;
}
}
}
void _animateOnIsAnimating() {
if (_controller.isAnimating) {
_controller.stop();
}
}
void _toggle() {
if (widget.enableToggle) {
if (expansionStatus == ExpansionStatus.expanded) {
_callCallbacks = true;
_animateToBottom();
}
if (expansionStatus == ExpansionStatus.contracted) {
_callCallbacks = true;
_animateToTop();
}
}
}
void _dragDown(DragDownDetails details) {
if (_controller.isAnimating) {
_useDrag = false;
} else {
_useDrag = true;
_startOffsetAtDragDown = details.localPosition.dy;
_startPositionAtDragDown = _positionOffset;
}
}
void _dragUpdate(DragUpdateDetails details) {
if (!_useDrag) return;
double offset = details.localPosition.dy;
double newOffset =
_startPositionAtDragDown! + offset - _startOffsetAtDragDown;
if (_minOffset <= newOffset && _maxOffset >= newOffset) {
setState(() {
_positionOffset = newOffset;
});
} else {
if (_minOffset > newOffset) {
setState(() {
_positionOffset = _minOffset;
});
}
if (_maxOffset < newOffset) {
setState(() {
_positionOffset = _maxOffset;
});
}
}
widget.onOffsetChanged?.call(_positionOffset, _minOffset, _maxOffset);
}
void _dragEnd(DragEndDetails details) {
if (_startPositionAtDragDown == _positionOffset || !_useDrag) return;
if (details.primaryVelocity! < -250) {
//drag up ended with high speed
_callCallbacks = true;
_animateToTop();
} else {
if (details.primaryVelocity! > 250) {
//drag down ended with high speed
_callCallbacks = true;
_animateToBottom();
} else {
if (_positionOffset == _maxOffset &&
widget.onIsContractedCallback != null) {
widget.onIsContractedCallback!();
}
if (_positionOffset == _minOffset &&
widget.onIsExtendedCallback != null) {
widget.onIsExtendedCallback!();
}
}
}
widget.onOffsetChanged?.call(_positionOffset, _minOffset, _maxOffset);
}
void _animateToTop() {
_animateOnIsAnimating();
_controller.value = (_positionOffset! - _minOffset) / _draggableHeight;
_animationMinOffset = _minOffset;
_oldStatus = AnimationStatus.forward;
_controller.animateTo(
0.0,
duration: widget.animationDurationExtend,
curve: widget.animationCurveExpand,
);
}
void _animateToBottom() {
_animateOnIsAnimating();
_controller.value = (_positionOffset! - _minOffset) / _draggableHeight;
_animationMinOffset = _minOffset;
_oldStatus = AnimationStatus.reverse;
_controller.animateTo(
1.0,
duration: widget.animationDurationContract,
curve: widget.animationCurveContract,
);
}
void _animateToMax() {
_animateOnIsAnimating();
_controller.value = 1.0;
_draggableHeight = _positionOffset! - _maxOffset;
_animationMinOffset = _maxOffset;
_oldStatus = AnimationStatus.reverse;
_controller.animateTo(
0.0,
duration: widget.animationDurationExtend,
curve: widget.animationCurveExpand,
);
}
void _animateToMin() {
_animateOnIsAnimating();
_controller.value = 1.0;
_draggableHeight = _positionOffset! - _minOffset;
_animationMinOffset = _minOffset;
_oldStatus = AnimationStatus.forward;
_controller.animateTo(
0.0,
duration: widget.animationDurationContract,
curve: widget.animationCurveContract,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
/// The status of the expandable content.
enum ExpansionStatus {
expanded,
middle,
contracted,
}
| 0
|
mirrored_repositories/Flutter-Radio-App/lib/radio
|
mirrored_repositories/Flutter-Radio-App/lib/radio/widgets/radio_card.dart
|
import 'package:flutter/material.dart';
class RadioCard extends StatelessWidget {
const RadioCard({
super.key, required this.onTab, required this.item,
});
final Map<String, dynamic> item;
final void Function() onTab;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Card(
color: Colors.grey.shade900,
clipBehavior: Clip.hardEdge,
child: InkWell(
onTap: onTab,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Container(
height: 100,
width: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
image: DecorationImage(
image: NetworkImage(item['imageURL']),
fit: BoxFit.cover
)
),
),
const SizedBox(width: 12,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(item['name'], style: theme.textTheme.labelLarge!.copyWith(fontSize: 18, color: Colors.grey.shade500), overflow: TextOverflow.ellipsis,),
Text(item['location'], style: theme.textTheme.bodyMedium!.copyWith(color: Colors.grey.shade700)),
const SizedBox(height: 8,),
Text(item['listener'], style: theme.textTheme.bodyMedium!.copyWith(fontWeight: FontWeight.w500, color: Colors.grey.shade600)),
],
),
),
Icon(!item['isPlay'] ? Icons.play_arrow : Icons.pause, size: 24, color: Colors.white),
const SizedBox(width: 6,)
],
),
)
],
),
)
);
}
}
| 0
|
mirrored_repositories/Flutter-Radio-App/lib/radio
|
mirrored_repositories/Flutter-Radio-App/lib/radio/widgets/player.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
class Player extends StatelessWidget {
const Player({
Key? key,
required this.percentageOpen, required this.title, required this.listener, required this.imageURL, required this. icon, required this.onTab, this.metadata,
}) : super(key: key);
final double percentageOpen;
final String title;
final String listener;
final String imageURL;
final IconData icon;
final Future<void> Function() onTab;
final List<String>? metadata;
@override
Widget build(BuildContext context) {
double heights = MediaQuery.of(context).size.height;
final imageHeight = 64 + (percentageOpen * heights * 0.5);
Uri image;
String metaTitle;
String metaDescription;
if (metadata != null) {
metaTitle = metadata![0];
metaDescription = metadata![1];
image = Uri.parse(metadata![2]);
} else {
metaTitle = 'Metadata';
metaDescription = '';
image = Uri.parse(imageURL);
}
return ConstrainedBox(
constraints: BoxConstraints(maxHeight: heights),
child: Stack(
children: <Widget>[
Container(
color: Colors.grey[900],
height: heights,
),
Opacity(
opacity: max(0, 1 - (percentageOpen * 4)),
child: SizedBox(
height: 64,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(width: 64),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(color: Colors.white),
),
const SizedBox(height: 2),
Text(
listener,
style: TextStyle(color: Colors.grey[500]),
),
],
),
const Spacer(),
IconButton(
icon: Icon(icon),
onPressed: onTab,
color: Colors.white,
),
const SizedBox(width: 12),
// IconButton(
// icon: const Icon(Icons.skip_next),
// onPressed: () {},
// color: Colors.white,
// ),
],
),
),
),
),
Opacity(
opacity: percentageOpen > 0.5
? min(1, max(0, percentageOpen - 0.5) * 2)
: 0,
child: Column(
children: [
SizedBox(
height: imageHeight * 0.9,
),
const SizedBox(height: 20,),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.thumb_down_alt_outlined,
size: 20,
color: Colors.white,
),
Column(
children: [
Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.w700),
),
const SizedBox(height: 8),
Text(
listener,
style: TextStyle(color: Colors.grey[500]),
),
Text(
metaTitle,
style: TextStyle(color: Colors.grey[500]),
),
Text(
metaDescription,
style: TextStyle(color: Colors.grey[500]),
),
],
),
const Icon(
Icons.thumb_up_alt_outlined,
size: 20,
color: Colors.white,
)
],
),
const SizedBox(height: 32),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Container(
height: 3,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.grey[400],
),
),
),
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'0:00',
style: TextStyle(color: Colors.grey[400]),
),
Text(
'3:27',
style: TextStyle(color: Colors.grey[400]),
),
],
),
),
const SizedBox(height: 24),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Icon(
Icons.shuffle,
size: 32,
color: Colors.white,
),
const Icon(
Icons.skip_previous,
size: 32,
color: Colors.white,
),
Container(
height: 80,
width: 80,
decoration: BoxDecoration(
color: Colors.grey[800],
shape: BoxShape.circle,
),
padding: const EdgeInsets.only(bottom: 16, left: 12, right: 26, top: 10),
child: IconButton(
onPressed: onTab,
icon: Icon(
icon,
size: 42,
color: Colors.white,
),
),
),
const Icon(
Icons.skip_next,
size: 32,
color: Colors.white,
),
const Icon(
Icons.repeat,
size: 32,
color: Colors.white,
)
],
),
),
],
),
),
Container(
height: imageHeight,
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16)
),
child: Container(
clipBehavior: Clip.hardEdge,
decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
child: Image.network(image.toString()),
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Radio-App
|
mirrored_repositories/Flutter-Radio-App/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:radio_app/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/raffle-flutter
|
mirrored_repositories/raffle-flutter/lib/main.dart
|
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/page/notifications.dart';
import 'package:raffle/page/tickets.dart';
import 'package:raffle/screen/home.dart';
void main() {
// Set the system UI overlay style globally
SystemChrome.setSystemUIOverlayStyle(system);
runApp(const MyApp());
}
const MaterialColor primaryColor = MaterialColor(
0xFF25D366,
<int, Color>{
50: Color(0xFFE5F9ED),
100: Color(0xFFB9F0C7),
200: Color(0xFF8CEA9F),
300: Color(0xFF5CE47B),
400: Color(0xFF39DC5F),
500: Color(0xFF25D366),
600: Color(0xFF1EB95F),
700: Color(0xFF188F52),
800: Color(0xFF126647),
900: Color(0xFF0A362E),
},
);
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
// Check if the app is running on the web
const bool isWeb = kIsWeb;
// Set the maximum width for the web app
const double maxWidth = 500.0;
// Wrap the MaterialApp with the Center and LayoutBuilder widgets
Widget app = isWeb
? Container(
color: Colors.black,
child: Center(
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
double appWidth = constraints.maxWidth < maxWidth
? constraints.maxWidth
: maxWidth;
return SizedBox(
width: appWidth,
child: buildMaterialApp(),
);
},
),
),
)
: buildMaterialApp();
final RaffleProvider raffleProvider = RaffleProvider();
return MultiProvider(
providers: [
ChangeNotifierProvider<RaffleProvider>(
create: (_) => raffleProvider,
),
],
child: app,
);
}
MaterialApp buildMaterialApp() {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: primaryColor,
focusColor: const Color(0xFF188F52),
unselectedWidgetColor: Colors.white,
cardColor: const Color(0xFF188F52),
textTheme: const TextTheme(
bodyLarge: TextStyle(color: Colors.white),
bodyMedium: TextStyle(color: Colors.white),
titleMedium: TextStyle(color: Colors.white),
titleLarge: TextStyle(color: Colors.white),
bodySmall: TextStyle(color: Colors.white),
labelLarge: TextStyle(color: Colors.white),
),
iconTheme: const IconThemeData(color: Colors.white),
colorScheme: ColorScheme.fromSwatch(
primarySwatch: primaryColor,
),
appBarTheme: AppBarTheme(
color: primaryColor.shade700, foregroundColor: Colors.white),
),
home: const HomeScreen(),
routes: {
'/myticket': (context) => const MyTicket(),
'/notifications': (context) => const NotificationsPage(),
},
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/page/raffle.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/widget/ticket.dart';
import 'package:flutter_html/flutter_html.dart';
class RafflePage extends StatelessWidget {
final Raffle raffle;
const RafflePage({super.key, required this.raffle});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: Provider.of<RaffleProvider>(context),
child: Scaffold(
appBar: AppBar(
title: Text('Raffe: ${raffle.name}'),
systemOverlayStyle: system,
),
body: SingleChildScrollView(
child: Column(
children: [
TicketWidget(show: false, raffle: raffle),
Padding(
padding: const EdgeInsets.all(10),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
blurRadius: 10,
offset: const Offset(0, 5),
),
],
),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Prize',
style: TextStyle(
fontSize: 14,
),
),
Text(
raffle.name,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Ticket price',
style: TextStyle(
fontSize: 14,
),
),
Text(
'₦ ${raffle.ticketPrice}',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Text(
'Ticket Total',
style: TextStyle(
fontSize: 14,
),
),
Text(
'100 %',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Ticket Sold',
style: TextStyle(
fontSize: 14,
),
),
Text(
'${(raffle.ticketsSold / (raffle.ticketsAvailable + raffle.ticketsSold)) * 100} %',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Ticket Available',
style: TextStyle(
fontSize: 14,
),
),
Text(
'${(raffle.ticketsAvailable / (raffle.ticketsAvailable + raffle.ticketsSold)) * 100} %',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Created Date',
style: TextStyle(
fontSize: 14,
),
),
Text(
raffle.createdAt.toString().substring(0, 19),
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Start Date',
style: TextStyle(
fontSize: 14,
),
),
Text(
raffle.startDate.toString().substring(0, 19),
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Html(
data: raffle.description,
),
),
],
),
),
),
),
const SizedBox(height: 20),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/page/notifications.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/main.dart';
class NotificationsPage extends StatelessWidget {
const NotificationsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: Provider.of<RaffleProvider>(context),
child: Consumer<RaffleProvider>(
builder: (context, provider, _) {
if (provider.notificationsList == null) {
provider.getNotifications();
return const Center(child: CircularProgressIndicator());
} else {
final notifications = provider.notificationsList;
return Scaffold(
appBar: AppBar(
title: const Text('Notifications'),
systemOverlayStyle: system,
),
body: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: notifications!.length,
itemBuilder: (context, index) {
final notification = notifications[index];
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
blurRadius: 10,
offset: const Offset(0, 5),
),
],
),
child: ListTile(
title: Text(
notification.createdAt.toString().substring(0, 19),
style: const TextStyle(
fontWeight: FontWeight.bold, color: Colors.black),
),
subtitle: Text(
notification.message.replaceFirst("You", "Someone"),
style: TextStyle(color: primaryColor.shade900),
),
trailing: const Icon(Icons.notifications),
onTap: () {
// Handle notification tap here
},
),
),
);
},
),
);
}
},
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/page/tickets.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/main.dart';
import 'package:raffle/page/raffle.dart';
import 'package:raffle/screen/account.dart';
class MyTicket extends StatelessWidget {
const MyTicket({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: Provider.of<RaffleProvider>(context),
child: Consumer<RaffleProvider>(
builder: (context, provider, _) {
if (provider.user == null) {
return const Account();
} else if (provider.userTickets == null) {
provider.getUserTickets();
return const Center(child: CircularProgressIndicator());
} else {
final ticket = provider.userTickets;
return Scaffold(
appBar: AppBar(
title: const Text('My Tickets'),
),
body: ListView.builder(
padding: const EdgeInsets.only(top: 15, bottom: 15),
itemCount: ticket?.length,
itemBuilder: (context, index) {
return ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RafflePage(
raffle: ticket![index].raffle,
),
),
);
},
title: Text(
'${ticket?[index].raffle.name}',
style: const TextStyle(
fontWeight: FontWeight.bold, color: Colors.black),
),
subtitle: Text(
' ₦${ticket?[index].raffle.ticketPrice}',
style: TextStyle(color: primaryColor.shade900),
),
trailing: Text(
'${ticket?[index].createdAt.toString().substring(0, 19)}',
style: TextStyle(color: primaryColor.shade900),
),
);
},
),
);
}
},
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/screen/account.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/main.dart';
import 'package:url_launcher/url_launcher.dart';
class Account extends StatefulWidget {
const Account({Key? key}) : super(key: key);
@override
AccountState createState() => AccountState();
}
class AccountState extends State<Account> {
final signinkey = GlobalKey<FormState>();
final signupkey = GlobalKey<FormState>();
final signinusernameController = TextEditingController();
final signinpasswordController = TextEditingController();
final signupnamesController = TextEditingController();
final signupusernameController = TextEditingController();
final signuppasswordController = TextEditingController();
late Widget account;
String? signinusernameError;
String? signinpasswordError;
String? signupusernameError;
String? signuppasswordError;
bool loading = false;
@override
void initState() {
super.initState();
account = signinWidget();
signinusernameController.addListener(signinvalidateUsername);
signupusernameController.addListener(signupvalidateUsername);
signinpasswordController.addListener(signinvalidatePassword);
signuppasswordController.addListener(signupvalidatePassword);
}
void signupvalidateUsername() {
if (signupusernameController.text.isEmpty) {
setState(
() {
signupusernameError = 'Please enter your username';
},
);
} else if (signupusernameController.text.length <= 4) {
setState(
() {
signupusernameError = 'username must not be less than 5';
},
);
} else {
setState(
() {
signupusernameError = null;
},
);
}
}
void signinvalidateUsername() {
if (signinusernameController.text.isEmpty) {
setState(
() {
signinusernameError = 'Please enter your username';
},
);
} else if (signinusernameController.text.length <= 4) {
setState(
() {
signinusernameError = 'username must not be less than 5';
},
);
} else {
setState(
() {
signinusernameError = null;
},
);
}
}
void signinvalidatePassword() {
RegExp number = RegExp(r'[0-9]');
if (signinpasswordController.text.isEmpty) {
setState(() {
signinpasswordError = 'Please enter your password';
});
}
if (!number.hasMatch(signinpasswordController.text)) {
setState(() {
signinpasswordError = 'at least one number (0123456789)';
});
} else {
setState(() {
signinpasswordError = null;
});
}
}
void signupvalidatePassword() {
RegExp number = RegExp(r'[0-9]');
RegExp symbol = RegExp(r'[!@#\$%^&*]');
if (signuppasswordController.text.isEmpty) {
setState(() {
signuppasswordError = 'Please enter your password';
});
} else if (signuppasswordController.text.length <= 8) {
setState(() {
signuppasswordError = 'must not less than 8';
});
} else if (!number.hasMatch(signuppasswordController.text)) {
setState(() {
signuppasswordError = 'at least one number (0123456789)';
});
} else if (!symbol.hasMatch(signuppasswordController.text)) {
return setState(() {
signuppasswordError = 'at least one symbols (!@#\$%^&*)';
});
} else {
setState(() {
signuppasswordError = null;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (context, constraints) {
return Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/123.webp'),
fit: BoxFit.cover,
),
),
child: SingleChildScrollView(
child: Column(
children: [
Container(
width: constraints.maxWidth,
height: constraints.maxHeight,
padding: const EdgeInsets.all(30),
decoration: background,
child: Center(child: account),
),
Container(
width: constraints.maxWidth,
height: constraints.maxHeight,
padding: const EdgeInsets.all(30),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.5),
),
child: website(),
),
],
),
),
);
},
),
);
}
Widget website() {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
"Lucky Tree Raffle Draw",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(height: 20),
Row(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextButton(
onPressed: () async {
if (!await launchUrl(
Uri.parse('http://127.0.0.1:8880/policy'))) {
throw 'Could not launch http://127.0.0.1:8880/policy';
}
},
child: const Text("Privacy Policy"),
),
const SizedBox(height: 10),
TextButton(
onPressed: () async {
if (!await launchUrl(
Uri.parse('http://127.0.0.1:8880/terms'))) {
throw 'Could not launch http://127.0.0.1:8880/terms';
}
},
child: const Text("Terms and Conditions"),
),
const SizedBox(height: 10),
TextButton(
onPressed: () async {
if (!await launchUrl(Uri.parse(
'http://127.0.0.1:8880/frequently-asked-questions'))) {
throw 'Could not launch http://127.0.0.1:8880/frequently-asked-questions';
}
},
child: const Text("FAQ"),
),
const SizedBox(height: 10),
],
),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
TextButton(
onPressed: () async {
if (!await launchUrl(
Uri.parse('http://127.0.0.1:8880/#about'))) {
throw 'Could not launch http://127.0.0.1:8880/#about';
}
},
child: const Text("About Us"),
),
const SizedBox(height: 10),
TextButton(
onPressed: () async {
if (!await launchUrl(
Uri.parse('http://127.0.0.1:8880/#contact'))) {
throw 'Could not launch http://127.0.0.1:8880/#contact';
}
},
child: const Text("Support"),
),
const SizedBox(height: 10),
TextButton(
onPressed: () async {
if (!await launchUrl(
Uri.parse('http://127.0.0.1:8880/#howto'))) {
throw 'Could not launch http://127.0.0.1:8880/#howto';
}
},
child: const Text("How To"),
),
],
),
),
],
),
],
);
}
Widget signinWidget() {
return Consumer<RaffleProvider>(
builder: (context, provider, _) {
return SingleChildScrollView(
child: Form(
key: signinkey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
"assets/images/logo.png",
height: 130,
),
const SizedBox(height: 20),
TextFormField(
style: const TextStyle(color: Colors.black),
controller: signinusernameController,
keyboardType: TextInputType.visiblePassword,
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.isEmpty) {
return "Please enter your username or email";
}
return signinusernameError;
},
onChanged: (String value) {
signinkey.currentState!.validate();
},
decoration: textinput('Username or Email'),
),
const SizedBox(height: 20),
TextFormField(
style: const TextStyle(color: Colors.black),
obscureText: true,
controller: signinpasswordController,
keyboardType: TextInputType.visiblePassword,
textInputAction: TextInputAction.next,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter a password';
}
return signinpasswordError;
},
onChanged: (String value) {
signinkey.currentState!.validate();
},
decoration: textinput('Password'),
),
const SizedBox(height: 20),
ElevatedButton(
style: ElevatedButton.styleFrom(
fixedSize: const Size(200, 40),
),
onPressed: () {
if (signinkey.currentState!.validate()) {
provider
.getUserProfile(
username: signinusernameController.text,
password: signinpasswordController.text,
)
.then((value) {
if (value is! User) {
setState(() {
signinusernameError = value as String?;
signinpasswordError = value;
});
}
});
}
},
child: const Text(
"Sign In",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
const SizedBox(height: 20),
const Text(
"By signing in, you agree to our Terms, Data Policy and Cookies Policy.",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
color: Colors.grey,
),
),
const SizedBox(height: 10),
const Text(
"Don't have an account? ",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
color: Colors.grey,
),
),
InkWell(
onTap: () {
setState(() {
account = signupWidget();
});
},
child: const Text(
"Sign Up",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: primaryColor,
),
),
),
const SizedBox(height: 20),
],
),
),
);
},
);
}
Widget signupWidget() {
return SingleChildScrollView(
child: Form(
key: signupkey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
"assets/images/logo.png",
height: 130,
),
const SizedBox(height: 20),
TextFormField(
style: const TextStyle(color: Colors.black),
decoration: textinput('Email Address'),
validator: (value) {
if (value == null || value.isEmpty) {
return "Please enter your email address";
}
return signupusernameError;
},
),
const SizedBox(height: 20),
TextFormField(
style: const TextStyle(color: Colors.black),
controller: signupusernameController,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.next,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter a username';
}
return null;
},
onChanged: (String value) {
signupkey.currentState!.validate();
},
decoration: textinput('Full Name'),
),
const SizedBox(height: 20),
TextFormField(
style: const TextStyle(color: Colors.black),
obscureText: true,
controller: signuppasswordController,
keyboardType: TextInputType.visiblePassword,
textInputAction: TextInputAction.next,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter a password';
}
return null;
},
onChanged: (String value) {
signupkey.currentState!.validate();
},
decoration: textinput('Password'),
),
const SizedBox(height: 20),
ElevatedButton(
style: ElevatedButton.styleFrom(
fixedSize: const Size(200, 40),
),
onPressed: () {
if (signupkey.currentState!.validate()) {
print(signupusernameController.text);
print(signuppasswordController.text);
}
},
child: const Text(
"Sign Up",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
const SizedBox(height: 20),
const Text(
"By signing up, you agree to our Terms, Data Policy and Cookies Policy.",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
color: Colors.grey,
),
),
const SizedBox(height: 10),
const Text(
"Have an account? ",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
color: Colors.grey,
),
),
InkWell(
onTap: () {
setState(() {
account = signinWidget();
});
},
child: const Text(
"Sign in",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: primaryColor,
),
),
),
const SizedBox(height: 20),
],
),
),
);
}
InputDecoration textinput(label) {
return InputDecoration(
labelText: label,
filled: true,
fillColor: Colors.grey[200],
border: const OutlineInputBorder(),
labelStyle: TextStyle(
color: Colors.grey.shade800,
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/screen/raffles.dart
|
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/widget/ticket.dart';
class RaffleScreen extends StatelessWidget {
const RaffleScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final GlobalKey<RefreshIndicatorState> refreshIndicatorKey =
GlobalKey<RefreshIndicatorState>();
bool isDesktop;
try {
isDesktop = (!Platform.isIOS && !Platform.isAndroid);
} catch (e) {
isDesktop = false;
}
return ChangeNotifierProvider.value(
value: Provider.of<RaffleProvider>(context),
child: Consumer<RaffleProvider>(
builder: (context, provider, _) {
if (provider.raffles.isEmpty) {
provider.fetchRaffles();
return const Center(child: CircularProgressIndicator());
} else {
final data = provider.raffles.reversed.toList();
return isDesktop
? Scaffold(
appBar: AppBar(
title: Text('${data.length} Raffle Available'),
),
body: RefreshIndicator(
key: refreshIndicatorKey,
onRefresh: provider.fetchRaffles,
child: rafflesw(provider),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
refreshIndicatorKey.currentState?.show();
},
tooltip: 'Refresh',
child: const Icon(Icons.refresh),
),
)
: RefreshIndicator(
key: refreshIndicatorKey,
onRefresh: provider.fetchRaffles,
child: rafflesw(provider),
);
}
},
),
);
}
Widget rafflesw(provider) {
final data = provider.raffles.reversed.toList();
return SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
children: [
for (final raffle in data)
TicketWidget(
show: true,
raffle: raffle,
),
],
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/screen/winners.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:raffle/screen/account.dart';
class WinnerList extends StatelessWidget {
const WinnerList({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: Provider.of<RaffleProvider>(context),
child: Consumer<RaffleProvider>(
builder: (context, provider, _) {
if (provider.user == null) {
return const Account();
} else if (provider.notificationsList == null) {
provider.getNotifications();
return const Center(child: CircularProgressIndicator());
} else {
final notifications = provider.notificationsList;
return Scaffold(
appBar: AppBar(
title: const Text('List of Winners'),
systemOverlayStyle: system,
),
body: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: notifications!.length,
itemBuilder: (context, index) {
//final winner = notifications[index];
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
blurRadius: 10,
offset: const Offset(0, 5),
),
],
),
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: InkWell(
onTap: () async {
const url = 'https://www.example.com';
if (!await launchUrl(Uri.parse(url))) {
throw 'Could not launch $url';
}
},
child: Padding(
padding: const EdgeInsets.all(15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Lucky poor women Won a Car',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
SizedBox(
height: 50,
child: Text(
'winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message winner.message',
style: TextStyle(
fontSize: 14,
color: Colors.grey[200],
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
),
),
);
},
),
);
}
},
),
);
}
}
| 0
|
mirrored_repositories/raffle-flutter/lib
|
mirrored_repositories/raffle-flutter/lib/screen/me.dart
|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:raffle/constant/variable.dart';
import 'package:raffle/main.dart';
import 'package:raffle/screen/account.dart';
import 'package:url_launcher/url_launcher.dart';
class AccountScreen extends StatelessWidget {
const AccountScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider.value(
value: Provider.of<RaffleProvider>(context),
child: Consumer<RaffleProvider>(
builder: (context, provider, _) {
if (provider.user == null) {
return const Account();
} else if (provider.user == null ||
provider.userTickets == null ||
provider.userNotifications == null) {
provider.getUserNotifications();
provider.getUserTickets();
return const Center(child: CircularProgressIndicator());
} else {
final user = provider.user;
final ticket = provider.userTickets;
final notifications = provider.userNotifications;
return Scaffold(
appBar: AppBar(
title: const Text("My Account"),
systemOverlayStyle: system,
actions: [
IconButton(
iconSize: 32,
icon: const Icon(Icons.logout),
onPressed: () {},
),
],
),
body: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
InkWell(
onTap: () {
Navigator.pushNamed(
context,
'/myticket',
);
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
blurRadius: 10,
offset: const Offset(0, 5),
),
],
),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.center,
children: <Widget>[
const Text(
'My Tickets',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
Text(
ticket!.length.toString(),
style: const TextStyle(
fontSize: 40,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 20),
],
),
),
),
),
),
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
blurRadius: 10,
offset: const Offset(0, 5),
),
],
),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 10,
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const CircleAvatar(
radius: 40,
backgroundColor: Colors.white,
backgroundImage:
AssetImage('images/2.webp'),
),
const SizedBox(height: 16),
Text(
user!.username,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
const SizedBox(height: 8),
Text(
'${user.firstName} ${user.lastName}',
style: const TextStyle(
fontSize: 16,
),
),
const SizedBox(height: 8),
Text(
user.email,
style: const TextStyle(
fontSize: 16,
),
),
],
),
),
),
),
],
),
),
SizedBox(
height: 400,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: notifications!.length,
itemBuilder: (context, index) {
final notification = notifications[index];
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 10),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
blurRadius: 10,
offset: const Offset(0, 5),
),
],
),
child: ListTile(
title: Text(
notification.createdAt
.toString()
.substring(0, 19),
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black),
),
subtitle: Text(
notification.message,
style:
TextStyle(color: primaryColor.shade900),
),
trailing:
const Icon(Icons.notifications_active),
onTap: () {
// Handle notification tap here
},
),
),
);
},
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
if (!await launchUrl(
Uri.parse('http://127.0.0.1:8880/contact'))) {
throw 'Could not launch http://127.0.0.1:8880/contact';
}
},
child: const Icon(
Icons.chat_sharp,
color: Colors.white,
),
),
);
}
},
),
);
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.