repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/FootballSchedule | mirrored_repositories/FootballSchedule/lib/home.dart | import 'package:flutter/material.dart';
import 'package:football_schedule/next/next_match.dart';
import 'package:football_schedule/previous/previous_match.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
var _pageState = 0;
var _appBarTitle = 'Previous Match';
void updatePage(int page , String title){
setState(() {
_pageState = page;
_appBarTitle = title;
});
}
Widget body(){
switch(_pageState){
case 0: return PreviousMatch();
case 1: return NextMatch();
default: return PreviousMatch();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_appBarTitle),
),
body: body(),
drawer: Drawer(
child: Column(
children: <Widget>[
Container(
color: Theme.of(context).primaryColor,
child: DrawerHeader(
child: Center(
child: Text(
'Hi',
style: TextStyle(fontSize: 24.0, color: Colors.white),
)
),
),
),
ListTile(
onTap: (){
Navigator.of(context).pop();
updatePage(0 , 'Previous Match');
},
leading: Icon(Icons.today),
title: Text('Previous Match'),
),
ListTile(
onTap: (){
Navigator.of(context).pop();
updatePage(1 , 'Next Match');
},
leading: Icon(Icons.access_alarms),
title: Text('Next Match'),
)
],
)
),
);
}
}
| 0 |
mirrored_repositories/FootballSchedule/lib | mirrored_repositories/FootballSchedule/lib/next/next_match.dart | import 'package:flutter/material.dart';
import 'package:football_schedule/entity/match_item.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
import 'package:football_schedule/next/next_item.dart';
class NextMatch extends StatefulWidget {
@override
_NextMatchState createState() => _NextMatchState();
}
class _NextMatchState extends State<NextMatch> {
Future<List<NextItem>> fetchMatch() async {
final request = await http.get(
'https://www.thesportsdb.com/api/v1/json/1/eventsnextleague.php?id=4328');
if (request.statusCode == 200) {
List response = json.decode(request.body)['events'];
List<NextItem> data = [];
for (int i = 0; i < response.length; i++) {
data.add(NextItem(
match: MatchItem(
dateMatch: response[i]['dateEvent'],
homeTeamName: response[i]['strHomeTeam'],
awayTeamName: response[i]['strAwayTeam'],
homeTeamId: response[i]['idHomeTeam'],
awayTeamId: response[i]['idAwayTeam'])));
}
return data;
} else {
return [];
}
}
Widget loadingPage() {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.orangeAccent,
),
);
}
Widget homePage(List<NextItem> events) {
return ListView.builder(
itemBuilder: (context, index) => events[index],
itemCount: events.length,
);
}
Widget errorPage() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Failed To Retrive Data',
style: TextStyle(fontSize: 17.0 , fontWeight: FontWeight.bold),
),
),
RaisedButton(
onPressed: () {
fetchMatch();
print('pressed');
},
child: Text('Try Again'),
)
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<NextItem>>(
future: fetchMatch(),
builder: (context, snapshot) {
print(snapshot.connectionState);
switch (snapshot.connectionState) {
case ConnectionState.none:
return errorPage();
case ConnectionState.active:
return loadingPage();
case ConnectionState.waiting:
return loadingPage();
case ConnectionState.done:
if (snapshot.hasData) {
print('has data');
return homePage(snapshot.data);
} else if (snapshot.hasError) {
print('has error');
return errorPage();
} else {
return loadingPage();
}
}
}),
);
}
} | 0 |
mirrored_repositories/FootballSchedule/lib | mirrored_repositories/FootballSchedule/lib/next/next_item.dart | import 'package:flutter/material.dart';
import 'package:football_schedule/entity/match_item.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
class NextItem extends StatefulWidget {
final MatchItem match;
const NextItem({Key key, this.match}) : super(key: key);
@override
_NextItemState createState() => _NextItemState(match);
}
class _NextItemState extends State<NextItem> {
final MatchItem match;
_NextItemState(this.match);
String teamHomeBadge = "";
String teamAwayBadge = "";
String dateMatch;
Widget homeBadge() {
if (teamHomeBadge.isEmpty) {
return defaultBadge();
} else {
return CachedNetworkImage(
width: 50.0,
height: 50.0,
imageUrl: teamHomeBadge,
placeholder: CircularProgressIndicator(),
errorWidget: defaultBadge(),
);
}
}
Widget awayBadge() {
if (teamAwayBadge.isEmpty) {
return defaultBadge();
} else {
return CachedNetworkImage(
width: 50.0,
height: 50.0,
imageUrl: teamAwayBadge,
placeholder: CircularProgressIndicator(),
errorWidget: defaultBadge(),
);
}
}
Widget defaultBadge() {
return Icon(
Icons.android,
size: 50.0,
color: Theme.of(context).primaryColor,
);
}
Future loadAwayTeam(String id) async {
final request = await http
.get("https://www.thesportsdb.com/api/v1/json/1/lookupteam.php?id=$id");
if (request.statusCode == 200) {
List response = json.decode(request.body)['teams'];
setState(() {
teamAwayBadge = response[0]['strTeamBadge'];
});
}
}
Future loadHomeTeam(String id) async {
final request = await http
.get("https://www.thesportsdb.com/api/v1/json/1/lookupteam.php?id=$id");
if (request.statusCode == 200) {
List response = json.decode(request.body)['teams'];
setState(() {
teamHomeBadge = response[0]['strTeamBadge'];
});
}
}
@override
void initState() {
super.initState();
String homeId = match.homeTeamId;
String awayId = match.awayTeamId;
loadAwayTeam(awayId);
loadHomeTeam(homeId);
initializeDateFormatting("in_ID");
DateFormat f = DateFormat("dd MMMM yyyy", "id");
dateMatch = f.format(DateTime.parse(match.dateMatch));
}
@override
Widget build(BuildContext context) {
return Material(
child: Container(
height: 130.0,
child: InkWell(
onTap: () {
print(match.dateMatch);
},
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 10.0),
child: Text(
dateMatch,
style: TextStyle(
fontSize: 17.0,
color: Colors.orangeAccent,
fontWeight: FontWeight.bold),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
flex: 3,
child: Center(
child: new Container(
height: 100.0,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
homeBadge(),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: Text(match.homeTeamName),
)
],
),
flex: 4,
)
],
),
),
),
),
),
Expanded(
flex: 1,
child: Center(
child: new Text(
'VS',
style: TextStyle(fontSize: 20.0),
),
),
),
Expanded(
flex: 3,
child: new Container(
height: 100.0,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
awayBadge(),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: Text(match.awayTeamName),
)
],
),
flex: 4,
),
],
),
),
),
),
],
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/FootballSchedule/lib | mirrored_repositories/FootballSchedule/lib/previous/previous_item.dart | import 'package:flutter/material.dart';
import 'package:football_schedule/entity/match_item.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
class PreviousItem extends StatefulWidget {
final MatchItem match;
const PreviousItem({Key key, this.match}) : super(key: key);
@override
_PreviousItemState createState() => _PreviousItemState(match);
}
class _PreviousItemState extends State<PreviousItem> {
final MatchItem match;
_PreviousItemState(this.match);
String teamHomeBadge = "";
String teamAwayBadge = "";
String dateMatch;
Widget homeBadge() {
if (teamHomeBadge.isEmpty) {
return defaultBadge();
} else {
return CachedNetworkImage(
width: 50.0,
height: 50.0,
imageUrl: teamHomeBadge,
placeholder: CircularProgressIndicator(),
errorWidget: defaultBadge(),
);
}
}
Widget awayBadge() {
if (teamAwayBadge.isEmpty) {
return defaultBadge();
} else {
return CachedNetworkImage(
width: 50.0,
height: 50.0,
imageUrl: teamAwayBadge,
placeholder: CircularProgressIndicator(),
errorWidget: defaultBadge(),
);
}
}
Widget defaultBadge() {
return Icon(
Icons.android,
size: 50.0,
color: Theme.of(context).primaryColor,
);
}
Future loadAwayTeam(String id) async {
final request = await http
.get("https://www.thesportsdb.com/api/v1/json/1/lookupteam.php?id=$id");
if (request.statusCode == 200) {
List response = json.decode(request.body)['teams'];
setState(() {
teamAwayBadge = response[0]['strTeamBadge'];
});
}
}
Future loadHomeTeam(String id) async {
final request = await http
.get("https://www.thesportsdb.com/api/v1/json/1/lookupteam.php?id=$id");
if (request.statusCode == 200) {
List response = json.decode(request.body)['teams'];
setState(() {
teamHomeBadge = response[0]['strTeamBadge'];
});
}
}
@override
void initState() {
super.initState();
String homeId = match.homeTeamId;
String awayId = match.awayTeamId;
loadAwayTeam(awayId);
loadHomeTeam(homeId);
initializeDateFormatting("in_ID");
DateFormat f = DateFormat("dd MMMM yyyy", "id");
dateMatch = f.format(DateTime.parse(match.dateMatch));
}
@override
Widget build(BuildContext context) {
return Material(
child: Container(
height: 130.0,
child: InkWell(
onTap: () {
print(match.dateMatch);
},
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 10.0),
child: Text(
dateMatch,
style: TextStyle(
fontSize: 17.0,
color: Colors.orangeAccent,
fontWeight: FontWeight.bold),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
flex: 3,
child: Center(
child: new Container(
height: 100.0,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
homeBadge(),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: Text(match.homeTeamName),
)
],
),
flex: 4,
),
Expanded(
child: Align(
alignment: Alignment.centerLeft,
child: Text(
match.awayTeamScore,
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold),
),
),
flex: 1,
)
],
),
),
),
),
),
Expanded(
flex: 1,
child: Center(
child: new Text(
'VS',
style: TextStyle(fontSize: 20.0),
),
),
),
Expanded(
flex: 3,
child: new Container(
height: 100.0,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Align(
alignment: Alignment.centerRight,
child: Text(
match.awayTeamScore,
style: TextStyle(
fontSize: 30.0,
fontWeight: FontWeight.bold),
),
),
flex: 1,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
awayBadge(),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: Text(match.awayTeamName),
)
],
),
flex: 4,
),
],
),
),
),
),
],
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/FootballSchedule/lib | mirrored_repositories/FootballSchedule/lib/previous/previous_match.dart | import 'package:flutter/material.dart';
import 'package:football_schedule/entity/match_item.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
import 'package:football_schedule/previous/previous_item.dart';
class PreviousMatch extends StatefulWidget {
@override
_PreviousMatchState createState() => _PreviousMatchState();
}
class _PreviousMatchState extends State<PreviousMatch> {
Future<List<PreviousItem>> fetchMatch() async {
final request = await http.get(
'https://www.thesportsdb.com/api/v1/json/1/eventspastleague.php?id=4328');
if (request.statusCode == 200) {
List response = json.decode(request.body)['events'];
List<PreviousItem> data = [];
for (int i = 0; i < response.length; i++) {
data.add(PreviousItem(
match: MatchItem(
dateMatch: response[i]['dateEvent'],
homeTeamName: response[i]['strHomeTeam'],
awayTeamName: response[i]['strAwayTeam'],
homeTeamId: response[i]['idHomeTeam'],
awayTeamId: response[i]['idAwayTeam'],
homeTeamScore: response[i]['intHomeScore'],
awayTeamScore: response[i]['intAwayScore'])));
}
return data;
} else {
return [];
}
}
Widget loadingPage() {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.orangeAccent,
),
);
}
Widget homePage(List<PreviousItem> events) {
return ListView.builder(
itemBuilder: (context, index) => events[index],
itemCount: events.length,
);
}
Widget errorPage() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Failed To Retrive Data',
style: TextStyle(fontSize: 17.0 , fontWeight: FontWeight.bold),
),
),
RaisedButton(
onPressed: () {
fetchMatch();
print('pressed');
},
child: Text('Try Again'),
)
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<PreviousItem>>(
future: fetchMatch(),
builder: (context, snapshot) {
print(snapshot.connectionState);
switch (snapshot.connectionState) {
case ConnectionState.none:
return errorPage();
case ConnectionState.active:
return loadingPage();
case ConnectionState.waiting:
return loadingPage();
case ConnectionState.done:
if (snapshot.hasData) {
print('has data');
return homePage(snapshot.data);
} else if (snapshot.hasError) {
print('has error');
return errorPage();
} else {
return loadingPage();
}
}
}),
);
}
}
| 0 |
mirrored_repositories/FootballSchedule/lib | mirrored_repositories/FootballSchedule/lib/entity/match_item.dart | import 'package:flutter/material.dart';
class MatchItem {
final String dateMatch;
final String homeTeamName;
final String awayTeamName;
final String homeTeamId;
final String awayTeamId;
final String homeTeamScore;
final String awayTeamScore;
const MatchItem(
{@required this.dateMatch,
@required this.homeTeamName,
@required this.awayTeamName,
@required this.homeTeamId,
@required this.awayTeamId,
this.homeTeamScore,
this.awayTeamScore});
}
| 0 |
mirrored_repositories/flutter-google-clone | mirrored_repositories/flutter-google-clone/lib/styles.dart | import 'package:flutter/cupertino.dart';
class Styles {
static const TextStyle heading = TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
);
static const TextStyle url = TextStyle(
fontSize: 14.0,
color: CupertinoColors.activeBlue,
fontWeight: FontWeight.w400,
);
}
| 0 |
mirrored_repositories/flutter-google-clone | mirrored_repositories/flutter-google-clone/lib/main.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:search/screens/home_page.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
var dir = await getApplicationDocumentsDirectory();
await Hive.initFlutter(dir.path);
await Hive.openBox('recents');
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const CupertinoApp(
title: 'Flutter Demo',
theme: CupertinoThemeData(
brightness: Brightness.light,
),
home: MyHomePage(),
);
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/main_page/web_view.dart | import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:search/all_web_model/web_search.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebSiteView extends StatefulWidget {
final WebSearch url;
const WebSiteView({
Key? key,
required this.url,
}) : super(key: key);
@override
_WebSiteViewState createState() => _WebSiteViewState();
}
class _WebSiteViewState extends State<WebSiteView> {
Completer<WebViewController> _controller = Completer<WebViewController>();
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Column(
children: [
SafeArea(
child: Container(
padding: const EdgeInsets.all(16),
child: Row(
children: [
GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(
Icons.arrow_back_ios,
),
),
),
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.url.title!,
maxLines: 1,
style: const TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Text(
widget.url.url!,
maxLines: 1,
style: const TextStyle(
color: Colors.black,
fontSize: 14,
),
),
],
),
),
GestureDetector(
onTap: () {
launch(widget.url.url!);
},
child: const Icon(Icons.open_in_browser))
],
),
),
),
Expanded(
child: WebView(
initialUrl: widget.url.url,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/main_page/main_page_screen.dart | // ignore: file_names
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:search/controllers/main_controller.dart';
import 'package:search/main_page/widgets/list_tile.dart';
class MainPageScreen extends StatefulWidget {
final String query;
MainPageScreen({
Key? key,
required this.query,
}) : super(key: key);
static const routeName = '/main_page';
@override
State<MainPageScreen> createState() => MainPageScreenState();
}
class MainPageScreenState extends State<MainPageScreen> {
@override
void initState() {
Provider.of<MainController>(context, listen: false).search(widget.query);
super.initState();
}
@override
Widget build(BuildContext context) {
return Consumer<MainController>(
builder: (context, controller, child) {
return Container(
child: controller.searchList.isEmpty
? const Center(child: CupertinoActivityIndicator())
: ListView.builder(
itemCount: controller.searchList.length,
itemBuilder: (context, i) {
final element = controller.searchList[i];
return SearchResultTile(
result: element,
);
},
),
);
},
);
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/main_page/news_screen.dart | // ignore: file_names
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:search/controllers/main_controller.dart';
import 'package:search/main_page/widgets/list_tile.dart';
class NewsScreen extends StatefulWidget {
final String query;
NewsScreen({
Key? key,
required this.query,
}) : super(key: key);
static const routeName = '/main_page';
@override
State<NewsScreen> createState() => NewsScreenState();
}
class NewsScreenState extends State<NewsScreen> {
@override
void initState() {
Provider.of<MainController>(context, listen: false).news(widget.query);
super.initState();
}
@override
Widget build(BuildContext context) {
return Consumer<MainController>(
builder: (context, controller, child) {
return Container(
child: controller.newsList.isEmpty
? const Center(child: CupertinoActivityIndicator())
: ListView.builder(
itemCount: controller.newsList.length,
itemBuilder: (context, i) {
final element = controller.newsList[i];
return SearchResultTile(
result: element,
);
},
),
);
},
);
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/main_page/images_screen.dart | // ignore: file_names
// import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:provider/provider.dart';
import 'package:search/controllers/main_controller.dart';
// import 'package:google/src/main_page/widgets/list_tile.dart';
class ImageScreen extends StatefulWidget {
final String query;
ImageScreen({
Key? key,
required this.query,
}) : super(key: key);
@override
State<ImageScreen> createState() => ImageScreenState();
}
class ImageScreenState extends State<ImageScreen> {
@override
void initState() {
Provider.of<MainController>(context, listen: false)
.searchImages(widget.query);
super.initState();
}
@override
Widget build(BuildContext context) {
return Consumer<MainController>(
builder: (context, controller, child) {
return Container(
child: controller.images.isEmpty
? const Center(child: CupertinoActivityIndicator())
: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2),
itemCount: controller.images.length,
itemBuilder: (context, i) {
final element = controller.images[i];
return Padding(
padding: const EdgeInsets.all(4.0),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CupertinoPageScaffold(
child: Hero(
tag: element.url!,
child: PhotoView(
imageProvider: CachedNetworkImageProvider(
element.url!,
),
),
),
),
),
);
},
child: Hero(
tag: element.url!,
child: CachedNetworkImage(
imageUrl: element.url!,
errorWidget: (context, url, error) =>
Image.network(
"https://images.pexels.com/photos/4271933/pexels-photo-4271933.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
fit: BoxFit.cover,
),
fit: BoxFit.cover),
),
),
);
},
),
);
},
);
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/main_page/all_screen.dart | import 'package:flutter/animation.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:provider/provider.dart';
import 'package:search/controllers/main_controller.dart';
import 'package:search/main_page/images_screen.dart';
import 'package:search/screens/recent.dart';
import 'main_page_screen.dart';
import 'news_screen.dart';
class AllScreens extends StatefulWidget {
final String query;
const AllScreens({
Key? key,
required this.query,
}) : super(key: key);
@override
_AllScreensState createState() => _AllScreensState();
}
class _AllScreensState extends State<AllScreens> {
String query = "";
int segmentedControlGroupValue = 0;
PageController cont = PageController(initialPage: 0);
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Column(
children: [
SafeArea(
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 20.0, vertical: 10),
child: CupertinoTextField(
readOnly: true,
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Recents()));
},
placeholder: widget.query,
placeholderStyle: const TextStyle(color: Colors.black),
suffix: const Padding(
padding: EdgeInsets.only(right: 16.0),
child: Icon(CupertinoIcons.search),
),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey.shade100,
),
),
),
CupertinoSlidingSegmentedControl(
groupValue: segmentedControlGroupValue,
children: const {
0: Text("All"),
1: Text("Images"),
2: Text("News")
},
onValueChanged: (int? i) {
setState(() {
segmentedControlGroupValue = i!;
});
cont.animateToPage(i!,
duration: Duration(microseconds: 500),
curve: Curves.easeIn);
}),
const SizedBox(height: 10),
const Divider()
],
),
),
Expanded(
child: PageView(
controller: cont,
onPageChanged: (i) {
setState(() {
segmentedControlGroupValue = i;
});
},
children: [
ChangeNotifierProvider(
create: (context) => MainController(),
child: MainPageScreen(
query: widget.query,
),
),
ChangeNotifierProvider(
create: (context) => MainController(),
child: ImageScreen(
query: widget.query,
),
),
ChangeNotifierProvider(
create: (context) => MainController(),
child: NewsScreen(
query: widget.query,
),
),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib/main_page | mirrored_repositories/flutter-google-clone/lib/main_page/widgets/list_tile.dart | import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:search/all_web_model/web_search.dart';
import 'package:search/main_page/web_view.dart';
import 'package:search/styles.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../main.dart';
class SearchResultTile extends StatelessWidget {
final WebSearch result;
const SearchResultTile({
Key? key,
required this.result,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => WebSiteView(
url: result,
),
),
);
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
result.url!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Styles.url,
),
const SizedBox(
height: 10,
),
image(context),
const SizedBox(
height: 10,
),
Text(
result.title!,
overflow: TextOverflow.ellipsis,
maxLines: 2,
style: Styles.heading,
),
const SizedBox(
height: 10,
),
Text(
result.description!,
),
],
),
),
const Divider(
height: 2,
thickness: 2,
)
],
),
);
}
Widget image(BuildContext context) {
return result.image!.url! != ""
? GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CupertinoPageScaffold(
child: Hero(
tag: result.image!.url!,
child: PhotoView(
imageProvider:
CachedNetworkImageProvider(result.image!.url!),
),
),
),
),
);
},
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: CachedNetworkImage(
width: double.infinity,
fit: BoxFit.cover,
imageUrl: result.image!.url!,
errorWidget: (context, url, error) => Image.network(
"https://images.pexels.com/photos/4271933/pexels-photo-4271933.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
fit: BoxFit.cover,
),
),
),
)
: Container();
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/controllers/main_controller.dart | // import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'package:search/all_web_model/image.dart';
import 'package:search/all_web_model/web_search.dart';
import 'package:search/repositories/web_repo.dart';
class MainController with ChangeNotifier {
List<WebSearch> searchList = [];
List<WebSearch> newsList = [];
List<Images> images = [];
final repo = WebRepositories();
void search(String query) async {
var wholelLst = await repo.getWebSearch(query);
searchList = wholelLst.allSearches;
notifyListeners();
}
void news(String query) async {
var wholelLst = await repo.getNewsSearch(query);
newsList = wholelLst.allSearches;
notifyListeners();
}
void searchImages(String query) async {
var wholelLst = await repo.getImagesSearch(query);
images = wholelLst.images;
notifyListeners();
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/all_web_model/website_model.dart | 0 |
|
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/all_web_model/web_search.dart | import 'image.dart';
import 'provider.dart';
class WebSearchList {
final List<WebSearch> allSearches;
WebSearchList({
required this.allSearches,
});
factory WebSearchList.fromJson(json) => WebSearchList(
allSearches:
(json['value'] as List).map((e) => WebSearch.fromJson(e)).toList(),
);
}
class WebSearch {
String? id;
String? title;
String? url;
String? description;
String? body;
String? snippet;
String? keywords;
String? language;
bool? isSafe;
DateTime? datePublished;
Provider? provider;
Images? image;
WebSearch({
this.id,
this.title,
this.url,
this.description,
this.body,
this.snippet,
this.keywords,
this.language,
this.isSafe,
this.datePublished,
this.provider,
this.image,
});
factory WebSearch.fromJson(Map<String, dynamic> json) => WebSearch(
id: json['id'] as String?,
title: json['title'] as String?,
url: json['url'] as String?,
description: json['description'] as String?,
body: json['body'] as String?,
snippet: json['snippet'] as String?,
keywords: json['keywords'] as String?,
language: json['language'] as String?,
isSafe: json['isSafe'] as bool?,
datePublished: json['datePublished'] == null
? null
: DateTime.parse(json['datePublished'] as String),
provider: json['provider'] == null
? null
: Provider.fromJson(json['provider'] as Map<String, dynamic>),
image: json['image'] == null
? null
: Images.fromJson(json['image'] as Map<String, dynamic>),
);
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'url': url,
'description': description,
'body': body,
'snippet': snippet,
'keywords': keywords,
'language': language,
'isSafe': isSafe,
'datePublished': datePublished?.toIso8601String(),
'provider': provider?.toJson(),
'image': image?.toJson(),
};
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/all_web_model/provider.dart | class Provider {
String? name;
String? favIcon;
String? favIconBase64Encoding;
Provider({this.name, this.favIcon, this.favIconBase64Encoding});
factory Provider.fromJson(Map<String, dynamic> json) => Provider(
name: json['name'] as String?,
favIcon: json['favIcon'] as String?,
favIconBase64Encoding: json['favIconBase64Encoding'] as String?,
);
Map<String, dynamic> toJson() => {
'name': name,
'favIcon': favIcon,
'favIconBase64Encoding': favIconBase64Encoding,
};
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/all_web_model/image.dart | import 'provider.dart';
class ImageList {
final List<Images> images;
ImageList({
required this.images,
});
factory ImageList.fromJson(json) =>
ImageList(images: (json as List).map((e) => Images.fromJson(e)).toList());
}
class Images {
String? url;
int? height;
int? width;
String? thumbnail;
int? thumbnailHeight;
int? thumbnailWidth;
String? base64Encoding;
dynamic name;
dynamic title;
Provider? provider;
dynamic imageWebSearchUrl;
String? webpageUrl;
Images({
this.url,
this.height,
this.width,
this.thumbnail,
this.thumbnailHeight,
this.thumbnailWidth,
this.base64Encoding,
this.name,
this.title,
this.provider,
this.imageWebSearchUrl,
this.webpageUrl,
});
factory Images.fromJson(Map<String, dynamic> json) => Images(
url: json['url'] as String?,
height: json['height'] as int?,
width: json['width'] as int?,
thumbnail: json['thumbnail'] as String?,
thumbnailHeight: json['thumbnailHeight'] as int?,
thumbnailWidth: json['thumbnailWidth'] as int?,
base64Encoding: json['base64Encoding'] as String?,
name: json['name'] as dynamic?,
title: json['title'] as dynamic?,
provider: json['provider'] == null
? null
: Provider.fromJson(json['provider'] as Map<String, dynamic>),
imageWebSearchUrl: json['imageWebSearchUrl'] as dynamic?,
webpageUrl: json['webpageUrl'] as String?,
);
Map<String, dynamic> toJson() => {
'url': url,
'height': height,
'width': width,
'thumbnail': thumbnail,
'thumbnailHeight': thumbnailHeight,
'thumbnailWidth': thumbnailWidth,
'base64Encoding': base64Encoding,
'name': name,
'title': title,
'provider': provider?.toJson(),
'imageWebSearchUrl': imageWebSearchUrl,
'webpageUrl': webpageUrl,
};
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/repositories/web_repo.dart | import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:search/all_web_model/image.dart';
import 'package:search/all_web_model/web_search.dart';
class WebRepositories {
final headers = {
"x-rapidapi-host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
"x-rapidapi-key": "Api key"
};
Future<WebSearchList> getWebSearch(String query) async {
var url =
"https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/WebSearchAPI?q=${query}&pageNumber=1&pageSize=50&autoCorrect=true";
var dio = Dio();
var res = await dio.get(
url,
options: Options(
headers: headers,
),
);
print(res);
return WebSearchList.fromJson(res.data);
}
Future<WebSearchList> getNewsSearch(String query) async {
var url =
"https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/search/NewsSearchAPI?q=$query&pageNumber=1&pageSize=50&autoCorrect=true&withThumbnails=true&fromPublishedDate=null&toPublishedDate=null";
var dio = Dio();
var res = await dio.get(
url,
options: Options(
headers: headers,
),
);
print(res);
return WebSearchList.fromJson(res.data);
}
Future<ImageList> getImagesSearch(String query) async {
var url =
"https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/ImageSearchAPI?q=$query&pageNumber=1&pageSize=50&autoCorrect=true";
var dio = Dio();
var res = await dio.get(
url,
options: Options(
headers: headers,
),
);
return ImageList.fromJson(res.data['value']);
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/screens/home_page.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:search/screens/recent.dart';
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage(
"http://source.unsplash.com/random/1600x900?nature,water",
),
fit: BoxFit.cover,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: CupertinoTextField(
readOnly: true,
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => Recents()));
},
placeholder: "Ask Anything.",
placeholderStyle:
TextStyle(color: Colors.black.withOpacity(.5)),
suffix: const Padding(
padding: EdgeInsets.only(right: 16.0),
child: Icon(CupertinoIcons.search),
),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(20),
),
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-google-clone/lib | mirrored_repositories/flutter-google-clone/lib/screens/recent.dart | import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:search/main_page/all_screen.dart';
import 'package:search/screens/widgets/list_tile.dart';
class Recents extends StatefulWidget {
Recents({Key? key}) : super(key: key);
@override
State<Recents> createState() => _RecentsState();
}
class _RecentsState extends State<Recents> {
String query = '';
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: SafeArea(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: CupertinoTextField(
onChanged: (v) {
setState(() {
query = v;
});
},
onSubmitted: (v) {
var box = Hive.box('recents');
box.add(v);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AllScreens(query: v)),
);
},
placeholder: "Ask Anything.",
placeholderStyle:
TextStyle(color: Colors.black.withOpacity(.5)),
suffix: const Padding(
padding: EdgeInsets.only(right: 16.0),
child: Icon(CupertinoIcons.search),
),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(20),
),
),
),
Expanded(
child: query.isEmpty
? ListView.builder(
shrinkWrap: true,
itemCount: Hive.box('recents').length,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
final favorite = Hive.box('recents').getAt(index);
return CupertinoListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
AllScreens(query: favorite)),
);
},
trailing: const Icon(CupertinoIcons.arrow_up_left),
onLongPress: () {
var box = Hive.box('recents');
box.deleteAt(index);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Recents()));
},
leading: const Icon(Icons.watch_later_outlined),
title: favorite,
);
},
)
: FutureBuilder(
future: getAutoCompleteList(query),
builder: (context, AsyncSnapshot snp) {
if (snp.hasData) {
final data = snp.data;
return ListView.builder(
shrinkWrap: true,
itemCount: data.length,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, i) {
return CupertinoListTile(
onTap: () async {
var box = Hive.box('recents');
await box.add(snp.data![i]);
print("done");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
AllScreens(query: snp.data![i])),
);
},
leading: const Icon(Icons.search),
title: snp.data![i],
trailing:
const Icon(CupertinoIcons.arrow_up_left),
);
},
);
} else if (snp.hasError) {
return Container();
} else {
return Container();
}
}),
)
],
),
),
);
}
}
Future<List> getAutoCompleteList(String query) async {
var url =
"https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/spelling/AutoComplete?text=$query";
final headers = {
"x-rapidapi-host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
"x-rapidapi-key": " Api key"
};
var dio = Dio();
var res = await dio.get(
url,
options: Options(
headers: headers,
),
);
print(res);
return res.data;
}
| 0 |
mirrored_repositories/flutter-google-clone/lib/screens | mirrored_repositories/flutter-google-clone/lib/screens/widgets/list_tile.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class CupertinoListTile extends StatefulWidget {
final Widget leading;
final String title;
final String? subtitle;
final Widget trailing;
final Function onTap;
final Function? onLongPress;
const CupertinoListTile({
Key? key,
required this.leading,
required this.title,
this.subtitle,
required this.trailing,
required this.onTap,
this.onLongPress,
}) : super(key: key);
@override
_StatefulStateCupertino createState() => _StatefulStateCupertino();
}
class _StatefulStateCupertino extends State<CupertinoListTile> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
widget.onTap();
},
onLongPress: () {
widget.onLongPress!();
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
widget.leading,
const SizedBox(width: 20),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(widget.title,
style: const TextStyle(
color: CupertinoColors.black,
fontSize: 18,
)),
widget.subtitle != null
? Text(widget.subtitle!,
style: const TextStyle(
color: CupertinoColors.systemGrey,
fontSize: 15,
))
: Container(),
],
),
],
),
widget.trailing,
],
),
const Divider()
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-google-clone | mirrored_repositories/flutter-google-clone/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:search/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/ToDoApp | mirrored_repositories/ToDoApp/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:to_do/db/db_helper.dart';
import 'package:to_do/services/theme_services.dart';
import 'package:to_do/ui/pages/splash_screen.dart';
import 'package:to_do/ui/theme.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// NotifyHelper().initializeNotification();
await DBHelper.initDb();
await GetStorage.init();
if (Get.isDarkMode) {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.white,
statusBarBrightness: Brightness.dark,
));
} else {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: darkGreyClr,
statusBarBrightness: Brightness.light,
));
}
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: Themes.light,
darkTheme: Themes.dark,
themeMode: ThemeServices().theme,
title: 'To Do',
debugShowCheckedModeBanner: false,
home: const SplashScreen(),
);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib | mirrored_repositories/ToDoApp/lib/controllers/task_controller.dart | import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:to_do/db/db_helper.dart';
import 'package:to_do/ui/pages/completed_task_screen.dart';
import '../models/task.dart';
class TaskController extends GetxController {
RxList<Task>? taskList = <Task>[].obs;
RxList<Task>? taskCompletedList;
RxList<Task>? todayTaskList;
RxList<Task>? learningTaskList;
RxList<Task>? personalTaskList;
RxList<Task>? workTaskList;
RxList<Task>? fitnessTaskList;
Future addTask({Task? task}) async {
try {
return await DBHelper.insertToDb(task);
} catch (error) {
print(error.toString());
}
}
Future<void> getTasks() async {
taskCompletedList = <Task>[].obs;
todayTaskList = <Task>[].obs;
learningTaskList = <Task>[].obs;
personalTaskList = <Task>[].obs;
workTaskList = <Task>[].obs;
fitnessTaskList = <Task>[].obs;
try {
print('get state');
final List<Map<String, dynamic>> tasks = await DBHelper.query();
tasks.forEach((element) {
if (element['isCompleted'] == 1) {
taskCompletedList!.add(Task.fromJson(element));
print('Completed tasks $tasks');
}
if ((element['date'] == DateFormat.yMd().format(DateTime.now()) ||
element['repeat'] == 'Daily') &&
element['isCompleted'] == 0) {
todayTaskList!.add(Task.fromJson(element));
// taskList!.add(Task.fromJson(element));
print('Today tasks $tasks');
}
if (element['category'] == 'learning') {
learningTaskList!.add(Task.fromJson(element));
}
if (element['category'] == 'personal') {
personalTaskList!.add(Task.fromJson(element));
}
if (element['category'] == 'work') {
workTaskList!.add(Task.fromJson(element));
}
if (element['category'] == 'fitness') {
fitnessTaskList!.add(Task.fromJson(element));
}
});
// tasks.map((element) {
// if (element['isCompleted'] == 1) {
// taskCompletedList!
// .assignAll(tasks.map((element) => Task.fromJson(element)).toList());
// print('Completed tasks $tasks');
// } else {
// taskList!.assignAll(
// tasks.map((element) => Task.fromJson(element)).toList());
// print(tasks);
// }
// }).toList();
taskList!
.assignAll(tasks.map((element) => Task.fromJson(element)).toList());
print(tasks);
} catch (error) {
print(error.toString());
}
}
void deleteTasks(Task task) async {
await DBHelper.delete(task);
getTasks();
}
void deleteAllTasks() async {
await DBHelper.deleteAll();
getTasks();
}
void taskCompleted(int id) async {
await DBHelper.updateDb(id);
getTasks();
}
void updateTask(Task task) async {
try {
await DBHelper.updatetask(task);
getTasks();
} catch (error) {
print(error.toString());
}
}
}
| 0 |
mirrored_repositories/ToDoApp/lib | mirrored_repositories/ToDoApp/lib/db/db_helper.dart | import 'package:sqflite/sqflite.dart';
import 'package:to_do/models/task.dart';
class DBHelper {
static Database? db;
static Future<void> initDb() async {
if (db == null) {
// String path = await getDatabasesPath() + 'Todo.db';
db = await openDatabase(
'Todo.db',
version: 1,
onCreate: (Database db, int version) async {
print('database created');
await db
.execute(
'CREATE TABLE tasks(id INTEGER PRIMARY KEY AUTOINCREMENT,title STRING,note TEXT,date STRING,startTime STRING,endTime STRING,remind INTEGER,repeat STRING,color INTEGER,isCompleted INTEGER,category STRING)',
)
.then((value) {
print('table created');
}).catchError((error) {
print(error.toString());
});
},
);
} else {
print('database');
}
}
static Future insertToDb(Task? task) async {
return await db!
.insert(
'tasks',
task!.toJson(),
)
.then((value) {
print('$value inserted successful');
}).catchError((error) {
print(error.toString());
});
}
static Future delete(Task? task) async {
try {
return await db!.delete('tasks', where: 'id=?', whereArgs: [task!.id]);
} catch (error) {
print(error.toString());
}
}
static Future deleteAll() async {
try {
return await db!.delete(
'tasks',
);
} catch (error) {
print(error.toString());
}
}
static Future<List<Map<String, dynamic>>> query() async {
print('query');
return await db!.query(
'tasks',
);
}
static Future updateDb(int id) async {
return await db!.rawUpdate(
'UPDATE tasks SET isCompleted = ? WHERE id = ?', [1, id]).then((value) {
print('task updeted successful');
}).catchError((error) {
print(error.toString());
});
}
static Future updatetask(Task task) async {
return await db!
.update('tasks', task.toJson(), where: 'id=?', whereArgs: [task.id]);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib | mirrored_repositories/ToDoApp/lib/models/task.dart | class Task {
int? id;
String? title;
String? note;
int? isCompleted;
String? date;
String? startTime;
String? endTime;
int? color;
int? remind;
String? repeat;
String? category;
Task({
this.id,
this.title,
this.note,
this.isCompleted,
this.date,
this.startTime,
this.endTime,
this.color,
this.remind,
this.repeat,
this.category,
});
Task.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
note = json['note'];
isCompleted = json['isCompleted'];
date = json['date'];
startTime = json['startTime'];
endTime = json['endTime'];
color = json['color'];
remind = json['remind'];
repeat = json['repeat'];
category = json['category'];
}
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'note': note,
'isCompleted': isCompleted,
'date': date,
'startTime': startTime,
'endTime': endTime,
'color': color,
'remind': remind,
'repeat': repeat,
'category': category,
};
}
}
| 0 |
mirrored_repositories/ToDoApp/lib | mirrored_repositories/ToDoApp/lib/ui/size_config.dart | import 'package:flutter/material.dart';
class SizeConfig {
static late MediaQueryData _mediaQueryData;
static late double screenWidth;
static late double screenHeight;
//static late double defaultSize;
static late Orientation orientation;
void init(BuildContext context) {
_mediaQueryData = MediaQuery.of(context);
screenWidth = _mediaQueryData.size.width;
print('$screenWidth');
screenHeight = _mediaQueryData.size.height;
orientation = _mediaQueryData.orientation;
}
}
// Get the proportionate height as per screen size
double getProportionateScreenHeight(double inputHeight) {
double screenHeight = SizeConfig.screenHeight;
// 812 is the layout height that designer use
return (inputHeight / 812.0) * screenHeight;
}
// Get the proportionate height as per screen size
double getProportionateScreenWidth(double inputWidth) {
double screenWidth = SizeConfig.screenWidth;
// 375 is the layout width that designer use
return (inputWidth / 375.0) * screenWidth;
}
| 0 |
mirrored_repositories/ToDoApp/lib | mirrored_repositories/ToDoApp/lib/ui/theme.dart | import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
const Color bluishClr = Color(0xFF4e5ae8);
const Color orangeClr = Color(0xCFFF8746);
const Color pinkClr = Color(0xFFff4667);
const Color white = Colors.white;
const primaryClr = bluishClr;
const Color darkGreyClr = Color(0xFF121212);
const Color darkHeaderClr = Color(0xFF424242);
class Themes {
static final light = ThemeData(
primaryColor: primaryClr,
backgroundColor: Colors.white,
brightness: Brightness.light,
);
static final dark = ThemeData(
primaryColor: darkGreyClr,
backgroundColor: darkGreyClr,
brightness: Brightness.dark,
);
}
TextStyle get headingStyle {
return GoogleFonts.lato(
textStyle: TextStyle(
color: Get.isDarkMode ? Colors.white : Colors.black,
fontSize: 24.0,
fontWeight: FontWeight.bold,
),
);
}
TextStyle get subHeadingStyle {
return GoogleFonts.lato(
textStyle: TextStyle(
color: Get.isDarkMode ? Colors.white : Colors.black,
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
);
}
TextStyle get titleStyle {
return GoogleFonts.lato(
textStyle: TextStyle(
color: Get.isDarkMode ? Colors.white : Colors.black,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
);
}
TextStyle get subTitleStyle {
return GoogleFonts.lato(
textStyle: TextStyle(
color: Get.isDarkMode ? Colors.white : Colors.black,
fontSize: 16.0,
fontWeight: FontWeight.w400,
),
);
}
TextStyle get bodyStyle {
return GoogleFonts.lato(
textStyle: TextStyle(
color: Get.isDarkMode ? Colors.white : Colors.black,
fontSize: 14.0,
fontWeight: FontWeight.w400,
),
);
}
TextStyle get body2Style {
return GoogleFonts.lato(
textStyle: TextStyle(
color: Get.isDarkMode ? Colors.grey[200] : Colors.black,
fontSize: 14.0,
fontWeight: FontWeight.w400,
),
);
}
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/widgets/task_tile.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:to_do/models/task.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
class TaskTile extends StatelessWidget {
const TaskTile(this.task, {Key? key}) : super(key: key);
final Task task;
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(
SizeConfig.orientation == Orientation.landscape ? 4 : 20,
),
),
width: SizeConfig.orientation == Orientation.landscape
? SizeConfig.screenWidth / 2
: SizeConfig.screenWidth,
margin: EdgeInsets.only(
bottom: getProportionateScreenHeight(12),
),
child: Container(
padding: const EdgeInsets.all(12.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16.0),
color: task.color == 0
? primaryClr
: task.color == 1
? pinkClr
: orangeClr,
),
child: Row(
children: [
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${task.title}',
style: GoogleFonts.lato(
textStyle: const TextStyle(
color: Colors.white,
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(
height: 12.0,
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(
Icons.access_time_rounded,
color: Colors.grey[200],
size: 18.0,
),
const SizedBox(
width: 7.0,
),
Text(
'${task.startTime} - ${task.endTime}',
style: GoogleFonts.lato(
textStyle: TextStyle(
color: Colors.grey[100],
fontSize: 13.0,
),
),
),
],
),
const SizedBox(
height: 12.0,
),
Text(
'${task.note}',
style: GoogleFonts.lato(
textStyle: TextStyle(
color: Colors.grey[100],
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
),
Container(
height: 60.0,
width: 0.5,
margin: const EdgeInsets.symmetric(
horizontal: 10.0,
),
color: Colors.grey[200]!.withOpacity(0.7),
),
RotatedBox(
quarterTurns: 3,
child: Text(
task.isCompleted == 0 ? 'TODO' : 'Completed',
style: GoogleFonts.lato(
textStyle: const TextStyle(
color: Colors.white,
fontSize: 10.0,
fontWeight: FontWeight.bold,
),
),
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/widgets/input_field.dart | import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
class InputField extends StatelessWidget {
const InputField(
{Key? key,
required this.title,
required this.hint,
this.widget,
this.controller})
: super(key: key);
final String title;
final String hint;
final Widget? widget;
final TextEditingController? controller;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(
top: 16.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: titleStyle,
),
Container(
width: SizeConfig.screenWidth,
height: 52.0,
padding: const EdgeInsets.only(
left: 14.0,
),
margin: const EdgeInsets.only(
top: 8.0,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12.0),
border: Border.all(
color: Colors.grey,
)),
child: Row(
children: [
Expanded(
child: TextFormField(
controller: controller,
autofocus: false,
readOnly: widget != null ? true : false,
cursorColor:
Get.isDarkMode ? Colors.grey[100] : Colors.grey[700],
style: subTitleStyle,
decoration: InputDecoration(
hintText: hint,
hintStyle: subTitleStyle,
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).backgroundColor,
),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context).backgroundColor,
),
),
),
),
),
widget ?? Container(),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/widgets/button.dart | import 'package:flutter/material.dart';
import 'package:to_do/ui/theme.dart';
class CustomButton extends StatelessWidget {
const CustomButton({Key? key, required this.lable, required this.onTap})
: super(key: key);
final String lable;
final Function() onTap;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
alignment: Alignment.center,
width: 100.0,
height: 45.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: primaryClr,
),
child: Text(
lable,
style: const TextStyle(
color: Colors.white,
),
textAlign: TextAlign.center,
),
),
);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/add_task_page.dart | import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:to_do/controllers/task_controller.dart';
import 'package:to_do/models/task.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/button.dart';
import 'package:to_do/ui/widgets/input_field.dart';
class AddTaskPage extends StatefulWidget {
const AddTaskPage({Key? key}) : super(key: key);
@override
State<AddTaskPage> createState() => _AddTaskPageState();
}
class _AddTaskPageState extends State<AddTaskPage> {
final TaskController taskController = Get.put(TaskController());
final TextEditingController titleController = TextEditingController();
final TextEditingController noteController = TextEditingController();
DateTime selectDate = DateTime.now();
String startTime = DateFormat('hh:mm a').format(DateTime.now()).toString();
String endTime = DateFormat('hh:mm a')
.format(DateTime.now().add(const Duration(minutes: 15)))
.toString();
int selectRemind = 5;
List<int> remindList = [5, 10, 15, 20];
String selectRepeat = 'none';
List<String> repeatList = ['none', 'Daily', 'Weekly', 'Monthly'];
int selectColor = 0;
String selectCategory = 'none';
List<String> categoryList = [
'none',
'learning',
'personal',
'work',
'fitness'
];
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
backgroundColor: Theme.of(context).backgroundColor,
elevation: 0.0,
leading: IconButton(
padding: const EdgeInsets.only(
left: 15.0,
),
onPressed: () => Get.back(),
icon: const Icon(
Icons.arrow_back_ios,
color: primaryClr,
),
),
// title: const Text(
// 'New Task',
// style: TextStyle(
// color: primaryClr,
// ),
// ),
// titleSpacing: 0.0,
actions: const [
CircleAvatar(
radius: 18.0,
backgroundImage: AssetImage(
'images/op_logo.jpg',
),
),
SizedBox(
width: 20.0,
),
],
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
children: [
Text(
'Add Task',
style: headingStyle,
),
InputField(
controller: titleController,
title: 'Title',
hint: 'Enter task title',
),
InputField(
controller: noteController,
title: 'Note',
hint: 'Enter task note',
),
InputField(
title: 'Date',
hint: DateFormat.yMd().format(selectDate),
widget: IconButton(
icon: const Icon(
Icons.calendar_today_outlined,
color: Colors.grey,
),
onPressed: () async {
DateTime? date = await showDatePicker(
context: context,
initialDate: selectDate,
firstDate: DateTime(2016),
lastDate: DateTime(2040),
);
if (date != null) {
setState(() {
selectDate = date;
});
} else {
print('no date selected');
}
},
),
),
Row(
children: [
Expanded(
child: InputField(
title: 'Start Time',
hint: startTime,
widget: IconButton(
icon: const Icon(
Icons.access_time_rounded,
color: Colors.grey,
),
onPressed: () async {
TimeOfDay? picStartTime = await showTimePicker(
context: context,
initialTime:
TimeOfDay.fromDateTime(DateTime.now()),
);
if (picStartTime != null) {
setState(() {
startTime = picStartTime.format(context);
});
} else {
print('no time selected');
}
},
),
),
),
const SizedBox(
width: 10.0,
),
Expanded(
child: InputField(
title: 'End Time',
hint: endTime,
widget: IconButton(
icon: const Icon(
Icons.access_time_rounded,
color: Colors.grey,
),
onPressed: () async {
TimeOfDay? picEndTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(DateTime.now()
.add(const Duration(minutes: 15))),
);
if (picEndTime != null) {
setState(() {
endTime = picEndTime.format(context);
});
} else {
print('no time selected');
}
},
),
),
),
],
),
InputField(
title: 'Remind',
hint: '$selectRemind minutes early',
widget: DropdownButton(
dropdownColor: Colors.blueGrey,
borderRadius: BorderRadius.circular(10.0),
items: remindList
.map<DropdownMenuItem<String>>(
(int value) => DropdownMenuItem<String>(
value: value.toString(),
child: Text(
'$value',
style: const TextStyle(
color: Colors.white,
),
),
),
)
.toList(),
onChanged: (String? newValue) {
setState(() {
selectRemind = int.parse(newValue!);
});
},
icon: const Icon(Icons.keyboard_arrow_down),
iconSize: 32.0,
elevation: 4,
style: subTitleStyle,
underline: Container(
height: 0.0,
),
),
),
InputField(
title: 'Repeat',
hint: selectRepeat,
widget: Row(
children: [
DropdownButton(
dropdownColor: Colors.blueGrey,
borderRadius: BorderRadius.circular(10.0),
items: repeatList
.map<DropdownMenuItem<String>>(
(String value) => DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: const TextStyle(
color: Colors.white,
),
),
),
)
.toList(),
onChanged: (String? newValue) {
setState(() {
selectRepeat = newValue!;
});
},
icon: const Icon(Icons.keyboard_arrow_down),
iconSize: 32.0,
elevation: 4,
style: subTitleStyle,
underline: Container(
height: 0.0,
),
),
],
),
),
InputField(
title: 'Category',
hint: selectCategory,
widget: Row(
children: [
DropdownButton(
dropdownColor: Colors.blueGrey,
borderRadius: BorderRadius.circular(10.0),
items: categoryList
.map<DropdownMenuItem<String>>(
(String value) => DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: const TextStyle(
color: Colors.white,
),
),
),
)
.toList(),
onChanged: (String? newValue) {
setState(() {
selectCategory = newValue!;
});
},
icon: const Icon(Icons.keyboard_arrow_down),
iconSize: 32.0,
elevation: 4,
style: subTitleStyle,
underline: Container(
height: 0.0,
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Colors',
style: titleStyle,
),
const SizedBox(
height: 3.0,
),
Row(
children: List.generate(
3,
(index) => GestureDetector(
onTap: () {
setState(() {
selectColor = index;
});
},
child: CircleAvatar(
radius: 14.0,
backgroundColor: index == 0
? primaryClr
: index == 1
? pinkClr
: orangeClr,
child: selectColor == index
? const Icon(
Icons.done,
size: 16.0,
)
: null,
),
)),
),
],
),
CustomButton(
lable: 'create task',
onTap: () async {
if (titleController.text != '' &&
noteController.text != '') {
await addTaskToDb();
TaskController().getTasks();
Get.back();
} else {
Get.defaultDialog(
title: 'Requird',
middleText: titleController.text == '' &&
noteController.text == ''
? 'please enter title and note'
: noteController.text == ''
? 'Note must not be empty'
: 'Title must not be empty',
titleStyle: const TextStyle(color: Colors.red),
textCancel: 'Cancel',
textConfirm: 'OK',
onConfirm: () {
Get.back();
},
cancelTextColor: Colors.grey,
confirmTextColor: Colors.white,
buttonColor: primaryClr,
);
}
},
),
],
),
),
],
),
),
),
),
);
}
addTaskToDb() async {
dynamic value = await TaskController().addTask(
task: Task(
title: titleController.text,
note: noteController.text,
isCompleted: 0,
date: DateFormat.yMd().format(selectDate),
startTime: startTime,
endTime: endTime,
color: selectColor,
remind: selectRemind,
repeat: selectRepeat,
category: selectCategory,
),
);
print(value);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/layout.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:get/get.dart';
import 'package:to_do/services/notification_services.dart';
import 'package:to_do/services/theme_services.dart';
import 'package:to_do/ui/pages/add_task_page.dart';
import 'package:to_do/ui/pages/completed_task_screen.dart';
import 'package:to_do/ui/pages/fitness_screen.dart';
import 'package:to_do/ui/pages/learning_screen.dart';
import 'package:to_do/ui/pages/personal_screen.dart';
import 'package:to_do/ui/pages/to_do_task_screen.dart';
import 'package:to_do/ui/pages/today_tasks.dart';
import 'package:to_do/ui/pages/work_screen.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../controllers/task_controller.dart';
class ToDoLayout extends StatefulWidget {
const ToDoLayout({Key? key}) : super(key: key);
@override
State<ToDoLayout> createState() => _ToDoLayoutState();
}
final TaskController taskController = Get.put(TaskController());
late NotifyHelper notifyHelper;
class _ToDoLayoutState extends State<ToDoLayout> {
@override
void initState() {
super.initState();
// notifyHelper = NotifyHelper();
// notifyHelper.initializeNotification();
// notifyHelper.requestIOSPermissions();
taskController.getTasks();
}
DateTime selecedTime = DateTime.now();
int currentIndex = 0;
List<Widget> screens = [
const ToDoTasks(),
const TodayTasks(),
const CompletedTasks(),
];
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
backgroundColor: Theme.of(context).backgroundColor,
elevation: 0.0,
actions: [
// IconButton(
// onPressed: () {
// Get.defaultDialog(
// title: 'Warning',
// middleText:
// 'This button will delete all tasks,if you agree press OK.',
// titleStyle: const TextStyle(color: Colors.red),
// textCancel: 'Cancel',
// textConfirm: 'OK',
// onConfirm: () {
// notifyHelper.cancelAllNotification();
// taskController.deleteAllTasks();
// Get.back();
// },
// cancelTextColor: Colors.grey,
// confirmTextColor: Colors.white,
// buttonColor: primaryClr,
// );
// },
// icon: Icon(
// Icons.delete,
// color: Get.isDarkMode ? Colors.white : darkGreyClr,
// ),
// ),
Padding(
padding: const EdgeInsets.only(left: 10.0),
child: IconButton(
padding: const EdgeInsets.only(
left: 15.0,
),
onPressed: () {
ThemeServices().switchThemeMode();
if (Get.isDarkMode) {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: Colors.white,
statusBarBrightness: Brightness.dark,
));
} else {
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: darkGreyClr,
statusBarBrightness: Brightness.light,
));
}
},
icon: Icon(
Get.isDarkMode
? Icons.wb_sunny_outlined
: Icons.nightlight_round_outlined,
color: Get.isDarkMode ? Colors.white : darkGreyClr,
),
),
),
const SizedBox(
width: 20.0,
),
const CircleAvatar(
radius: 18.0,
backgroundImage: AssetImage(
'images/op_logo.jpg',
),
),
const SizedBox(
width: 20.0,
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await Get.to(const AddTaskPage());
taskController.getTasks();
},
child: const Icon(
Icons.add,
color: Colors.white,
),
backgroundColor: primaryClr,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: currentIndex,
backgroundColor: Theme.of(context).backgroundColor,
selectedItemColor: Get.isDarkMode ? Colors.white : darkGreyClr,
showSelectedLabels: true,
showUnselectedLabels: false,
elevation: 0.0,
items: const [
BottomNavigationBarItem(
icon: Icon(
Icons.calendar_today,
),
label: 'Calender',
),
BottomNavigationBarItem(
icon: Icon(
Icons.today_rounded,
),
label: 'Today',
),
BottomNavigationBarItem(
icon: Icon(
Icons.done_outline,
),
label: 'Completed',
),
],
onTap: (int index) {
setState(() {
currentIndex = index;
});
},
),
drawer: Drawer(
backgroundColor: Theme.of(context).backgroundColor,
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const CircleAvatar(
radius: 40.0,
backgroundImage: AssetImage(
'images/op_logo.jpg',
),
),
const SizedBox(
height: 10.0,
),
Text(
'User Name',
style: headingStyle,
),
const SizedBox(
height: 15.0,
),
const Divider(
height: 5.0,
color: Colors.grey,
),
const SizedBox(
height: 15.0,
),
Text(
'Categoty',
style: subHeadingStyle,
),
const SizedBox(
height: 10.0,
),
InkWell(
onTap: () {
Get.back();
Get.to(const LearningTasks());
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 15.0),
child: Row(
children: [
const Icon(
Icons.science,
color: primaryClr,
),
const SizedBox(
width: 10.0,
),
Text(
'Learning',
style: subTitleStyle,
),
],
),
),
),
InkWell(
onTap: () {
Get.back();
Get.to(const PersonalTasks());
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 15.0),
child: Row(
children: [
const Icon(
Icons.person,
color: primaryClr,
),
const SizedBox(
width: 10.0,
),
Text(
'Personal',
style: subTitleStyle,
),
],
),
),
),
InkWell(
onTap: () {
Get.back();
Get.to(const WorkTasks());
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 15.0),
child: Row(
children: [
const Icon(
Icons.work,
color: primaryClr,
),
const SizedBox(
width: 10.0,
),
Text(
'Work',
style: subTitleStyle,
),
],
),
),
),
InkWell(
onTap: () {
Get.back();
Get.to(const FitnessTasks());
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 15.0),
child: Row(
children: [
const Icon(
Icons.fitness_center,
color: primaryClr,
),
const SizedBox(
width: 10.0,
),
Text(
'Fitness',
style: subTitleStyle,
),
],
),
),
),
const SizedBox(
height: 20.0,
),
const Divider(
height: 5.0,
color: Colors.grey,
),
const SizedBox(
height: 20.0,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: () async {
const String url =
'https://twitter.com/hanysameh11?t=_-XBJoiTwM8GroEVhG0tYg&s=09';
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: true,
forceWebView: true,
enableJavaScript: true,
);
} else {
throw 'Could not launch $url';
}
},
icon: const Icon(
FontAwesomeIcons.twitter,
size: 30.0,
),
),
const SizedBox(
width: 10.0,
),
IconButton(
onPressed: () async {
const String url =
'https://www.facebook.com/hany.sameh23';
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: true,
forceWebView: true,
enableJavaScript: true,
);
} else {
throw 'Could not launch $url';
}
},
icon: const Icon(
FontAwesomeIcons.facebook,
size: 30.0,
),
),
const SizedBox(
width: 10.0,
),
IconButton(
onPressed: () async {
const String url =
'https://instagram.com/hany_sameh_?igshid=YmMyMTA2M2Y=';
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: true,
forceWebView: true,
enableJavaScript: true,
);
} else {
throw 'Could not launch $url';
}
},
icon: const Icon(
FontAwesomeIcons.instagram,
size: 30.0,
),
),
],
),
),
const Spacer(),
Center(
child: Text(
'From\n One Piece',
textAlign: TextAlign.center,
style: subTitleStyle.copyWith(
color: Colors.grey,
),
),
),
],
),
),
),
),
body: screens[currentIndex],
);
}
}
// DatePicker(
// DateTime.now(),
// height: 100.0,
// width: 70.0,
// initialSelectedDate: DateTime.now(),
// selectedTextColor: Colors.white,
// selectionColor: primaryClr,
// onDateChange: (date) {
// setState(() {
// selecedTime = date;
// });
// },
// dateTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 20.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// dayTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// monthTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 12.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// ), | 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/learning_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:to_do/services/notification_services.dart';
import 'package:to_do/ui/pages/update_task_screen.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/task_tile.dart';
import '../../controllers/task_controller.dart';
import '../../models/task.dart';
class LearningTasks extends StatefulWidget {
const LearningTasks({Key? key}) : super(key: key);
@override
State<LearningTasks> createState() => _LearningTasksState();
}
final TaskController taskController = Get.put(TaskController());
late NotifyHelper notifyHelper;
class _LearningTasksState extends State<LearningTasks> {
@override
void initState() {
super.initState();
notifyHelper = NotifyHelper();
notifyHelper.initializeNotification();
notifyHelper.requestIOSPermissions();
taskController.getTasks();
}
DateTime selecedTime = DateTime.now();
int currentIndex = 0;
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
backgroundColor: Theme.of(context).backgroundColor,
elevation: 0.0,
title: Text(
'Learning',
style: headingStyle.copyWith(
color: primaryClr,
),
),
),
body: Column(
children: [
// Container(
// margin: const EdgeInsets.only(
// left: 20.0,
// right: 10.0,
// top: 10.0,
// ),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// DateFormat.yMMMd().format(DateTime.now()),
// style: subHeadingStyle,
// ),
// Text(
// 'Today',
// style: headingStyle,
// ),
// ],
// ),
// // CustomButton(
// // lable: '+ add task',
// // onTap: () async {
// // await Get.to(const AddTaskPage());
// // taskController.getTasks();
// // },
// // ),
// Padding(
// padding: const EdgeInsets.only(right: 15.0),
// child: IconButton(
// onPressed: () {
// Get.defaultDialog(
// title: 'Warning',
// middleText:
// 'This button will delete all tasks,if you agree press OK.',
// titleStyle: const TextStyle(color: Colors.red),
// textCancel: 'Cancel',
// textConfirm: 'OK',
// onConfirm: () {
// notifyHelper.cancelAllNotification();
// taskController.deleteAllTasks();
// Get.back();
// },
// cancelTextColor: Colors.grey,
// confirmTextColor: Colors.white,
// buttonColor: primaryClr,
// );
// },
// icon: Icon(
// Icons.delete,
// size: 30.0,
// color: Get.isDarkMode ? Colors.white : darkGreyClr,
// ),
// ),
// ),
// ],
// ),
// ),
// Container(
// margin: const EdgeInsets.only(top: 6.0, left: 20.0),
// child: CalendarTimeline(
// initialDate: selecedTime,
// firstDate: DateTime(2021, 1, 15),
// lastDate: DateTime(2030, 11, 20),
// onDateSelected: (date) {
// setState(() {
// selecedTime = date!;
// });
// },
// leftMargin: 20,
// monthColor: Colors.grey,
// dayColor: Colors.blueAccent[100],
// activeDayColor: Colors.white,
// activeBackgroundDayColor: primaryClr,
// dotsColor: const Color(0xFF333A47),
// selectableDayPredicate: (date) => date.day != 23,
// locale: 'en_ISO',
// ),
// ),
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'Learning Tasks',
style: headingStyle,
),
),
],
),
const SizedBox(
height: 20.0,
),
Expanded(
child: Obx(() {
if (taskController.learningTaskList!.isEmpty) {
return noTasks(context);
} else {
return RefreshIndicator(
onRefresh: () async {
await taskController.getTasks();
},
child: ListView.builder(
shrinkWrap: true,
scrollDirection:
SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
var task = taskController.learningTaskList![index];
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 1375),
child: SlideAnimation(
horizontalOffset: 300,
child: FadeInAnimation(
child: GestureDetector(
onTap: (() {
showBottomSheet(
context,
task,
);
}),
child: TaskTile(task),
),
),
),
);
},
itemCount: taskController.learningTaskList!.length,
),
);
}
}),
),
],
),
);
}
noTasks(context) => Center(
child: Stack(
children: [
AnimatedPositioned(
duration: const Duration(
milliseconds: 2000,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
direction: SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
children: [
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 6.0,
)
: const SizedBox(
height: 220.0,
),
SvgPicture.asset(
'images/task.svg',
color: primaryClr.withOpacity(0.5),
semanticsLabel: 'Task',
height: 100.0,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 10.0,
),
child: Text(
'you don\'t have eny tasks completed yet!,\n finish some tasks',
style: subTitleStyle,
textAlign: TextAlign.center,
),
),
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 120.0,
)
: const SizedBox(
height: 180.0,
),
],
),
)
],
),
);
showBottomSheet(context, Task task) {
Get.bottomSheet(
SingleChildScrollView(
child: Container(
padding: const EdgeInsets.only(top: 4.0),
width: SizeConfig.screenWidth,
height: SizeConfig.orientation == Orientation.landscape
? task.isCompleted == 1
? SizeConfig.screenHeight * 0.6
: SizeConfig.screenHeight * 0.8
: task.isCompleted == 1
? SizeConfig.screenHeight * 0.30
: SizeConfig.screenHeight * 0.39,
color: Get.isDarkMode ? darkHeaderClr : Colors.white,
child: Expanded(
child: Column(
children: [
Flexible(
child: Container(
height: 6.0,
width: 120.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color:
Get.isDarkMode ? Colors.grey[600] : Colors.grey[300],
),
),
),
const SizedBox(
height: 20.0,
),
if (task.isCompleted == 0)
buildBottomSheet(
label: 'Task Completed',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.taskCompleted(task.id!);
Get.back();
},
color: primaryClr,
),
buildBottomSheet(
label: 'Edit Task',
onTap: () {
Get.back();
Get.to(UpdateTaskScreen(
task: task,
));
},
color: primaryClr,
),
buildBottomSheet(
label: 'Delete Task',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.deleteTasks(task);
Get.back();
},
color: Colors.red,
),
Divider(
color: Get.isDarkMode ? Colors.grey : darkGreyClr,
),
buildBottomSheet(
label: 'Cancle',
onTap: () {
Get.back();
},
color: primaryClr,
),
const SizedBox(
height: 10.0,
),
],
),
),
),
),
);
}
buildBottomSheet({
required String label,
required Function() onTap,
required Color color,
bool isClose = false,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4.0),
height: 55.0,
width: SizeConfig.screenWidth * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: isClose
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[300]!
: color,
),
borderRadius: BorderRadius.circular(20.0),
color: isClose ? Colors.transparent : color,
),
child: Center(
child: Text(
label,
style: isClose
? titleStyle
: titleStyle.copyWith(
color: Colors.white,
),
),
),
),
);
}
}
// DatePicker(
// DateTime.now(),
// height: 100.0,
// width: 70.0,
// initialSelectedDate: DateTime.now(),
// selectedTextColor: Colors.white,
// selectionColor: primaryClr,
// onDateChange: (date) {
// setState(() {
// selecedTime = date;
// });
// },
// dateTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 20.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// dayTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// monthTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 12.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// ), | 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/today_tasks.dart | import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:to_do/services/notification_services.dart';
import 'package:to_do/ui/pages/update_task_screen.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/task_tile.dart';
import '../../controllers/task_controller.dart';
import '../../models/task.dart';
class TodayTasks extends StatefulWidget {
const TodayTasks({Key? key}) : super(key: key);
@override
State<TodayTasks> createState() => _TodayTasksState();
}
final TaskController taskController = Get.put(TaskController());
late NotifyHelper notifyHelper;
class _TodayTasksState extends State<TodayTasks> {
@override
void initState() {
super.initState();
notifyHelper = NotifyHelper();
notifyHelper.initializeNotification();
notifyHelper.requestIOSPermissions();
taskController.getTasks();
}
DateTime selecedTime = DateTime.now();
int currentIndex = 0;
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Column(
children: [
// Container(
// margin: const EdgeInsets.only(
// left: 20.0,
// right: 10.0,
// top: 10.0,
// ),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// DateFormat.yMMMd().format(DateTime.now()),
// style: subHeadingStyle,
// ),
// Text(
// 'Today',
// style: headingStyle,
// ),
// ],
// ),
// // CustomButton(
// // lable: '+ add task',
// // onTap: () async {
// // await Get.to(const AddTaskPage());
// // taskController.getTasks();
// // },
// // ),
// Padding(
// padding: const EdgeInsets.only(right: 15.0),
// child: IconButton(
// onPressed: () {
// Get.defaultDialog(
// title: 'Warning',
// middleText:
// 'This button will delete all tasks,if you agree press OK.',
// titleStyle: const TextStyle(color: Colors.red),
// textCancel: 'Cancel',
// textConfirm: 'OK',
// onConfirm: () {
// notifyHelper.cancelAllNotification();
// taskController.deleteAllTasks();
// Get.back();
// },
// cancelTextColor: Colors.grey,
// confirmTextColor: Colors.white,
// buttonColor: primaryClr,
// );
// },
// icon: Icon(
// Icons.delete,
// size: 30.0,
// color: Get.isDarkMode ? Colors.white : darkGreyClr,
// ),
// ),
// ),
// ],
// ),
// ),
// Container(
// margin: const EdgeInsets.only(top: 6.0, left: 20.0),
// child: CalendarTimeline(
// initialDate: selecedTime,
// firstDate: DateTime(2021, 1, 15),
// lastDate: DateTime(2030, 11, 20),
// onDateSelected: (date) {
// setState(() {
// selecedTime = date!;
// });
// },
// leftMargin: 20,
// monthColor: Colors.grey,
// dayColor: Colors.blueAccent[100],
// activeDayColor: Colors.white,
// activeBackgroundDayColor: primaryClr,
// dotsColor: const Color(0xFF333A47),
// selectableDayPredicate: (date) => date.day != 23,
// locale: 'en_ISO',
// ),
// ),
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'Today Tasks',
style: headingStyle,
),
),
],
),
const SizedBox(
height: 20.0,
),
Expanded(
child: Obx(() {
if (taskController.todayTaskList!.isEmpty) {
return noTasks(context);
} else {
return RefreshIndicator(
onRefresh: () async {
await taskController.getTasks();
},
child: ListView.builder(
shrinkWrap: true,
scrollDirection:
SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
var task = taskController.todayTaskList![index];
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 1375),
child: SlideAnimation(
horizontalOffset: 300,
child: FadeInAnimation(
child: GestureDetector(
onTap: (() {
showBottomSheet(
context,
task,
);
}),
child: TaskTile(task),
),
),
),
);
},
itemCount: taskController.todayTaskList!.length,
),
);
}
}),
),
],
);
}
noTasks(context) => Center(
child: Stack(
children: [
AnimatedPositioned(
duration: const Duration(
milliseconds: 2000,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
direction: SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
children: [
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 6.0,
)
: const SizedBox(
height: 220.0,
),
SvgPicture.asset(
'images/task.svg',
color: primaryClr.withOpacity(0.5),
semanticsLabel: 'Task',
height: 100.0,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 10.0,
),
child: Text(
'you don\'t have eny tasks today,\n add some tasks',
style: subTitleStyle,
textAlign: TextAlign.center,
),
),
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 120.0,
)
: const SizedBox(
height: 180.0,
),
],
),
)
],
),
);
showBottomSheet(context, Task task) {
Get.bottomSheet(
SingleChildScrollView(
child: Container(
padding: const EdgeInsets.only(top: 4.0),
width: SizeConfig.screenWidth,
height: SizeConfig.orientation == Orientation.landscape
? task.isCompleted == 1
? SizeConfig.screenHeight * 0.6
: SizeConfig.screenHeight * 0.8
: task.isCompleted == 1
? SizeConfig.screenHeight * 0.30
: SizeConfig.screenHeight * 0.39,
color: Get.isDarkMode ? darkHeaderClr : Colors.white,
child: Expanded(
child: Column(
children: [
Flexible(
child: Container(
height: 6.0,
width: 120.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color:
Get.isDarkMode ? Colors.grey[600] : Colors.grey[300],
),
),
),
const SizedBox(
height: 20.0,
),
if (task.isCompleted == 0)
buildBottomSheet(
label: 'Task Completed',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.taskCompleted(task.id!);
Get.back();
},
color: primaryClr,
),
buildBottomSheet(
label: 'Edit Task',
onTap: () {
Get.back();
Get.to(UpdateTaskScreen(
task: task,
));
},
color: primaryClr,
),
buildBottomSheet(
label: 'Delete Task',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.deleteTasks(task);
Get.back();
},
color: Colors.red,
),
Divider(
color: Get.isDarkMode ? Colors.grey : darkGreyClr,
),
buildBottomSheet(
label: 'Cancle',
onTap: () {
Get.back();
},
color: primaryClr,
),
const SizedBox(
height: 10.0,
),
],
),
),
),
),
);
}
buildBottomSheet({
required String label,
required Function() onTap,
required Color color,
bool isClose = false,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4.0),
height: 55.0,
width: SizeConfig.screenWidth * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: isClose
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[300]!
: color,
),
borderRadius: BorderRadius.circular(20.0),
color: isClose ? Colors.transparent : color,
),
child: Center(
child: Text(
label,
style: isClose
? titleStyle
: titleStyle.copyWith(
color: Colors.white,
),
),
),
),
);
}
}
// DatePicker(
// DateTime.now(),
// height: 100.0,
// width: 70.0,
// initialSelectedDate: DateTime.now(),
// selectedTextColor: Colors.white,
// selectionColor: primaryClr,
// onDateChange: (date) {
// setState(() {
// selecedTime = date;
// });
// },
// dateTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 20.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// dayTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// monthTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 12.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// ), | 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/fitness_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:to_do/services/notification_services.dart';
import 'package:to_do/ui/pages/update_task_screen.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/task_tile.dart';
import '../../controllers/task_controller.dart';
import '../../models/task.dart';
class FitnessTasks extends StatefulWidget {
const FitnessTasks({Key? key}) : super(key: key);
@override
State<FitnessTasks> createState() => _FitnessTasksState();
}
final TaskController taskController = Get.put(TaskController());
late NotifyHelper notifyHelper;
class _FitnessTasksState extends State<FitnessTasks> {
@override
void initState() {
super.initState();
notifyHelper = NotifyHelper();
notifyHelper.initializeNotification();
notifyHelper.requestIOSPermissions();
taskController.getTasks();
}
DateTime selecedTime = DateTime.now();
int currentIndex = 0;
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
backgroundColor: Theme.of(context).backgroundColor,
elevation: 0.0,
title: Text(
'Fitness',
style: headingStyle.copyWith(
color: primaryClr,
),
),
),
body: Column(
children: [
// Container(
// margin: const EdgeInsets.only(
// left: 20.0,
// right: 10.0,
// top: 10.0,
// ),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// DateFormat.yMMMd().format(DateTime.now()),
// style: subHeadingStyle,
// ),
// Text(
// 'Today',
// style: headingStyle,
// ),
// ],
// ),
// // CustomButton(
// // lable: '+ add task',
// // onTap: () async {
// // await Get.to(const AddTaskPage());
// // taskController.getTasks();
// // },
// // ),
// Padding(
// padding: const EdgeInsets.only(right: 15.0),
// child: IconButton(
// onPressed: () {
// Get.defaultDialog(
// title: 'Warning',
// middleText:
// 'This button will delete all tasks,if you agree press OK.',
// titleStyle: const TextStyle(color: Colors.red),
// textCancel: 'Cancel',
// textConfirm: 'OK',
// onConfirm: () {
// notifyHelper.cancelAllNotification();
// taskController.deleteAllTasks();
// Get.back();
// },
// cancelTextColor: Colors.grey,
// confirmTextColor: Colors.white,
// buttonColor: primaryClr,
// );
// },
// icon: Icon(
// Icons.delete,
// size: 30.0,
// color: Get.isDarkMode ? Colors.white : darkGreyClr,
// ),
// ),
// ),
// ],
// ),
// ),
// Container(
// margin: const EdgeInsets.only(top: 6.0, left: 20.0),
// child: CalendarTimeline(
// initialDate: selecedTime,
// firstDate: DateTime(2021, 1, 15),
// lastDate: DateTime(2030, 11, 20),
// onDateSelected: (date) {
// setState(() {
// selecedTime = date!;
// });
// },
// leftMargin: 20,
// monthColor: Colors.grey,
// dayColor: Colors.blueAccent[100],
// activeDayColor: Colors.white,
// activeBackgroundDayColor: primaryClr,
// dotsColor: const Color(0xFF333A47),
// selectableDayPredicate: (date) => date.day != 23,
// locale: 'en_ISO',
// ),
// ),
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'Fitness Tasks',
style: headingStyle,
),
),
],
),
const SizedBox(
height: 20.0,
),
Expanded(
child: Obx(() {
if (taskController.fitnessTaskList!.isEmpty) {
return noTasks(context);
} else {
return RefreshIndicator(
onRefresh: () async {
await taskController.getTasks();
},
child: ListView.builder(
shrinkWrap: true,
scrollDirection:
SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
var task = taskController.fitnessTaskList![index];
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 1375),
child: SlideAnimation(
horizontalOffset: 300,
child: FadeInAnimation(
child: GestureDetector(
onTap: (() {
showBottomSheet(
context,
task,
);
}),
child: TaskTile(task),
),
),
),
);
},
itemCount: taskController.fitnessTaskList!.length,
),
);
}
}),
),
],
),
);
}
noTasks(context) => Center(
child: Stack(
children: [
AnimatedPositioned(
duration: const Duration(
milliseconds: 2000,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
direction: SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
children: [
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 6.0,
)
: const SizedBox(
height: 220.0,
),
SvgPicture.asset(
'images/task.svg',
color: primaryClr.withOpacity(0.5),
semanticsLabel: 'Task',
height: 100.0,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 10.0,
),
child: Text(
'you don\'t have eny tasks completed yet!,\n finish some tasks',
style: subTitleStyle,
textAlign: TextAlign.center,
),
),
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 120.0,
)
: const SizedBox(
height: 180.0,
),
],
),
)
],
),
);
showBottomSheet(context, Task task) {
Get.bottomSheet(
SingleChildScrollView(
child: Container(
padding: const EdgeInsets.only(top: 4.0),
width: SizeConfig.screenWidth,
height: SizeConfig.orientation == Orientation.landscape
? task.isCompleted == 1
? SizeConfig.screenHeight * 0.6
: SizeConfig.screenHeight * 0.8
: task.isCompleted == 1
? SizeConfig.screenHeight * 0.30
: SizeConfig.screenHeight * 0.39,
color: Get.isDarkMode ? darkHeaderClr : Colors.white,
child: Expanded(
child: Column(
children: [
Flexible(
child: Container(
height: 6.0,
width: 120.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color:
Get.isDarkMode ? Colors.grey[600] : Colors.grey[300],
),
),
),
const SizedBox(
height: 20.0,
),
if (task.isCompleted == 0)
buildBottomSheet(
label: 'Task Completed',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.taskCompleted(task.id!);
Get.back();
},
color: primaryClr,
),
buildBottomSheet(
label: 'Edit Task',
onTap: () {
Get.back();
Get.to(UpdateTaskScreen(
task: task,
));
},
color: primaryClr,
),
buildBottomSheet(
label: 'Delete Task',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.deleteTasks(task);
Get.back();
},
color: Colors.red,
),
Divider(
color: Get.isDarkMode ? Colors.grey : darkGreyClr,
),
buildBottomSheet(
label: 'Cancle',
onTap: () {
Get.back();
},
color: primaryClr,
),
const SizedBox(
height: 10.0,
),
],
),
),
),
),
);
}
buildBottomSheet({
required String label,
required Function() onTap,
required Color color,
bool isClose = false,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4.0),
height: 55.0,
width: SizeConfig.screenWidth * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: isClose
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[300]!
: color,
),
borderRadius: BorderRadius.circular(20.0),
color: isClose ? Colors.transparent : color,
),
child: Center(
child: Text(
label,
style: isClose
? titleStyle
: titleStyle.copyWith(
color: Colors.white,
),
),
),
),
);
}
}
// DatePicker(
// DateTime.now(),
// height: 100.0,
// width: 70.0,
// initialSelectedDate: DateTime.now(),
// selectedTextColor: Colors.white,
// selectionColor: primaryClr,
// onDateChange: (date) {
// setState(() {
// selecedTime = date;
// });
// },
// dateTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 20.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// dayTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// monthTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 12.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// ), | 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/personal_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:to_do/services/notification_services.dart';
import 'package:to_do/ui/pages/update_task_screen.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/task_tile.dart';
import '../../controllers/task_controller.dart';
import '../../models/task.dart';
class PersonalTasks extends StatefulWidget {
const PersonalTasks({Key? key}) : super(key: key);
@override
State<PersonalTasks> createState() => _PersonalTasksState();
}
final TaskController taskController = Get.put(TaskController());
late NotifyHelper notifyHelper;
class _PersonalTasksState extends State<PersonalTasks> {
@override
void initState() {
super.initState();
notifyHelper = NotifyHelper();
notifyHelper.initializeNotification();
notifyHelper.requestIOSPermissions();
taskController.getTasks();
}
DateTime selecedTime = DateTime.now();
int currentIndex = 0;
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
backgroundColor: Theme.of(context).backgroundColor,
elevation: 0.0,
title: Text(
'Personal',
style: headingStyle.copyWith(
color: primaryClr,
),
),
),
body: Column(
children: [
// Container(
// margin: const EdgeInsets.only(
// left: 20.0,
// right: 10.0,
// top: 10.0,
// ),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// DateFormat.yMMMd().format(DateTime.now()),
// style: subHeadingStyle,
// ),
// Text(
// 'Today',
// style: headingStyle,
// ),
// ],
// ),
// // CustomButton(
// // lable: '+ add task',
// // onTap: () async {
// // await Get.to(const AddTaskPage());
// // taskController.getTasks();
// // },
// // ),
// Padding(
// padding: const EdgeInsets.only(right: 15.0),
// child: IconButton(
// onPressed: () {
// Get.defaultDialog(
// title: 'Warning',
// middleText:
// 'This button will delete all tasks,if you agree press OK.',
// titleStyle: const TextStyle(color: Colors.red),
// textCancel: 'Cancel',
// textConfirm: 'OK',
// onConfirm: () {
// notifyHelper.cancelAllNotification();
// taskController.deleteAllTasks();
// Get.back();
// },
// cancelTextColor: Colors.grey,
// confirmTextColor: Colors.white,
// buttonColor: primaryClr,
// );
// },
// icon: Icon(
// Icons.delete,
// size: 30.0,
// color: Get.isDarkMode ? Colors.white : darkGreyClr,
// ),
// ),
// ),
// ],
// ),
// ),
// Container(
// margin: const EdgeInsets.only(top: 6.0, left: 20.0),
// child: CalendarTimeline(
// initialDate: selecedTime,
// firstDate: DateTime(2021, 1, 15),
// lastDate: DateTime(2030, 11, 20),
// onDateSelected: (date) {
// setState(() {
// selecedTime = date!;
// });
// },
// leftMargin: 20,
// monthColor: Colors.grey,
// dayColor: Colors.blueAccent[100],
// activeDayColor: Colors.white,
// activeBackgroundDayColor: primaryClr,
// dotsColor: const Color(0xFF333A47),
// selectableDayPredicate: (date) => date.day != 23,
// locale: 'en_ISO',
// ),
// ),
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'Personal Tasks',
style: headingStyle,
),
),
],
),
const SizedBox(
height: 20.0,
),
Expanded(
child: Obx(() {
if (taskController.personalTaskList!.isEmpty) {
return noTasks(context);
} else {
return RefreshIndicator(
onRefresh: () async {
await taskController.getTasks();
},
child: ListView.builder(
shrinkWrap: true,
scrollDirection:
SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
var task = taskController.personalTaskList![index];
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 1375),
child: SlideAnimation(
horizontalOffset: 300,
child: FadeInAnimation(
child: GestureDetector(
onTap: (() {
showBottomSheet(
context,
task,
);
}),
child: TaskTile(task),
),
),
),
);
},
itemCount: taskController.personalTaskList!.length,
),
);
}
}),
),
],
),
);
}
noTasks(context) => Center(
child: Stack(
children: [
AnimatedPositioned(
duration: const Duration(
milliseconds: 2000,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
direction: SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
children: [
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 6.0,
)
: const SizedBox(
height: 220.0,
),
SvgPicture.asset(
'images/task.svg',
color: primaryClr.withOpacity(0.5),
semanticsLabel: 'Task',
height: 100.0,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 10.0,
),
child: Text(
'you don\'t have eny tasks completed yet!,\n finish some tasks',
style: subTitleStyle,
textAlign: TextAlign.center,
),
),
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 120.0,
)
: const SizedBox(
height: 180.0,
),
],
),
)
],
),
);
showBottomSheet(context, Task task) {
Get.bottomSheet(
SingleChildScrollView(
child: Container(
padding: const EdgeInsets.only(top: 4.0),
width: SizeConfig.screenWidth,
height: SizeConfig.orientation == Orientation.landscape
? task.isCompleted == 1
? SizeConfig.screenHeight * 0.6
: SizeConfig.screenHeight * 0.8
: task.isCompleted == 1
? SizeConfig.screenHeight * 0.30
: SizeConfig.screenHeight * 0.39,
color: Get.isDarkMode ? darkHeaderClr : Colors.white,
child: Expanded(
child: Column(
children: [
Flexible(
child: Container(
height: 6.0,
width: 120.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color:
Get.isDarkMode ? Colors.grey[600] : Colors.grey[300],
),
),
),
const SizedBox(
height: 20.0,
),
if (task.isCompleted == 0)
buildBottomSheet(
label: 'Task Completed',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.taskCompleted(task.id!);
Get.back();
},
color: primaryClr,
),
buildBottomSheet(
label: 'Edit Task',
onTap: () {
Get.back();
Get.to(UpdateTaskScreen(
task: task,
));
},
color: primaryClr,
),
buildBottomSheet(
label: 'Delete Task',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.deleteTasks(task);
Get.back();
},
color: Colors.red,
),
Divider(
color: Get.isDarkMode ? Colors.grey : darkGreyClr,
),
buildBottomSheet(
label: 'Cancle',
onTap: () {
Get.back();
},
color: primaryClr,
),
const SizedBox(
height: 10.0,
),
],
),
),
),
),
);
}
buildBottomSheet({
required String label,
required Function() onTap,
required Color color,
bool isClose = false,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4.0),
height: 55.0,
width: SizeConfig.screenWidth * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: isClose
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[300]!
: color,
),
borderRadius: BorderRadius.circular(20.0),
color: isClose ? Colors.transparent : color,
),
child: Center(
child: Text(
label,
style: isClose
? titleStyle
: titleStyle.copyWith(
color: Colors.white,
),
),
),
),
);
}
}
// DatePicker(
// DateTime.now(),
// height: 100.0,
// width: 70.0,
// initialSelectedDate: DateTime.now(),
// selectedTextColor: Colors.white,
// selectionColor: primaryClr,
// onDateChange: (date) {
// setState(() {
// selecedTime = date;
// });
// },
// dateTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 20.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// dayTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// monthTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 12.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// ), | 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/on_boarding_screen.dart | import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/button.dart';
import '../../services/theme_services.dart';
class OnBoardingModel {
final String image;
final String title;
final String subtitle;
OnBoardingModel(
{required this.image, required this.title, required this.subtitle});
}
class OnBoardingScreen extends StatefulWidget {
const OnBoardingScreen({Key? key}) : super(key: key);
@override
State<OnBoardingScreen> createState() => _OnBoardingScreenState();
}
class _OnBoardingScreenState extends State<OnBoardingScreen> {
var onBoardingController = PageController();
bool isLast = false;
bool onBoarding = false;
List<OnBoardingModel> screens = [
OnBoardingModel(
image: 'images/onBoarding1.png',
title: 'Cheklist Finished Task',
subtitle:
'if you completed your task,so you can view the result you work for each day.',
),
OnBoardingModel(
image: 'images/onBoarding2.png',
title: 'Create Your Task',
subtitle:
'Create your task to make sure every task you have can completed on time.',
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
elevation: 0.0,
backgroundColor: Theme.of(context).backgroundColor,
actions: [
Padding(
padding: const EdgeInsets.only(right: 15.0),
child: TextButton(
onPressed: () {
BoardingServices().switchScreen(onBoarding);
},
child: Text(
'SKIP',
style: TextStyle(
color: Get.isDarkMode ? Colors.grey[100] : Colors.grey[400],
),
),
),
),
],
),
body: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(
children: [
SmoothPageIndicator(
controller: onBoardingController,
count: screens.length,
effect: ExpandingDotsEffect(
dotColor:
Get.isDarkMode ? Colors.grey[100]! : Colors.grey[300]!,
activeDotColor: primaryClr,
dotHeight: 10,
expansionFactor: 4,
dotWidth: 10,
spacing: 5.0,
),
),
const SizedBox(
height: 20.0,
),
Expanded(
child: PageView.builder(
controller: onBoardingController,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) =>
buildBoardingItem(screens[index], context),
itemCount: screens.length,
onPageChanged: (int index) {
if (index == screens.length - 1) {
setState(() {
isLast = true;
});
} else {
isLast = false;
}
},
),
),
const SizedBox(
height: 10.0,
),
CustomButton(
lable: 'Next',
onTap: () {
if (isLast) {
BoardingServices().switchScreen(onBoarding);
} else {
onBoardingController.nextPage(
duration: const Duration(milliseconds: 750),
curve: Curves.fastLinearToSlowEaseIn,
);
}
},
),
],
),
),
);
}
}
Widget buildBoardingItem(OnBoardingModel model, context) => Column(
children: [
Expanded(
child: CircleAvatar(
backgroundColor: Theme.of(context).backgroundColor,
radius: 180.0,
backgroundImage: AssetImage(model.image),
),
),
const SizedBox(
height: 20.0,
),
Text(
model.title,
style: headingStyle,
textAlign: TextAlign.center,
),
const SizedBox(
height: 10.0,
),
Text(
model.subtitle,
style: subHeadingStyle.copyWith(
fontSize: 15.0,
),
textAlign: TextAlign.center,
),
const SizedBox(
height: 20.0,
),
],
);
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/completed_task_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:to_do/services/notification_services.dart';
import 'package:to_do/ui/pages/update_task_screen.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/task_tile.dart';
import '../../controllers/task_controller.dart';
import '../../models/task.dart';
class CompletedTasks extends StatefulWidget {
const CompletedTasks({Key? key}) : super(key: key);
@override
State<CompletedTasks> createState() => _CompletedTasksState();
}
final TaskController taskController = Get.put(TaskController());
late NotifyHelper notifyHelper;
class _CompletedTasksState extends State<CompletedTasks> {
@override
void initState() {
super.initState();
// notifyHelper = NotifyHelper();
// notifyHelper.initializeNotification();
// notifyHelper.requestIOSPermissions();
taskController.getTasks();
}
DateTime selecedTime = DateTime.now();
int currentIndex = 0;
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Column(
children: [
// Container(
// margin: const EdgeInsets.only(
// left: 20.0,
// right: 10.0,
// top: 10.0,
// ),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// DateFormat.yMMMd().format(DateTime.now()),
// style: subHeadingStyle,
// ),
// Text(
// 'Today',
// style: headingStyle,
// ),
// ],
// ),
// // CustomButton(
// // lable: '+ add task',
// // onTap: () async {
// // await Get.to(const AddTaskPage());
// // taskController.getTasks();
// // },
// // ),
// Padding(
// padding: const EdgeInsets.only(right: 15.0),
// child: IconButton(
// onPressed: () {
// Get.defaultDialog(
// title: 'Warning',
// middleText:
// 'This button will delete all tasks,if you agree press OK.',
// titleStyle: const TextStyle(color: Colors.red),
// textCancel: 'Cancel',
// textConfirm: 'OK',
// onConfirm: () {
// notifyHelper.cancelAllNotification();
// taskController.deleteAllTasks();
// Get.back();
// },
// cancelTextColor: Colors.grey,
// confirmTextColor: Colors.white,
// buttonColor: primaryClr,
// );
// },
// icon: Icon(
// Icons.delete,
// size: 30.0,
// color: Get.isDarkMode ? Colors.white : darkGreyClr,
// ),
// ),
// ),
// ],
// ),
// ),
// Container(
// margin: const EdgeInsets.only(top: 6.0, left: 20.0),
// child: CalendarTimeline(
// initialDate: selecedTime,
// firstDate: DateTime(2021, 1, 15),
// lastDate: DateTime(2030, 11, 20),
// onDateSelected: (date) {
// setState(() {
// selecedTime = date!;
// });
// },
// leftMargin: 20,
// monthColor: Colors.grey,
// dayColor: Colors.blueAccent[100],
// activeDayColor: Colors.white,
// activeBackgroundDayColor: primaryClr,
// dotsColor: const Color(0xFF333A47),
// selectableDayPredicate: (date) => date.day != 23,
// locale: 'en_ISO',
// ),
// ),
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'Completed Tasks',
style: headingStyle,
),
),
],
),
const SizedBox(
height: 20.0,
),
Expanded(
child: Obx(() {
if (taskController.taskCompletedList!.isEmpty) {
return noTasks(context);
} else {
return RefreshIndicator(
onRefresh: () async {
await taskController.getTasks();
},
child: ListView.builder(
shrinkWrap: true,
scrollDirection:
SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
var task = taskController.taskCompletedList![index];
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 1375),
child: SlideAnimation(
horizontalOffset: 300,
child: FadeInAnimation(
child: GestureDetector(
onTap: (() {
showBottomSheet(
context,
task,
);
}),
child: TaskTile(task),
),
),
),
);
},
itemCount: taskController.taskCompletedList!.length,
),
);
}
}),
),
],
);
}
noTasks(context) => Center(
child: Stack(
children: [
AnimatedPositioned(
duration: const Duration(
milliseconds: 2000,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
direction: SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
children: [
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 6.0,
)
: const SizedBox(
height: 220.0,
),
SvgPicture.asset(
'images/task.svg',
color: primaryClr.withOpacity(0.5),
semanticsLabel: 'Task',
height: 100.0,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 10.0,
),
child: Text(
'you don\'t have eny tasks completed yet!,\n finish some tasks',
style: subTitleStyle,
textAlign: TextAlign.center,
),
),
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 120.0,
)
: const SizedBox(
height: 180.0,
),
],
),
)
],
),
);
showBottomSheet(context, Task task) {
Get.bottomSheet(
SingleChildScrollView(
child: Container(
padding: const EdgeInsets.only(top: 4.0),
width: SizeConfig.screenWidth,
height: SizeConfig.orientation == Orientation.landscape
? task.isCompleted == 1
? SizeConfig.screenHeight * 0.6
: SizeConfig.screenHeight * 0.8
: task.isCompleted == 1
? SizeConfig.screenHeight * 0.30
: SizeConfig.screenHeight * 0.39,
color: Get.isDarkMode ? darkHeaderClr : Colors.white,
child: Expanded(
child: Column(
children: [
Flexible(
child: Container(
height: 6.0,
width: 120.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color:
Get.isDarkMode ? Colors.grey[600] : Colors.grey[300],
),
),
),
const SizedBox(
height: 20.0,
),
if (task.isCompleted == 0)
buildBottomSheet(
label: 'Task Completed',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.taskCompleted(task.id!);
Get.back();
},
color: primaryClr,
),
buildBottomSheet(
label: 'Edit Task',
onTap: () {
Get.back();
Get.to(UpdateTaskScreen(
task: task,
));
},
color: primaryClr,
),
buildBottomSheet(
label: 'Delete Task',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.deleteTasks(task);
Get.back();
},
color: Colors.red,
),
Divider(
color: Get.isDarkMode ? Colors.grey : darkGreyClr,
),
buildBottomSheet(
label: 'Cancle',
onTap: () {
Get.back();
},
color: primaryClr,
),
const SizedBox(
height: 10.0,
),
],
),
),
),
),
);
}
buildBottomSheet({
required String label,
required Function() onTap,
required Color color,
bool isClose = false,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4.0),
height: 55.0,
width: SizeConfig.screenWidth * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: isClose
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[300]!
: color,
),
borderRadius: BorderRadius.circular(20.0),
color: isClose ? Colors.transparent : color,
),
child: Center(
child: Text(
label,
style: isClose
? titleStyle
: titleStyle.copyWith(
color: Colors.white,
),
),
),
),
);
}
}
// DatePicker(
// DateTime.now(),
// height: 100.0,
// width: 70.0,
// initialSelectedDate: DateTime.now(),
// selectedTextColor: Colors.white,
// selectionColor: primaryClr,
// onDateChange: (date) {
// setState(() {
// selecedTime = date;
// });
// },
// dateTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 20.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// dayTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// monthTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 12.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// ), | 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/splash_screen.dart | import 'package:easy_splash_screen/easy_splash_screen.dart';
import 'package:flutter/material.dart';
import '../../services/theme_services.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: EasySplashScreen(
logo: Image.asset('images/todo_icon.png'),
title: const Text(
'ToDo List',
style: TextStyle(
fontSize: 18.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
loadingText: const Text(
'From\nONE PIECE',
style: TextStyle(
color: Colors.black,
fontSize: 16.0,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
showLoader: false,
durationInSeconds: 2,
navigator: BoardingServices().screen,
),
);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/login_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_custom_clippers/flutter_custom_clippers.dart';
import 'package:get/get.dart';
import 'package:to_do/ui/pages/layout.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/button.dart';
import 'package:to_do/ui/widgets/input_field.dart';
import '../../services/theme_services.dart';
import '../size_config.dart';
String username = 'User';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
var nameController = TextEditingController();
bool login = false;
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
body: SingleChildScrollView(
child: Column(
children: [
Stack(
alignment: Alignment.centerLeft,
children: [
ClipPath(
clipper: WaveClipperTwo(),
child: Container(
height: 300.0,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
primaryClr,
Colors.blue[500]!,
],
),
),
),
),
const Padding(
padding: EdgeInsets.only(left: 25.0),
child: Text(
'LOGIN',
style: TextStyle(
fontSize: 40.0,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
],
),
Padding(
padding: const EdgeInsets.only(
top: 30.0,
left: 20.0,
right: 20.0,
bottom: 10.0,
),
child: Text(
'enter your name to login and create your first task',
style: Theme.of(context)
.textTheme
.caption!
.copyWith(fontSize: 15.0),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: InputField(
controller: nameController,
title: 'Name',
hint: 'Enter your frist name here...',
),
),
const SizedBox(
height: 30.0,
),
CustomButton(
lable: 'Next',
onTap: () {
if (nameController.text != '') {
setState(() {
username = nameController.text;
});
LoginScreenServices().switchScreen(login);
print(username);
} else {
Get.snackbar(
'Name Required',
'Please enter your name',
colorText: Colors.red,
backgroundColor: Colors.white,
);
}
},
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/to_do_task_screen.dart | import 'package:calendar_timeline/calendar_timeline.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:to_do/services/notification_services.dart';
import 'package:to_do/ui/pages/completed_task_screen.dart';
import 'package:to_do/ui/pages/update_task_screen.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/task_tile.dart';
import '../../models/task.dart';
class ToDoTasks extends StatefulWidget {
const ToDoTasks({Key? key}) : super(key: key);
@override
State<ToDoTasks> createState() => _ToDoTasksState();
}
// final TaskController taskController = Get.put(TaskController());
// late NotifyHelper notifyHelper;
class _ToDoTasksState extends State<ToDoTasks> {
@override
void initState() {
super.initState();
notifyHelper = NotifyHelper();
notifyHelper.initializeNotification();
notifyHelper.requestIOSPermissions();
//taskController.getTasks();
}
DateTime selecedTime = DateTime.now();
int currentIndex = 0;
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Column(
children: [
Container(
margin: const EdgeInsets.only(
left: 20.0,
right: 10.0,
top: 10.0,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
DateFormat.yMMMd().format(DateTime.now()),
style: subHeadingStyle,
),
Text(
'Today',
style: headingStyle,
),
],
),
// CustomButton(
// lable: '+ add task',
// onTap: () async {
// await Get.to(const AddTaskPage());
// taskController.getTasks();
// },
// ),
Padding(
padding: const EdgeInsets.only(right: 15.0),
child: IconButton(
onPressed: () {
Get.defaultDialog(
title: 'Warning',
middleText:
'This button will delete all tasks,if you agree press OK.',
titleStyle: const TextStyle(color: Colors.red),
textCancel: 'Cancel',
textConfirm: 'OK',
onConfirm: () {
notifyHelper.cancelAllNotification();
taskController.deleteAllTasks();
Get.back();
},
cancelTextColor: Colors.grey,
confirmTextColor: Colors.white,
buttonColor: primaryClr,
);
},
icon: Icon(
Icons.delete,
size: 30.0,
color: Get.isDarkMode ? Colors.white : darkGreyClr,
),
),
),
],
),
),
Container(
margin: const EdgeInsets.only(top: 6.0, left: 20.0),
child: CalendarTimeline(
initialDate: selecedTime,
firstDate: DateTime(2021, 1, 15),
lastDate: DateTime(2030, 11, 20),
onDateSelected: (date) {
setState(() {
selecedTime = date!;
});
},
leftMargin: 20,
monthColor: Colors.grey,
dayColor: Colors.blueAccent[100],
activeDayColor: Colors.white,
activeBackgroundDayColor: primaryClr,
dotsColor: const Color(0xFF333A47),
selectableDayPredicate: (date) => date.day != 23,
locale: 'en_ISO',
),
),
const SizedBox(
height: 8.0,
),
Expanded(
child: Obx(() {
if (taskController.taskList!.isEmpty) {
return noTasks(context);
} else {
return RefreshIndicator(
onRefresh: () async {
await taskController.getTasks();
},
child: ListView.builder(
shrinkWrap: true,
scrollDirection:
SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
var task = taskController.taskList![index];
if (task.repeat == 'Daily' ||
task.date == DateFormat.yMd().format(selecedTime) ||
(task.repeat == 'Weekly' &&
selecedTime
.difference(
DateFormat.yMd().parse(task.date!))
.inDays %
7 ==
0) ||
(task.repeat == 'Monthly' &&
DateFormat.yMd().parse(task.date!).day ==
selecedTime.day)) {
// var hour = task.startTime.toString().split(':')[0];
// var minutes = task.startTime.toString().split(':')[1];
var date = DateFormat.jm().parse(task.startTime!);
var time = DateFormat('HH:mm').format(date);
notifyHelper.scheduledNotification(
int.parse(time.toString().split(':')[0]),
int.parse(time.toString().split(':')[1]),
task);
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 1375),
child: SlideAnimation(
horizontalOffset: 300,
child: FadeInAnimation(
child: GestureDetector(
onTap: (() {
showBottomSheet(
context,
task,
);
}),
child: task.isCompleted == 0
? TaskTile(task)
: Container(),
),
),
),
);
} else {
return Container();
}
},
itemCount: taskController.taskList!.length,
),
);
}
}),
),
],
);
}
noTasks(context) => Stack(
children: [
AnimatedPositioned(
duration: const Duration(
milliseconds: 2000,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
direction: SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
children: [
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 6.0,
)
: const SizedBox(
height: 220.0,
),
SvgPicture.asset(
'images/task.svg',
color: primaryClr.withOpacity(0.5),
semanticsLabel: 'Task',
height: 100.0,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 10.0,
),
child: Text(
'you don\'t have eny tasks yet!,\n add new task to make your day productive',
style: subTitleStyle,
textAlign: TextAlign.center,
),
),
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 120.0,
)
: const SizedBox(
height: 180.0,
),
],
),
)
],
);
showBottomSheet(context, Task task) {
Get.bottomSheet(
SingleChildScrollView(
child: Container(
padding: const EdgeInsets.only(top: 4.0),
width: SizeConfig.screenWidth,
height: SizeConfig.orientation == Orientation.landscape
? task.isCompleted == 1
? SizeConfig.screenHeight * 0.6
: SizeConfig.screenHeight * 0.8
: task.isCompleted == 1
? SizeConfig.screenHeight * 0.30
: SizeConfig.screenHeight * 0.39,
color: Get.isDarkMode ? darkHeaderClr : Colors.white,
child: Expanded(
child: Column(
children: [
Flexible(
child: Container(
height: 6.0,
width: 120.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color:
Get.isDarkMode ? Colors.grey[600] : Colors.grey[300],
),
),
),
const SizedBox(
height: 20.0,
),
if (task.isCompleted == 0)
buildBottomSheet(
label: 'Task Completed',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.taskCompleted(task.id!);
Get.back();
},
color: primaryClr,
),
buildBottomSheet(
label: 'Edit Task',
onTap: () {
Get.back();
Get.to(UpdateTaskScreen(
task: task,
));
},
color: primaryClr,
),
buildBottomSheet(
label: 'Delete Task',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.deleteTasks(task);
Get.back();
},
color: Colors.red,
),
Divider(
color: Get.isDarkMode ? Colors.grey : darkGreyClr,
),
buildBottomSheet(
label: 'Cancle',
onTap: () {
Get.back();
},
color: primaryClr,
),
const SizedBox(
height: 10.0,
),
],
),
),
),
),
);
}
buildBottomSheet({
required String label,
required Function() onTap,
required Color color,
bool isClose = false,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4.0),
height: 55.0,
width: SizeConfig.screenWidth * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: isClose
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[300]!
: color,
),
borderRadius: BorderRadius.circular(20.0),
color: isClose ? Colors.transparent : color,
),
child: Center(
child: Text(
label,
style: isClose
? titleStyle
: titleStyle.copyWith(
color: Colors.white,
),
),
),
),
);
}
}
// DatePicker(
// DateTime.now(),
// height: 100.0,
// width: 70.0,
// initialSelectedDate: DateTime.now(),
// selectedTextColor: Colors.white,
// selectionColor: primaryClr,
// onDateChange: (date) {
// setState(() {
// selecedTime = date;
// });
// },
// dateTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 20.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// dayTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// monthTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 12.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// ), | 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/work_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:to_do/services/notification_services.dart';
import 'package:to_do/ui/pages/update_task_screen.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/task_tile.dart';
import '../../controllers/task_controller.dart';
import '../../models/task.dart';
class WorkTasks extends StatefulWidget {
const WorkTasks({Key? key}) : super(key: key);
@override
State<WorkTasks> createState() => _WorkTasksState();
}
final TaskController taskController = Get.put(TaskController());
late NotifyHelper notifyHelper;
class _WorkTasksState extends State<WorkTasks> {
@override
void initState() {
super.initState();
notifyHelper = NotifyHelper();
notifyHelper.initializeNotification();
notifyHelper.requestIOSPermissions();
taskController.getTasks();
}
DateTime selecedTime = DateTime.now();
int currentIndex = 0;
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
backgroundColor: Theme.of(context).backgroundColor,
elevation: 0.0,
title: Text(
'Work',
style: headingStyle.copyWith(
color: primaryClr,
),
),
),
body: Column(
children: [
// Container(
// margin: const EdgeInsets.only(
// left: 20.0,
// right: 10.0,
// top: 10.0,
// ),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// DateFormat.yMMMd().format(DateTime.now()),
// style: subHeadingStyle,
// ),
// Text(
// 'Today',
// style: headingStyle,
// ),
// ],
// ),
// // CustomButton(
// // lable: '+ add task',
// // onTap: () async {
// // await Get.to(const AddTaskPage());
// // taskController.getTasks();
// // },
// // ),
// Padding(
// padding: const EdgeInsets.only(right: 15.0),
// child: IconButton(
// onPressed: () {
// Get.defaultDialog(
// title: 'Warning',
// middleText:
// 'This button will delete all tasks,if you agree press OK.',
// titleStyle: const TextStyle(color: Colors.red),
// textCancel: 'Cancel',
// textConfirm: 'OK',
// onConfirm: () {
// notifyHelper.cancelAllNotification();
// taskController.deleteAllTasks();
// Get.back();
// },
// cancelTextColor: Colors.grey,
// confirmTextColor: Colors.white,
// buttonColor: primaryClr,
// );
// },
// icon: Icon(
// Icons.delete,
// size: 30.0,
// color: Get.isDarkMode ? Colors.white : darkGreyClr,
// ),
// ),
// ),
// ],
// ),
// ),
// Container(
// margin: const EdgeInsets.only(top: 6.0, left: 20.0),
// child: CalendarTimeline(
// initialDate: selecedTime,
// firstDate: DateTime(2021, 1, 15),
// lastDate: DateTime(2030, 11, 20),
// onDateSelected: (date) {
// setState(() {
// selecedTime = date!;
// });
// },
// leftMargin: 20,
// monthColor: Colors.grey,
// dayColor: Colors.blueAccent[100],
// activeDayColor: Colors.white,
// activeBackgroundDayColor: primaryClr,
// dotsColor: const Color(0xFF333A47),
// selectableDayPredicate: (date) => date.day != 23,
// locale: 'en_ISO',
// ),
// ),
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'Work Tasks',
style: headingStyle,
),
),
],
),
const SizedBox(
height: 20.0,
),
Expanded(
child: Obx(() {
if (taskController.workTaskList!.isEmpty) {
return noTasks(context);
} else {
return RefreshIndicator(
onRefresh: () async {
await taskController.getTasks();
},
child: ListView.builder(
shrinkWrap: true,
scrollDirection:
SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
var task = taskController.workTaskList![index];
return AnimationConfiguration.staggeredList(
position: index,
duration: const Duration(milliseconds: 1375),
child: SlideAnimation(
horizontalOffset: 300,
child: FadeInAnimation(
child: GestureDetector(
onTap: (() {
showBottomSheet(
context,
task,
);
}),
child: TaskTile(task),
),
),
),
);
},
itemCount: taskController.workTaskList!.length,
),
);
}
}),
),
],
),
);
}
noTasks(context) => Center(
child: Stack(
children: [
AnimatedPositioned(
duration: const Duration(
milliseconds: 2000,
),
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
direction: SizeConfig.orientation == Orientation.landscape
? Axis.horizontal
: Axis.vertical,
children: [
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 6.0,
)
: const SizedBox(
height: 220.0,
),
SvgPicture.asset(
'images/task.svg',
color: primaryClr.withOpacity(0.5),
semanticsLabel: 'Task',
height: 100.0,
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 10.0,
),
child: Text(
'you don\'t have eny tasks completed yet!,\n finish some tasks',
style: subTitleStyle,
textAlign: TextAlign.center,
),
),
SizeConfig.orientation == Orientation.landscape
? const SizedBox(
height: 120.0,
)
: const SizedBox(
height: 180.0,
),
],
),
)
],
),
);
showBottomSheet(context, Task task) {
Get.bottomSheet(
SingleChildScrollView(
child: Container(
padding: const EdgeInsets.only(top: 4.0),
width: SizeConfig.screenWidth,
height: SizeConfig.orientation == Orientation.landscape
? task.isCompleted == 1
? SizeConfig.screenHeight * 0.6
: SizeConfig.screenHeight * 0.8
: task.isCompleted == 1
? SizeConfig.screenHeight * 0.30
: SizeConfig.screenHeight * 0.39,
color: Get.isDarkMode ? darkHeaderClr : Colors.white,
child: Expanded(
child: Column(
children: [
Flexible(
child: Container(
height: 6.0,
width: 120.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color:
Get.isDarkMode ? Colors.grey[600] : Colors.grey[300],
),
),
),
const SizedBox(
height: 20.0,
),
if (task.isCompleted == 0)
buildBottomSheet(
label: 'Task Completed',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.taskCompleted(task.id!);
Get.back();
},
color: primaryClr,
),
buildBottomSheet(
label: 'Edit Task',
onTap: () {
Get.back();
Get.to(UpdateTaskScreen(
task: task,
));
},
color: primaryClr,
),
buildBottomSheet(
label: 'Delete Task',
onTap: () {
notifyHelper.cancelNotification(task);
taskController.deleteTasks(task);
Get.back();
},
color: Colors.red,
),
Divider(
color: Get.isDarkMode ? Colors.grey : darkGreyClr,
),
buildBottomSheet(
label: 'Cancle',
onTap: () {
Get.back();
},
color: primaryClr,
),
const SizedBox(
height: 10.0,
),
],
),
),
),
),
);
}
buildBottomSheet({
required String label,
required Function() onTap,
required Color color,
bool isClose = false,
}) {
return GestureDetector(
onTap: onTap,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4.0),
height: 55.0,
width: SizeConfig.screenWidth * 0.9,
decoration: BoxDecoration(
border: Border.all(
width: 2.0,
color: isClose
? Get.isDarkMode
? Colors.grey[600]!
: Colors.grey[300]!
: color,
),
borderRadius: BorderRadius.circular(20.0),
color: isClose ? Colors.transparent : color,
),
child: Center(
child: Text(
label,
style: isClose
? titleStyle
: titleStyle.copyWith(
color: Colors.white,
),
),
),
),
);
}
}
// DatePicker(
// DateTime.now(),
// height: 100.0,
// width: 70.0,
// initialSelectedDate: DateTime.now(),
// selectedTextColor: Colors.white,
// selectionColor: primaryClr,
// onDateChange: (date) {
// setState(() {
// selecedTime = date;
// });
// },
// dateTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 20.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// dayTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 16.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// monthTextStyle: GoogleFonts.lato(
// textStyle: const TextStyle(
// color: Colors.grey,
// fontSize: 12.0,
// fontWeight: FontWeight.w600,
// ),
// ),
// ), | 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/notification_screen.dart | import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:to_do/ui/pages/login_screen.dart';
import 'package:to_do/ui/theme.dart';
class NotificationScreen extends StatefulWidget {
const NotificationScreen({Key? key, required this.payload}) : super(key: key);
final payload;
@override
_NotificationScreenState createState() => _NotificationScreenState();
}
class _NotificationScreenState extends State<NotificationScreen> {
String payload = '';
@override
void initState() {
super.initState();
payload = widget.payload;
}
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
titleSpacing: 0.0,
title: Text(
payload.toString().split('|')[0],
style: TextStyle(
color: Get.isDarkMode ? Colors.white : darkGreyClr,
),
),
leading: IconButton(
padding: const EdgeInsets.only(
left: 10.0,
),
onPressed: () => Get.back(),
icon: Icon(
Icons.arrow_back_ios,
color: Get.isDarkMode ? Colors.white : darkGreyClr,
),
),
elevation: 0.0,
backgroundColor: Theme.of(context).backgroundColor,
),
body: Column(
children: [
const SizedBox(
height: 20.0,
),
Column(
children: [
Text(
'Hello , $username',
style: TextStyle(
color: Get.isDarkMode ? Colors.white : darkGreyClr,
fontSize: 26,
fontWeight: FontWeight.w900,
),
),
const SizedBox(
height: 10.0,
),
Text(
'you have a new reminder',
style: TextStyle(
color: Get.isDarkMode ? Colors.grey[100] : darkGreyClr,
fontSize: 18,
fontWeight: FontWeight.w900,
),
),
],
),
const SizedBox(
height: 10.0,
),
Expanded(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
vertical: 10.0,
),
margin: const EdgeInsets.symmetric(
horizontal: 30.0,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
color: primaryClr,
),
child: SingleChildScrollView(
child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: const [
Icon(
Icons.text_format,
size: 35.0,
color: Colors.white,
),
SizedBox(
width: 3.0,
),
Text(
'Title',
style: TextStyle(
color: Colors.white,
fontSize: 30,
),
),
],
),
const SizedBox(
height: 10.0,
),
Text(
payload.toString().split('|')[0],
style: const TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
const SizedBox(
height: 20.0,
),
Row(
children: const [
Icon(
Icons.description,
size: 35.0,
color: Colors.white,
),
SizedBox(
width: 3.0,
),
Text(
'Description',
style: TextStyle(
color: Colors.white,
fontSize: 30,
),
),
],
),
const SizedBox(
height: 10.0,
),
Text(
payload.toString().split('|')[1],
style: const TextStyle(
color: Colors.white,
fontSize: 20.0,
),
textAlign: TextAlign.justify,
),
const SizedBox(
height: 20.0,
),
Row(
children: const [
Icon(
Icons.calendar_today_outlined,
size: 35.0,
color: Colors.white,
),
SizedBox(
width: 4.0,
),
Text(
'Date',
style: TextStyle(
color: Colors.white,
fontSize: 30,
),
),
],
),
const SizedBox(
height: 10.0,
),
Text(
payload.toString().split('|')[2],
style: const TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
const SizedBox(
height: 20.0,
),
],
),
),
),
),
const SizedBox(
height: 10.0,
),
],
),
);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib/ui | mirrored_repositories/ToDoApp/lib/ui/pages/update_task_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:to_do/controllers/task_controller.dart';
import 'package:to_do/models/task.dart';
import 'package:to_do/ui/pages/layout.dart';
import 'package:to_do/ui/size_config.dart';
import 'package:to_do/ui/theme.dart';
import 'package:to_do/ui/widgets/button.dart';
import 'package:to_do/ui/widgets/input_field.dart';
class UpdateTaskScreen extends StatefulWidget {
final Task task;
const UpdateTaskScreen({
Key? key,
required this.task,
}) : super(key: key);
@override
State<UpdateTaskScreen> createState() => _UpdateTaskScreenState();
}
class _UpdateTaskScreenState extends State<UpdateTaskScreen> {
final TaskController taskController = Get.put(TaskController());
final TextEditingController titleController = TextEditingController();
final TextEditingController noteController = TextEditingController();
DateTime selectDate = DateTime.now();
String startTime = DateFormat('hh:mm a').format(DateTime.now()).toString();
String endTime = DateFormat('hh:mm a')
.format(DateTime.now().add(const Duration(minutes: 15)))
.toString();
int selectRemind = 5;
List<int> remindList = [5, 10, 15, 20];
String selectRepeat = 'none';
List<String> repeatList = ['none', 'Daily', 'Weekly', 'Monthly'];
int selectColor = 0;
String selectCategory = 'none';
List<String> categoryList = [
'none',
'learning',
'personal',
'work',
'fitness'
];
@override
void initState() {
// TODO: implement initState
super.initState();
titleController.text = widget.task.title!;
noteController.text = widget.task.note!;
selectRemind = widget.task.remind!;
selectRepeat = widget.task.repeat!;
startTime = widget.task.startTime!;
endTime = widget.task.endTime!;
selectColor = widget.task.color!;
selectDate = DateFormat.yMd().parse(widget.task.date!);
selectCategory = widget.task.category!;
}
@override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
backgroundColor: Theme.of(context).backgroundColor,
elevation: 0.0,
leading: IconButton(
padding: const EdgeInsets.only(
left: 15.0,
),
onPressed: () => Get.back(),
icon: const Icon(
Icons.arrow_back_ios,
color: primaryClr,
),
),
actions: const [
CircleAvatar(
radius: 18.0,
backgroundImage: AssetImage(
'images/op_logo.jpg',
),
),
SizedBox(
width: 20.0,
),
],
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
children: [
Text(
'Edit Task',
style: headingStyle,
),
InputField(
controller: titleController,
title: 'Title',
hint: 'Enter task title',
),
InputField(
controller: noteController,
title: 'Note',
hint: 'Enter task note',
),
InputField(
title: 'Date',
hint: DateFormat.yMd().format(selectDate),
widget: IconButton(
icon: const Icon(
Icons.calendar_today_outlined,
color: Colors.grey,
),
onPressed: () async {
DateTime? date = await showDatePicker(
context: context,
initialDate: selectDate,
firstDate: DateTime(2016),
lastDate: DateTime(2040),
);
if (date != null) {
setState(() {
selectDate = date;
});
} else {
print('no date selected');
}
},
),
),
Row(
children: [
Expanded(
child: InputField(
title: 'Start Time',
hint: startTime,
widget: IconButton(
icon: const Icon(
Icons.access_time_rounded,
color: Colors.grey,
),
onPressed: () async {
TimeOfDay? picStartTime = await showTimePicker(
context: context,
initialTime:
TimeOfDay.fromDateTime(DateTime.now()),
);
if (picStartTime != null) {
setState(() {
startTime = picStartTime.format(context);
});
} else {
print('no time selected');
}
},
),
),
),
const SizedBox(
width: 10.0,
),
Expanded(
child: InputField(
title: 'End Time',
hint: endTime,
widget: IconButton(
icon: const Icon(
Icons.access_time_rounded,
color: Colors.grey,
),
onPressed: () async {
TimeOfDay? picEndTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(DateTime.now()
.add(const Duration(minutes: 15))),
);
if (picEndTime != null) {
setState(() {
endTime = picEndTime.format(context);
});
} else {
print('no time selected');
}
},
),
),
),
],
),
InputField(
title: 'Remind',
hint: '$selectRemind minutes early',
widget: DropdownButton(
dropdownColor: Colors.blueGrey,
borderRadius: BorderRadius.circular(10.0),
items: remindList
.map<DropdownMenuItem<String>>(
(int value) => DropdownMenuItem<String>(
value: value.toString(),
child: Text(
'$value',
style: const TextStyle(
color: Colors.white,
),
),
),
)
.toList(),
onChanged: (String? newValue) {
setState(() {
selectRemind = int.parse(newValue!);
});
},
icon: const Icon(Icons.keyboard_arrow_down),
iconSize: 32.0,
elevation: 4,
style: subTitleStyle,
underline: Container(
height: 0.0,
),
),
),
InputField(
title: 'Repeat',
hint: selectRepeat,
widget: Row(
children: [
DropdownButton(
dropdownColor: Colors.blueGrey,
borderRadius: BorderRadius.circular(10.0),
items: repeatList
.map<DropdownMenuItem<String>>(
(String value) => DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: const TextStyle(
color: Colors.white,
),
),
),
)
.toList(),
onChanged: (String? newValue) {
setState(() {
selectRepeat = newValue!;
});
},
icon: const Icon(Icons.keyboard_arrow_down),
iconSize: 32.0,
elevation: 4,
style: subTitleStyle,
underline: Container(
height: 0.0,
),
),
],
),
),
InputField(
title: 'Category',
hint: selectCategory,
widget: Row(
children: [
DropdownButton(
dropdownColor: Colors.blueGrey,
borderRadius: BorderRadius.circular(10.0),
items: categoryList
.map<DropdownMenuItem<String>>(
(String value) => DropdownMenuItem<String>(
value: value,
child: Text(
value,
style: const TextStyle(
color: Colors.white,
),
),
),
)
.toList(),
onChanged: (String? newValue) {
setState(() {
selectCategory = newValue!;
});
},
icon: const Icon(Icons.keyboard_arrow_down),
iconSize: 32.0,
elevation: 4,
style: subTitleStyle,
underline: Container(
height: 0.0,
),
),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Colors',
style: titleStyle,
),
const SizedBox(
height: 3.0,
),
Row(
children: List.generate(
3,
(index) => GestureDetector(
onTap: () {
setState(() {
selectColor = index;
});
},
child: CircleAvatar(
radius: 14.0,
backgroundColor: index == 0
? primaryClr
: index == 1
? pinkClr
: orangeClr,
child: selectColor == index
? const Icon(
Icons.done,
size: 16.0,
)
: null,
),
)),
),
],
),
CustomButton(
lable: 'Update Task',
onTap: () async {
if (titleController.text != '' &&
noteController.text != '') {
final update = widget.task;
update.title = titleController.text;
update.note = noteController.text;
update.startTime = startTime;
update.endTime = endTime;
update.remind = selectRemind;
update.repeat = selectRepeat;
update.date = DateFormat.yMd().format(selectDate);
update.color = selectColor;
update.category = selectCategory;
taskController.updateTask(update);
TaskController().getTasks();
Get.back();
} else {}
},
),
],
),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/ToDoApp/lib | mirrored_repositories/ToDoApp/lib/services/theme_services.dart | import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:to_do/ui/pages/layout.dart';
import 'package:to_do/ui/pages/login_screen.dart';
import 'package:to_do/ui/pages/on_boarding_screen.dart';
class ThemeServices {
final GetStorage box = GetStorage();
final key = 'isDarkMode';
saveThemetoBox(bool isDarkMode) {
box.write(key, isDarkMode);
}
bool loadThemeFromBox() {
return box.read(key) ?? false;
}
ThemeMode get theme => loadThemeFromBox() ? ThemeMode.dark : ThemeMode.light;
void switchThemeMode() {
Get.changeThemeMode(loadThemeFromBox() ? ThemeMode.light : ThemeMode.dark);
saveThemetoBox(!loadThemeFromBox());
}
}
class BoardingServices {
final GetStorage box = GetStorage();
final boardingKey = 'onBoarding';
saveScreentoBox(bool onBoarding) {
box.write(boardingKey, onBoarding);
}
bool loadScreenFromBox() {
return box.read(boardingKey) ?? false;
}
Widget get screen => loadScreenFromBox()
? LoginScreenServices().screen
: const OnBoardingScreen();
void switchScreen(bool onBoarding) {
onBoarding = true;
saveScreentoBox(!loadScreenFromBox());
Get.off(const LoginScreen());
}
}
class LoginScreenServices {
final GetStorage box = GetStorage();
final loginKey = 'login';
saveLoginScreentoBox(bool login) {
box.write(loginKey, login);
}
bool loadLoginScreenFromBox() {
return box.read(loginKey) ?? false;
}
Widget get screen =>
loadLoginScreenFromBox() ? const ToDoLayout() : const LoginScreen();
void switchScreen(bool login) {
login = true;
saveLoginScreentoBox(!loadLoginScreenFromBox());
Get.off(const ToDoLayout());
}
}
| 0 |
mirrored_repositories/ToDoApp/lib | mirrored_repositories/ToDoApp/lib/services/notification_services.dart | import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import '/models/task.dart';
import '/ui/pages/notification_screen.dart';
class NotifyHelper {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
String selectedNotificationPayload = '';
final BehaviorSubject<String> selectNotificationSubject =
BehaviorSubject<String>();
initializeNotification() async {
tz.initializeTimeZones();
_configureSelectNotificationSubject();
await _configureLocalTimeZone();
// await requestIOSPermissions(flutterLocalNotificationsPlugin);
final IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false,
onDidReceiveLocalNotification: onDidReceiveLocalNotification,
);
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('todo_icon');
final InitializationSettings initializationSettings =
InitializationSettings(
iOS: initializationSettingsIOS,
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: (String? payload) async {
if (payload != null) {
debugPrint('notification payload: ' + payload);
}
selectNotificationSubject.add(payload!);
},
);
}
displayNotification({required String title, required String body}) async {
print('doing test');
var androidPlatformChannelSpecifics = const AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.max, priority: Priority.high);
var iOSPlatformChannelSpecifics = const IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
title,
body,
platformChannelSpecifics,
payload: 'Default_Sound',
);
}
cancelNotification(Task task) async {
await flutterLocalNotificationsPlugin.cancel(task.id!);
}
cancelAllNotification() async {
await flutterLocalNotificationsPlugin.cancelAll();
}
scheduledNotification(int hour, int minutes, Task task) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
task.id!,
task.title,
task.note,
//tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
_nextInstanceOfTenAM(
hour, minutes, task.remind!, task.repeat!, task.date!),
const NotificationDetails(
android: AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description'),
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.time,
payload: '${task.title}|${task.note}|${task.startTime}|',
);
}
tz.TZDateTime _nextInstanceOfTenAM(
int hour, int minutes, int remind, String repeat, String date) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
var formattedDate = DateFormat.yMd().parse(date);
final tz.TZDateTime fd = tz.TZDateTime.from(formattedDate, tz.local);
tz.TZDateTime scheduledDate =
tz.TZDateTime(tz.local, fd.year, fd.month, fd.day, hour, minutes);
scheduledDate = taskRemind(remind, scheduledDate);
if (scheduledDate.isBefore(now)) {
if (repeat == 'Daily') {
scheduledDate = tz.TZDateTime(tz.local, now.year, now.month,
(formattedDate.day) + 1, hour, minutes);
}
if (repeat == 'Weekly') {
scheduledDate = tz.TZDateTime(tz.local, now.year, now.month,
(formattedDate.day) + 7, hour, minutes);
}
if (repeat == 'Monthly') {
scheduledDate = tz.TZDateTime(tz.local, now.year,
(formattedDate.month) + 1, formattedDate.day, hour, minutes);
}
scheduledDate = taskRemind(remind, scheduledDate);
}
print(scheduledDate);
return scheduledDate;
}
tz.TZDateTime taskRemind(int remind, tz.TZDateTime scheduledDate) {
if (remind == 5) {
scheduledDate = scheduledDate.subtract(const Duration(minutes: 5));
}
if (remind == 10) {
scheduledDate = scheduledDate.subtract(const Duration(minutes: 10));
}
if (remind == 15) {
scheduledDate = scheduledDate.subtract(const Duration(minutes: 15));
}
if (remind == 20) {
scheduledDate = scheduledDate.subtract(const Duration(minutes: 20));
}
print(scheduledDate);
return scheduledDate;
}
void requestIOSPermissions() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
Future<void> _configureLocalTimeZone() async {
tz.initializeTimeZones();
final String timeZoneName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZoneName));
}
/* Future selectNotification(String? payload) async {
if (payload != null) {
//selectedNotificationPayload = "The best";
selectNotificationSubject.add(payload);
print('notification payload: $payload');
} else {
print("Notification Done");
}
Get.to(() => SecondScreen(selectedNotificationPayload));
} */
//Older IOS
Future onDidReceiveLocalNotification(
int id, String? title, String? body, String? payload) async {
// display a dialog with the notification details, tap ok to go to another page
/* showDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: const Text('Title'),
content: const Text('Body'),
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: const Text('Ok'),
onPressed: () async {
Navigator.of(context, rootNavigator: true).pop();
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Container(color: Colors.white),
),
);
},
)
],
),
);
*/
Get.dialog(Text(body!));
}
void _configureSelectNotificationSubject() async {
selectNotificationSubject.stream.listen((String payload) async {
debugPrint('My payload is ' + payload);
await Get.to(() => NotificationScreen(payload: payload));
});
// flutterLocalNotificationsPlugin
// .getNotificationAppLaunchDetails()
// .asStream()
// .listen((payload) async {
// await Get.to(() => NotificationScreen(payload: payload));
// });
}
}
| 0 |
mirrored_repositories/ToDoApp | mirrored_repositories/ToDoApp/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:to_do/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/day_night_login | mirrored_repositories/day_night_login/lib/main.dart | import 'package:day_night_login/routes/login.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Login(),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/routes/login.dart | import 'package:day_night_login/components/arrow_button.dart';
import 'package:day_night_login/components/day/sun.dart';
import 'package:day_night_login/components/day/sun_rays.dart';
import 'package:day_night_login/components/input_field.dart';
import 'package:day_night_login/components/night/moon.dart';
import 'package:day_night_login/components/night/moon_rays.dart';
import 'package:day_night_login/components/toggle_button.dart';
import 'package:day_night_login/enums/mode.dart';
import 'package:day_night_login/models/login_theme.dart';
import 'package:day_night_login/utils/cached_images.dart';
import 'package:day_night_login/utils/viewport_size.dart';
import 'package:flutter/material.dart';
class Login extends StatefulWidget {
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> with SingleTickerProviderStateMixin {
AnimationController _animationController;
LoginTheme day;
LoginTheme night;
Mode _activeMode = Mode.day;
@override
void initState() {
_animationController = AnimationController(
vsync: this,
duration: const Duration(
milliseconds: 1000,
),
);
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
_animationController.forward(from: 0.0);
}); // wait for all the widget to render
initializeTheme(); //initializing theme for day and night
super.initState();
}
@override
void didChangeDependencies() {
cacheImages();
super.didChangeDependencies();
}
cacheImages() {
CachedImages.imageAssets.forEach((asset) {
precacheImage(asset, context);
});
}
initializeTheme() {
day = LoginTheme(
title: 'Good Morning,',
backgroundGradient: [
const Color(0xFF8C2480),
const Color(0xFFCE587D),
const Color(0xFFFF9485),
const Color(0xFFFF9D80),
// const Color(0xFFFFBD73),
],
landscape: CachedImages.imageAssets[0],
circle: Sun(
controller: _animationController,
),
rays: SunRays(
controller: _animationController,
),
);
night = LoginTheme(
title: 'Good Night,',
backgroundGradient: [
const Color(0xFF0D1441),
const Color(0xFF283584),
const Color(0xFF6384B2),
const Color(0xFF6486B7),
],
landscape: CachedImages.imageAssets[1],
circle: Moon(
controller: _animationController,
),
rays: MoonRays(
controller: _animationController,
),
);
}
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
ViewportSize.getSize(context);
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: _activeMode == Mode.day
? day.backgroundGradient
: night.backgroundGradient,
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Stack(
alignment: Alignment.center,
children: [
Positioned(
width: height * 0.8,
height: height * 0.8,
bottom: _activeMode == Mode.day ? -300 : -50,
child: _activeMode == Mode.day ? day.rays : night.rays,
),
Positioned(
bottom: _activeMode == Mode.day ? -160 : -80,
child: _activeMode == Mode.day ? day.circle : night.circle,
),
Positioned.fill(
child: Image(
image:
_activeMode == Mode.day ? day.landscape : night.landscape,
fit: BoxFit.fill,
),
),
Positioned(
top: height * 0.1,
left: width * 0.07,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ToggleButton(
startText: 'Morning Login',
endText: 'Night Login',
tapCallback: (index) {
setState(() {
_activeMode = index == 0 ? Mode.day : Mode.night;
_animationController.forward(from: 0.0);
});
},
),
buildText(
text: _activeMode == Mode.day ? day.title : night.title,
padding: EdgeInsets.only(top: height * 0.04),
fontSize: width * 0.09,
fontFamily: 'YesevaOne',
),
buildText(
fontSize: width * 0.04,
padding: EdgeInsets.only(
top: height * 0.02,
),
text: 'Enter your informations below',
),
buildText(
text: 'Email Address',
padding: EdgeInsets.only(
top: height * 0.04, bottom: height * 0.015),
fontSize: width * 0.04,
),
InputField(
hintText: 'Enter your email',
),
buildText(
text: 'Password',
padding: EdgeInsets.only(
top: height * 0.03,
bottom: height * 0.015,
),
fontSize: width * 0.04,
),
InputField(
hintText: 'Your password',
),
const ArrowButton(),
],
),
),
],
),
),
);
}
Padding buildText(
{double fontSize, EdgeInsets padding, String text, String fontFamily}) {
return Padding(
padding: padding,
child: Text(
text,
style: TextStyle(
color: const Color(0xFFFFFFFF),
fontSize: fontSize,
fontFamily: fontFamily ?? '',
),
),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/components/toggle_button.dart | import 'package:day_night_login/utils/viewport_size.dart';
import 'package:flutter/material.dart';
class ToggleButton extends StatefulWidget {
final String startText;
final String endText;
final ValueChanged tapCallback;
const ToggleButton({
Key key,
this.startText,
this.endText,
this.tapCallback,
}) : super(key: key);
@override
_ToggleButtonState createState() => _ToggleButtonState();
}
class _ToggleButtonState extends State<ToggleButton> {
int _activeIndex = 0;
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Stack(
children: [
GestureDetector(
onTap: () {
setState(() {
_activeIndex = _activeIndex == 0 ? 1 : 0;
});
widget.tapCallback(_activeIndex);
},
child: Container(
width: width * 0.7,
height: height * 0.06,
decoration: ShapeDecoration(
color: const Color(0x33FFFFFF),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(width * 0.036),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
buildText(
text: widget.startText,
color: const Color(0xFFFFFFFF),
),
buildText(
text: widget.endText,
color: const Color(0xFFFFFFFF),
),
],
),
),
),
AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeOutCirc,
width: width * 0.7,
alignment:
_activeIndex == 0 ? Alignment.centerLeft : Alignment.centerRight,
child: Container(
alignment: Alignment.center,
width: width * 0.35,
height: height * 0.06,
decoration: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(width * 0.036),
),
color: const Color(0xFFFFFFFF),
),
child: buildText(
text: _activeIndex == 0 ? widget.startText : widget.endText,
),
),
),
],
);
}
Text buildText({String text, Color color = const Color(0xFF000000)}) {
return Text(
text,
style: TextStyle(
fontSize: ViewportSize.width * 0.04,
color: color,
fontWeight: FontWeight.bold,
fontFamily: 'Varela',
),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/components/input_field.dart | import 'package:day_night_login/utils/viewport_size.dart';
import 'package:flutter/material.dart';
class InputField extends StatelessWidget {
const InputField({
Key key,
@required this.hintText,
}) : super(key: key);
final String hintText;
@override
Widget build(BuildContext context) {
return Container(
width: ViewportSize.width * 0.85,
alignment: Alignment.center,
child: Theme(
data: ThemeData(
primaryColor: const Color(0x55000000),
),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(ViewportSize.width * 0.025),
),
hintText: hintText,
hintStyle: TextStyle(
color: const Color(0xFFFFFFFF),
),
fillColor: const Color(0x33000000),
filled: true,
),
),
),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/components/arrow_button.dart | import 'package:day_night_login/utils/custom_icons_icons.dart';
import 'package:day_night_login/utils/viewport_size.dart';
import 'package:flutter/widgets.dart';
class ArrowButton extends StatelessWidget {
const ArrowButton({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: ViewportSize.width - ViewportSize.width * 0.15,
margin: EdgeInsets.only(
top: ViewportSize.height * 0.02,
),
alignment: Alignment.centerRight,
child: Container(
width: ViewportSize.width * 0.155,
height: ViewportSize.width * 0.155,
decoration: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: const Color(0xFFFFFFFF),
shadows: [
BoxShadow(
color: const Color(0x55000000),
blurRadius: ViewportSize.width * 0.02,
offset: Offset(3, 3),
),
],
),
child: Icon(CustomIcons.right_arrow),
),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/components/gradient_circle.dart | import 'package:flutter/material.dart';
class GradientCircle extends StatelessWidget {
const GradientCircle({Key key, @required this.width, this.child, this.stops})
: super(key: key);
final double width;
final Widget child;
final List<double> stops;
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
width: width,
height: width,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [
const Color(0x00FFFFFF),
const Color(0x44FFFFFF),
],
stops: stops,
),
),
child: child,
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib/components | mirrored_repositories/day_night_login/lib/components/night/moon_rays.dart | import 'package:flutter/widgets.dart';
class MoonRays extends AnimatedWidget {
MoonRays({@required this.controller}) : super(listenable: controller);
final AnimationController controller;
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: controller.drive(Tween<double>(begin: 0.00, end: 1.0)),
child: Transform.translate(
offset: controller
.drive(
Tween<Offset>(
begin: Offset(0, 0),
end: Offset(0, -100),
),
)
.value,
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [
const Color(0x666384B2),
const Color(0x006486B7),
],
stops: [
0.5,
1.0,
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib/components | mirrored_repositories/day_night_login/lib/components/night/moon.dart | import 'package:day_night_login/components/gradient_circle.dart';
import 'package:day_night_login/utils/viewport_size.dart';
import 'package:flutter/widgets.dart';
class Moon extends AnimatedWidget {
Moon({@required this.controller}) : super(listenable: controller);
final AnimationController controller;
@override
Widget build(BuildContext context) {
return Transform.translate(
offset: controller
.drive(
Tween<Offset>(
begin: Offset(0, 0),
end: Offset(0, -110),
).chain(
CurveTween(curve: Curves.easeInOut),
),
)
.value,
child: GradientCircle(
width: ViewportSize.width * 0.67,
stops: [
0.8,
1,
],
child: GradientCircle(
width: ViewportSize.width * 0.54,
stops: [
0.75,
1,
],
child: GradientCircle(
width: ViewportSize.width * 0.42,
stops: [
0.7,
1,
],
child: Image.asset(
'assets/images/moon.png',
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib/components | mirrored_repositories/day_night_login/lib/components/day/sun_rays.dart | import 'package:flutter/widgets.dart';
class SunRays extends AnimatedWidget {
SunRays({this.controller}) : super(listenable: controller);
final AnimationController controller;
@override
Widget build(BuildContext context) {
return Transform.translate(
offset: controller
.drive(
Tween<Offset>(
begin: Offset(0, 0),
end: Offset(0, -150),
),
)
.value,
child: FadeTransition(
opacity: controller,
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [
const Color(0xFFf9c87e),
const Color(0xEEf4aa85),
const Color(0x00f4aa85),
],
stops: [0.3, 0.55, 1],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib/components | mirrored_repositories/day_night_login/lib/components/day/sun.dart | import 'package:day_night_login/components/gradient_circle.dart';
import 'package:day_night_login/utils/viewport_size.dart';
import 'package:flutter/widgets.dart';
class Sun extends AnimatedWidget {
Sun({this.controller}) : super(listenable: controller);
final AnimationController controller;
@override
Widget build(BuildContext context) {
return Transform.translate(
offset: controller
.drive(
Tween<Offset>(
begin: Offset(0, 0),
end: Offset(0, -80),
).chain(
CurveTween(curve: Curves.easeInOut),
),
)
.value,
child: Stack(
alignment: Alignment.center,
children: [
GradientCircle(
width: ViewportSize.width * 0.9,
stops: [
0.88,
1,
],
child: GradientCircle(
width: ViewportSize.width * 0.7,
stops: [0.8, 1],
child: GradientCircle(
width: ViewportSize.width * 0.5,
stops: [0.6, 1],
child: Container(
width: ViewportSize.width * 0.3,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: const Color(0xFFFFFFFF),
),
),
),
),
),
Container(
width: ViewportSize.width * 0.5,
height: ViewportSize.height * 0.5,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [
const Color(0xFFfad9a5),
const Color(0x00fad9a5),
],
stops: [0.3, 1],
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/models/login_theme.dart | import 'package:flutter/widgets.dart';
class LoginTheme {
final String title;
final AssetImage landscape;
final List<Color> backgroundGradient;
final Widget circle;
final Widget rays;
LoginTheme(
{this.circle,
this.backgroundGradient,
this.landscape,
this.title,
this.rays});
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/enums/mode.dart | enum Mode {
day,
night,
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/utils/cached_images.dart | import 'package:flutter/material.dart';
class CachedImages {
static const List<AssetImage> imageAssets = [
const AssetImage('assets/images/day.png'),
const AssetImage('assets/images/night.png'),
];
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/utils/custom_icons_icons.dart | /// Flutter icons CustomIcons
/// Copyright (C) 2020 by original authors @ fluttericon.com, fontello.com
/// This font was generated by FlutterIcon.com, which is derived from Fontello.
///
/// To use this font, place it in your fonts/ directory and include the
/// following in your pubspec.yaml
///
/// flutter:
/// fonts:
/// - family: CustomIcons
/// fonts:
/// - asset: fonts/CustomIcons.ttf
///
///
///
import 'package:flutter/widgets.dart';
class CustomIcons {
CustomIcons._();
static const _kFontFam = 'CustomIcons';
static const _kFontPkg = null;
static const IconData right_arrow = IconData(0xe800, fontFamily: _kFontFam, fontPackage: _kFontPkg);
}
| 0 |
mirrored_repositories/day_night_login/lib | mirrored_repositories/day_night_login/lib/utils/viewport_size.dart | import 'package:flutter/widgets.dart';
class ViewportSize {
static double height;
static double width;
static getSize(BuildContext context) {
height = MediaQuery.of(context).size.height;
width = MediaQuery.of(context).size.width;
}
}
| 0 |
mirrored_repositories/day_night_login | mirrored_repositories/day_night_login/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:day_night_login/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Insta-Metrics-Prototype | mirrored_repositories/Insta-Metrics-Prototype/lib/constants.dart |
import 'package:flutter/material.dart';
const kSendButtonTextStyle = TextStyle(
color: Colors.lightBlueAccent,
fontWeight: FontWeight.bold,
fontSize: 18.0,
);
const kMessageTextFieldDecoration = InputDecoration(
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
hintText: 'Type your message here...',
border: InputBorder.none,
);
const kMessageContainerDecoration = BoxDecoration(
border: Border(
top: BorderSide(color: Colors.lightBlueAccent, width: 2.0),
),
);
const kTextFieldDecoration = InputDecoration(
hintText: 'Enter a value',
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
); | 0 |
mirrored_repositories/Insta-Metrics-Prototype | mirrored_repositories/Insta-Metrics-Prototype/lib/Observer.dart |
import 'dart:async';
import 'package:flutter/material.dart';
class Observer<T> extends StatelessWidget {
@required
final Stream<T> stream;
@required
final Function onSuccess;
final Function onError;
final Function onWaiting;
const Observer({this.onError, this.onSuccess, this.stream, this.onWaiting});
Function get _defaultOnWaiting =>
(context) => Center(child: CircularProgressIndicator());
Function get _defaultOnError => (context, error) => Text(error);
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: stream,
builder: (context, AsyncSnapshot<T> snapshot) {
if (snapshot.hasError) {
return (onError != null)
? onError(context, snapshot.error)
: _defaultOnError(context, snapshot.error);
}
if (snapshot.hasData) {
T data = snapshot.data;
return onSuccess(context, data);
} else {
return (onWaiting != null)
? onWaiting(context)
: _defaultOnWaiting(context);
}
},
);
}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype | mirrored_repositories/Insta-Metrics-Prototype/lib/main.dart | import 'package:flutter/material.dart';
import 'package:insta_metrics/Observer.dart';
import 'package:insta_metrics/models/InstagramViewModel.dart';
import 'package:insta_metrics/repositories/InstagramRepository.dart';
import 'package:insta_metrics/screens/home/filters_screen.dart';
import 'package:insta_metrics/screens/home/post_details_screen.dart';
import 'package:insta_metrics/screens/wellcome_screen.dart';
import 'package:insta_metrics/screens/home/home_screen.dart';
import 'package:provider/provider.dart';
void main() async {
final instagramViewModel = new InstagramViewModel(repo : InstagramRepository());
runApp(
MultiProvider(
providers : [
ChangeNotifierProvider<InstagramViewModel>.value(value: instagramViewModel),
],
child : InstaMetrics()
)
);
}
class InstaMetrics extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home : WelcomeScreen(),
routes: {
HomeScreen.id: (context) => HomeScreen(),
WelcomeScreen.id: (context) => WelcomeScreen(),
PostDetails.id : (context) => PostDetails(),
FilterScreen.id : (context) => FilterScreen()
},
);
}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib | mirrored_repositories/Insta-Metrics-Prototype/lib/components/rounded_button.dart | import 'package:flutter/material.dart';
class RoundedButton extends StatelessWidget {
RoundedButton({this.title, this.colour, @required this.onPressed});
final Color colour;
final String title;
final Function onPressed;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
elevation: 5.0,
color: colour,
borderRadius: BorderRadius.circular(30.0),
child: MaterialButton(
onPressed: onPressed,
minWidth: 200.0,
height: 42.0,
child: Text(
title,
style: TextStyle(
color: Colors.white,
),
),
),
),
);
}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib | mirrored_repositories/Insta-Metrics-Prototype/lib/models/Post.dart | class Post{
final String type;
final DateTime post_date;
final String media_url;
final String media_preview;
final String caption;
final int likes;
final int comments;
final bool is_video;
Post({this.type, this.media_url, this.media_preview, this.caption, this.likes,
this.comments,this.is_video,this.post_date});
String toString(){
return "Post{type: $type, likes : $likes, comments: $comments,is_video: $is_video}";
}
factory Post.fromJson(Map<String,dynamic> json){
var caption = 'No caption';
if(json['edge_media_to_caption'] != null){
if(json['edge_media_to_caption']['edges'] != null && json['edge_media_to_caption']['edges'].length > 0 ){
caption = json['edge_media_to_caption']['edges'][0]['node']['text'];
}
}
return Post(
type: json['__typename'],
media_url: json['display_url'],
media_preview: json['media_preview'],
likes: json['edge_media_preview_like'] != null ? json['edge_media_preview_like']['count'] : 0,
comments: json['edge_media_to_comment'] != null ? json['edge_media_to_comment']['count'] : 0,
is_video: json['is_video'] == 1,
caption: caption,
post_date: DateTime.fromMillisecondsSinceEpoch(json['taken_at_timestamp'] * 1000)
);
}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib | mirrored_repositories/Insta-Metrics-Prototype/lib/models/InstagramViewModel.dart | import 'package:flutter/material.dart';
import 'package:insta_metrics/contracts/InstagramInterface.dart';
import 'package:insta_metrics/models/providers/Filters.dart';
import 'package:insta_metrics/repositories/InstagramRepository.dart';
import 'Post.dart';
import 'filters/DateFilter.dart';
import 'filters/NumberFilter.dart';
class InstagramViewModel
extends ChangeNotifier
with Filters
implements InstagramInterface
{
final InstagramRepository repo;
String userName;
String fullName;
String bio;
String external_url;
String profile_url;
int followers;
int following;
List<Post> posts;
int total_posts;
int likes_total;
int comments_total;
InstagramViewModel({this.repo});
searchPosts(String username) async{
var data = await this.repo.searchPosts(username);
if(data != null){
print(data);
this._setupUserData(data[0],data[1]);
return true;
}
return false;
}
_setupUserData(Map<String,dynamic> json,List<dynamic> postsList){
final int postQty = json['edge_owner_to_timeline_media']['count'];
List<Post> posts = [];
postsList.forEach((e) {
posts.add(Post.fromJson(e));
});
var likes_total = posts.map((e) => e.likes).reduce((a, b) => a + b);
print(likes_total);
var comments_total = posts.map((e) => e.comments).reduce((a, b) => a + b);
this.userName = json['username'];
this.fullName = json['full_name'];
this.bio = json['biography'];
this.external_url= json['external_url'] ?? null;
this.total_posts = postQty;
this.posts= posts;
this.followers= json['edge_followed_by']['count'];
this.following= json['edge_follow']['count'];
this.profile_url= json['profile_pic_url'];
this.likes_total = likes_total;
this.comments_total = comments_total;
}
getUserPosts(){
return this.posts;
}
filterPosts(
DateFilter filterByDate,
NumberFilter filterByLikes,
NumberFilter filterByComments,
List<String> filterByHashTags,
String order,
int orderBy,
bool dateFilter,
bool likesFilter,
bool commentsFilter){
this.filterByDate = filterByDate;
this.filterByLikes = filterByLikes;
this.filterByComments = filterByComments;
this.filterByHashTags = filterByHashTags;
this.order = order;
this.orderBy = orderBy;
this.dateFilter = dateFilter;
this.likesFilter = likesFilter;
this.commentsFilter = commentsFilter;
return this.posts;
}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib/models | mirrored_repositories/Insta-Metrics-Prototype/lib/models/filters/DateFilter.dart | class DateFilter{
final DateTime startDate;
final DateTime endDate;
DateFilter({this.startDate,this.endDate});
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib/models | mirrored_repositories/Insta-Metrics-Prototype/lib/models/filters/NumberFilter.dart | class NumberFilter{
final int maxValue;
final int minValue;
NumberFilter({this.maxValue,this.minValue});
String toString(){
return "NumberFilter :{maxValue : $maxValue, minValue : $minValue }";
}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib/models | mirrored_repositories/Insta-Metrics-Prototype/lib/models/providers/Filters.dart | import 'package:insta_metrics/models/filters/DateFilter.dart';
import 'package:insta_metrics/models/filters/NumberFilter.dart';
import '../Post.dart';
class Filters{
DateFilter filterByDate;
NumberFilter filterByLikes;
NumberFilter filterByComments;
List<String> filterByHashTags;
String order;
int orderBy;
bool dateFilter;
bool likesFilter;
bool commentsFilter;
List<Post> getPosts(List<Post> posts){
if(this.dateFilter == true){
posts = this.getPostsFilterByDate(posts);
}
if(this.likesFilter == true){
posts = this.getPostsFilterByLikes(posts);
}
if(this.commentsFilter == true){
posts = this.getPostsFilterByComments(posts);
print('here');
}
switch(this.orderBy){
case 1:
posts = this.getPostsOrderByLikes(posts,order:this.order);
break;
case 2:
posts = this.getPostsOrderByComments(posts,order:this.order);
break;
case 3:
posts = this.getPostsOrderByDate(posts,order:this.order);
break;
}
return posts;
}
List<Post> getPostsWithHashTag(hashtag,List<Post> posts){
return posts.where((post) => post.caption.replaceAll('\n',' ').contains(hashtag)).toList();
}
List<Post> getPostsFilterByDate(List<Post> posts){
return posts.where((post) => post.post_date.isAfter(this.filterByDate.startDate) && post.post_date.isBefore(this.filterByDate.endDate)).toList();
}
List<Post> getPostsFilterByLikes(List<Post> posts){
return posts.where((post){
return post.likes >= this.filterByLikes.minValue && post.likes <= this.filterByLikes.maxValue;
}).toList();
}
List<Post> getPostsFilterByComments(List<Post> posts){
return posts.where((post) {
print(post);
print("${this.filterByComments.minValue} ${this.filterByComments.maxValue}");
print(post.comments >= this.filterByComments.minValue && post.comments <= this.filterByComments.maxValue);
return post.comments >= this.filterByComments.minValue &&
post.comments <= this.filterByComments.maxValue;
}).toList();
}
List<Post> getPostsOrderByDate(List<Post> posts,{order = 'asc'}){
if(order == 'asc') {
posts.sort((a,b) => a.post_date.isBefore(b.post_date) ? 1 : -1 );
}else{
posts.sort((a,b) => a.post_date.isAfter(b.post_date) ? 1 : -1);
}
return posts;
}
List<Post> getPostsOrderByLikes(List<Post> posts,{order = 'asc'}){
if(order == 'asc') {
posts.sort((a,b) => a.likes >= b.likes ? 1 : -1 );
}else{
posts.sort((a,b) => a.likes <= b.likes ? 1 : -1);
}
return posts;
}
List<Post> getPostsOrderByComments(List<Post> posts,{order = 'asc'}){
if(order == 'asc') {
posts.sort((a,b) => a.comments >= b.comments ? 1 : -1 );
}else{
posts.sort((a,b) => a.comments <= b.comments ? 1 : -1);
}
return posts;
}
}
| 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib | mirrored_repositories/Insta-Metrics-Prototype/lib/repositories/InstagramRepository.dart | import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:insta_metrics/contracts/InstagramInterface.dart';
import 'package:insta_metrics/models/Post.dart';
class InstagramResponse{
final Map<String,dynamic> jsonData;
final List<Post> posts;
InstagramResponse({this.jsonData, this.posts});
}
class InstagramRepository implements InstagramInterface {
InstagramRepository();
searchPosts(String username) async {
try {
final response = await http.get("https://www.instagram.com/$username/?__a=1");
if (response.statusCode == 200) {
String nextPage;
var jsonData = json.decode(response.body);
var posts = [];
jsonData = jsonData['graphql']['user'];
if (!jsonData['edge_owner_to_timeline_media']['page_info']['has_next_page'] == true) {
for (var post in jsonData['edge_owner_to_timeline_media']['edges']) {
posts.add(post['node']);
}
} else {
nextPage = jsonData['edge_owner_to_timeline_media']['page_info']
['end_cursor'];
http.Response responsePosts;
while (nextPage != null) {
responsePosts = await http.get(
"https://www.instagram.com/graphql/query/?query_id=17888483320059182&id=" +
jsonData['id'] +
"&first=50&after=" +
nextPage);
var jsonPostData = json.decode(responsePosts.body);
if (jsonPostData['status'] == "ok") {
jsonPostData =
jsonPostData['data']['user']['edge_owner_to_timeline_media'];
if (jsonPostData['page_info']['has_next_page'] == true) {
nextPage = jsonPostData['page_info']['end_cursor'];
} else {
nextPage = null;
}
for (var post in jsonPostData['edges']) {
posts.add(post['node']);
}
}
}
}
var ret = [];
ret.add(jsonData);
ret.add(posts);
return ret;
}
return null;
} catch (e) {
return null;
}
}
}
| 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib | mirrored_repositories/Insta-Metrics-Prototype/lib/screens/wellcome_screen.dart |
import 'package:flutter/material.dart';
import 'package:insta_metrics/models/InstagramViewModel.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:insta_metrics/components/rounded_button.dart';
import 'package:provider/provider.dart';
import 'home/home_screen.dart';
class WelcomeScreen extends StatefulWidget {
static const String id = 'welcome_screen';
@override
_WelcomeScreenState createState() => _WelcomeScreenState();
}
class _WelcomeScreenState extends State<WelcomeScreen> {
bool showSpinner = false;
String userName;
TextEditingController _inputController = TextEditingController();
updateUserName(){
setState(() {
this.userName = _inputController.text;
});
}
@override
Widget build(BuildContext context) {
final instagram = Provider.of<InstagramViewModel>(context);
return Scaffold(
backgroundColor: Colors.white,
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text('Insta metrics ',
style: TextStyle(
fontSize: 45.0,
fontWeight: FontWeight.w900,
),
),
SizedBox(
height: 48.0,
),
TextField(
controller: _inputController,
decoration: InputDecoration(
focusColor: Colors.white,
suffixIcon: Icon(
Icons.search,
color: Colors.indigoAccent,
),
hintText: "Instagram username",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide(color: Colors.blueGrey, width: 1),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
borderSide: BorderSide(color: Colors.white, width: 1),
),
),
style: TextStyle(fontSize: 16.0, color: Colors.indigo),
onChanged: (query) => updateUserName,
),
SizedBox(
height: 24.0,
),
RoundedButton(
title: 'Search',
colour: Colors.lightBlueAccent,
onPressed: () async {
setState(() {
showSpinner = true;
});
var response = await instagram.searchPosts(_inputController.text);
if(response == true) {
Navigator.pushNamed(
context,
HomeScreen.id,
);
}
setState(() {
showSpinner = false;
});
},
),
],
),
),
),
);
}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib/screens | mirrored_repositories/Insta-Metrics-Prototype/lib/screens/home/home_screen.dart | import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:insta_metrics/models/InstagramViewModel.dart';
import 'package:insta_metrics/models/Post.dart';
import 'package:insta_metrics/screens/home/filters_screen.dart';
import 'package:insta_metrics/screens/home/post_details_screen.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
_SliverAppBarDelegate(this._card, this._height);
final Widget _card;
final double _height;
@override
double get minExtent => _height;
@override
double get maxExtent => _height;
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return new Container(
child: _card,
);
}
@override
bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
return true;
}
}
class HomeScreen extends StatelessWidget {
static const String id = 'login_screen';
RangeValues filterLikes;
RangeValues filterComments;
bool _likesFilter = false;
bool _commentsFilter = false;
bool _dateFilter = false;
double _height = 60;
ScrollController controller = ScrollController();
@override
Widget build(BuildContext context) {
final instagram = Provider.of<InstagramViewModel>(context);
return Scaffold(
body: Container(
width: double.infinity,
height: double.infinity,
child: SafeArea(
child: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
elevation: 0,
title: Text(
'Insta Metrics',
style: TextStyle(color: Colors.grey[500]),
),
backgroundColor: Colors.white,
floating: false,
actions: <Widget>[
GestureDetector(
onTap: () {},
child: Icon(Icons.menu, color: Colors.grey[500]))
],
centerTitle: true,
expandedHeight: 40,
primary: false,
),
SliverPersistentHeader(
floating: false,
delegate: _SliverAppBarDelegate(
Card(
margin: EdgeInsets.all(0),
elevation: 0,
child: buildProfileCard(context, instagram)),
400),
pinned: false,
),
SliverPersistentHeader(
delegate: _SliverAppBarDelegate(buildMetricsCard(context,instagram),60),
pinned: true,
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
instagram.getUserPosts().sort( (a,b) => a.post_date.isBefore(b.post_date) == true ? 1 : -1 );
return Container(
child: buildPostCard(context,instagram.getUserPosts().elementAt(index), instagram,index),
margin: EdgeInsets.symmetric(horizontal: 40, vertical: 3),
);
},
childCount: instagram.getUserPosts().length,
),
)
],
),
),),
);
}
Card buildProfileInfoCard(InstagramViewModel user) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
elevation: 0,
margin: EdgeInsets.symmetric(horizontal: 5),
shadowColor: Colors.blueGrey,
child: Container(
child: Center(
child: Column(
children: <Widget>[
Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(children: <Widget>[
Text('Followers',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.followers),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
Column(children: <Widget>[
Text('Following',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.following),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
]),
),
SizedBox(
height: 20,
),
Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(children: <Widget>[
Text('Likes',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.likes_total),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
Column(children: <Widget>[
Text('Comments',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.likes_total),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
Column(children: <Widget>[
Text('Posts',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.total_posts),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
]),
),
SizedBox(
height: 60,
),
Center(
child: Stack(children: <Widget>[
Text(
'Posts',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Colors.grey[600]),
)
])),
GestureDetector(onTap: (){}, child: Text("hashtag")),
],
),
),
),
);
}
Card buildMetricsCard(context,InstagramViewModel user) {
return Card(
margin: EdgeInsets.symmetric(vertical: 0),
elevation: 0,
shadowColor: Colors.blueGrey,
child: AnimatedContainer(
duration: Duration(seconds: 2),
height: _height,
decoration: BoxDecoration(color: Colors.transparent),
child: Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Column(
children: <Widget>[
Center(
child: Stack(children: <Widget>[
Text(
'Posts',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Colors.grey[600]),
)
])),
GestureDetector(onTap: (){}, child: Text("hashtag")),
],
),
GestureDetector(
onTap: () {
showModalBottomSheet(
context: context,
useRootNavigator: true,
isScrollControlled: true,
builder: (BuildContext context){
if(filterLikes == null){
filterLikes = RangeValues(
user.getPostsOrderByLikes(user.posts).first.likes.toDouble(),
user.getPostsOrderByLikes(user.posts).last.likes.toDouble()
);
}
if(filterComments == null){
filterComments = RangeValues(
user.getPostsOrderByComments(user.posts).first.comments.toDouble(),
user.getPostsOrderByComments(user.posts).last.comments.toDouble()
);
}
return StatefulBuilder(
builder: (context,setState){
return Container(
height: MediaQuery.of(context).size.height*0.50,
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
alignment: WrapAlignment.center,
spacing: 10,
children: <Widget>[
ListTile(
leading: Icon(Icons.filter_list),
title: Text('Filter By',style: TextStyle(
fontSize: 20,
color: Colors.grey[500],
),),
onTap: () => {}
),
Column(
children: <Widget>[
Text(this.formatNumber(filterLikes.start.toInt())),
RangeSlider(
divisions: user.getPostsOrderByComments(user.posts).last.likes,
values: filterLikes,
min : user.getPostsOrderByLikes(user.posts).first.likes.toDouble(),
max : user.getPostsOrderByLikes(user.posts).last.likes.toDouble(),
onChanged: (value){
setState(() {
_likesFilter = true;
filterLikes = value;
});
}),
Text(this.formatNumber(filterLikes.end.toInt())),
],
),
SizedBox(
height: 20,
),
Column(
children: <Widget>[
Text(this.formatNumber(filterComments.start.toInt())),
RangeSlider(
divisions: user.getPostsOrderByComments(user.posts).last.comments,
values: filterComments,
min : user.getPostsOrderByComments(user.posts).first.comments.toDouble(),
max : user.getPostsOrderByComments(user.posts).last.comments.toDouble(),
onChanged: (value){
setState(() {
_commentsFilter = true;
filterComments = value;
});
}),
Text(this.formatNumber(filterComments.end.toInt())),
],
),
ListTile(
leading:Icon(Icons.sort),
title: Text('Sort by',style: TextStyle(
fontSize: 20,
color: Colors.grey[500],
),),
onTap: () => {},
),
FlatButton(onPressed: (){
setState(() {
});
Navigator.pushNamed(
context,
FilterScreen.id,
);
},
child: Text('Ok')
)
],
),
);},
);},
);
},
child: Icon(Icons.filter_list, size: 30, color: Colors.grey[500],)),
],
),
),
),
);
}
String formatNumber(number){
return NumberFormat.compact().format(number).toString();
}
GestureDetector buildPostCard(context,Post post, InstagramViewModel user,index) {
String formatDate(int date) =>
date < 10 ? '0' + date.toString() : date.toString();
String postDate(Post post) =>
'${formatDate(post.post_date.day)}/${formatDate(post.post_date.month)}/${formatDate(post.post_date.year)} - ${formatDate(post.post_date.hour)}:${formatDate(post.post_date.minute)}';
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, PostDetails.id, arguments: post);
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
shadowColor: Colors.blueGrey,
elevation: 0,
child: SizedBox(
child: Center(
child: Container(
height: 260,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.grey[200],
),
child: Stack(children: <Widget>[
Hero(
tag: index,
child: Container(
height: 210,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
image: DecorationImage(
image: NetworkImage(post.media_url),
fit: BoxFit.cover),
color: Colors.transparent,
)),
),
Container(
width: MediaQuery.of(context).size.width,
height: 210,
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 1, sigmaY: 1),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.black.withOpacity(0.6),
),
),
),
),
Positioned(
width: MediaQuery.of(context).size.width * 0.80,
top: 20,
left: 20,
child: Center(
child: Text(
"Post in: " + postDate(post),
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w300,
fontSize: 15),
),
),
),
Positioned(
top: 120,
width: MediaQuery.of(context).size.width * 0.80,
height: 60,
child: Container(
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Tooltip(
preferBelow: false,
message:
post.likes < 10 ? 'Post with Low Likes ' : '',
child: Icon(
Icons.favorite,
color: post.likes < 10
? Colors.orange[500]
: Colors.red[500],
size: 30,
)),
Text(
this.formatNumber(post.likes),
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500),
),
SizedBox(
width: 150,
),
Icon(
Icons.chat_bubble_outline,
color: Colors.white,
size: 30,
),
Text(
post.comments.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500),
)
],
),
)),
Positioned(
top: 155,
child: Container(
margin: EdgeInsets.only(left: 4, right: 4),
height: 60,
width: MediaQuery.of(context).size.width * 0.80,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
for (var text
in post.caption.replaceAll('\n', ' ').split(' '))
if (text.startsWith('#'))
Tooltip(
message: text,
child: GestureDetector(
onTap: () {
},
child: Chip(
backgroundColor: Colors.grey[200],
elevation: 0,
label: Text(text),
),
),
)
],
),
),
)
]),
),
),
),
),
);
}
Stack buildProfileCard(BuildContext context, InstagramViewModel user) {
return Stack(
children: <Widget>[
Positioned(
height: 100,
top: 10,
width: MediaQuery.of(context).size.width,
child: Center(
child: Container(
height: 100,
width: 100,
margin: EdgeInsets.only(right: 5, left: 4),
child: CircleAvatar(
backgroundImage: NetworkImage("${user.profile_url}"),
backgroundColor: Colors.grey,
),
),
)),
Positioned(
top: 60,
width: MediaQuery.of(context).size.width,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: 200,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
user.fullName,
style: TextStyle(fontSize: 25),
),
SizedBox(
height: 5,
),
Text(
'@' + user.userName,
style:
TextStyle(color: Colors.grey[500], fontSize: 20),
),
],
),
),
]),
),
),
Positioned(
top: 200,
width: MediaQuery.of(context).size.width,
child: Container(
child: Center(
child: Column(
children: <Widget>[
Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(children: <Widget>[
Text('Followers',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.followers),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
Column(children: <Widget>[
Text('Following',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.following),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
]),
),
SizedBox(
height: 20,
),
Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(children: <Widget>[
Text('Likes',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.likes_total),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
Column(children: <Widget>[
Text('Comments',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.comments_total),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
Column(children: <Widget>[
Text('Posts',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(user.total_posts),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
]),
),
SizedBox(
height: 30,
),
],
),
),
),
)
],
);
}
}
| 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib/screens | mirrored_repositories/Insta-Metrics-Prototype/lib/screens/home/post_details_screen.dart | import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:insta_metrics/models/Post.dart';
import 'package:intl/intl.dart';
class PostDetails extends StatefulWidget {
static const String id = 'post_details_screen';
PostDetails({Key key}) : super(key: key);
@override
_PostDetailsState createState() {
return _PostDetailsState();
}
}
class _PostDetailsState extends State<PostDetails> {
ScrollController controller = ScrollController();
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
String formatNumber(number){
return NumberFormat.compact().format(number).toString();
}
@override
Widget build(BuildContext context) {
String formatDate(int date) =>
date < 10 ? '0' + date.toString() : date.toString();
String postDate(Post post) =>
'${formatDate(post.post_date.day)}/${formatDate(post.post_date.month)}/${formatDate(post.post_date.year)} - ${formatDate(post.post_date.hour)}:${formatDate(post.post_date.minute)}';
Post post = ModalRoute.of(context).settings.arguments;
if (post == null) {
Navigator.pop(context);
}
return Scaffold(
//backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text(
"Post in: "+postDate(post),
style: TextStyle(color: Colors.grey[500]),
),
elevation: 0,
iconTheme: IconThemeData(color: Colors.grey[500],size: 30),
backgroundColor: Colors.white,
centerTitle: true,
),
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Hero(
tag: post.hashCode,
child: Container(
decoration: BoxDecoration(
color: Colors.transparent,
image: DecorationImage(
image: NetworkImage(post.media_url), fit: BoxFit.cover)),
height: 400,
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 1, sigmaY: 1),
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.5),
),
),
Container(
decoration: BoxDecoration(
color: Colors.transparent,
image: DecorationImage(
image: NetworkImage(post.media_url), fit: BoxFit.fitHeight)),
)
],
),
),
),
),
Container(
height: MediaQuery.of(context).size.height - 480,
child: ListView(controller: controller, children: <Widget>[
Container(
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
child: Stack(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width,
child: Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(children: <Widget>[
Text('Likes',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(post.likes),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
Column(children: <Widget>[
Text('Comments',
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
SizedBox(
height: 10,
),
Text(this.formatNumber(post.comments),
style: TextStyle(
color: Colors.grey[700], fontSize: 20)),
]),
]),
),
)
],
),
margin: EdgeInsets.symmetric(horizontal: 4, vertical: 4),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
),
Container(
margin: EdgeInsets.only(left: 4, right: 4),
height: 60,
width: MediaQuery.of(context).size.width*0.80,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
for (var text
in post.caption.replaceAll('\n', ' ').split(' '))
if (text.startsWith('#'))
Tooltip(
message: text,
child: Chip(
label: Text(text),
),
)
],
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.white),
child: Center(child: Text(post.caption)),
margin: EdgeInsets.symmetric(horizontal: 4, vertical: 4),
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
width: MediaQuery.of(context).size.width * 0.80,
)
]),
),
],
),
));
}
}
| 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib/screens | mirrored_repositories/Insta-Metrics-Prototype/lib/screens/home/filters_screen.dart |
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:insta_metrics/models/InstagramViewModel.dart';
import 'package:insta_metrics/models/Post.dart';
import 'package:insta_metrics/models/filters/DateFilter.dart';
import 'package:insta_metrics/models/filters/NumberFilter.dart';
import 'package:insta_metrics/screens/home/post_details_screen.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
class FilterScreen extends StatelessWidget {
static const String id = 'filter_screen';
RangeValues filterLikes;
RangeValues filterComments;
bool _likesFilter = false;
bool _commentsFilter = false;
bool _dateFilter = false;
ScrollController controller = ScrollController();
@override
Widget build(BuildContext context) {
final instagram = Provider.of<InstagramViewModel>(context);
return Scaffold(
body: Container(
width: double.infinity,
height: double.infinity,
child: SafeArea(
child: CustomScrollView(
slivers: <Widget>[
SliverAppBar(
iconTheme: IconThemeData(color: Colors.grey[500]),
elevation: 0,
title: Text(
instagram.filterByLikes.toString(),
style: TextStyle(color: Colors.grey[500]),
),
backgroundColor: Colors.white,
actions: <Widget>[
GestureDetector(
onTap: () {
showModalBottomSheet(
context: context,
useRootNavigator: true,
isScrollControlled: true,
builder: (BuildContext context){
if(filterLikes == null){
filterLikes = RangeValues(
instagram.filterByLikes.minValue.toDouble(),
instagram.filterByLikes.maxValue.toDouble()
);
}
if(filterComments == null){
filterComments = RangeValues(
instagram.filterByComments.minValue.toDouble(),
instagram.filterByComments.maxValue.toDouble()
);
}
return StatefulBuilder(
builder: (context,setState){
return Container(
height: MediaQuery.of(context).size.height*0.50,
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
alignment: WrapAlignment.center,
spacing: 10,
children: <Widget>[
ListTile(
leading: Icon(Icons.filter_list),
title: Text('Filter By',style: TextStyle(
fontSize: 20,
color: Colors.grey[500],
),),
onTap: () => {}
),
Column(
children: <Widget>[
Text(filterLikes.start.toInt().toString()),
RangeSlider(
values: filterLikes,
min : instagram.getPostsOrderByLikes(instagram.posts).first.likes.toDouble(),
max : instagram.getPostsOrderByLikes(instagram.posts).last.likes.toDouble(),
onChanged: (value){
setState(() {
_likesFilter = true;
filterLikes = value;
});
}),
Text(filterLikes.end.toInt().toString()),
],
),
ListTile(
leading:Icon(Icons.sort),
title: Text('Sort by',style: TextStyle(
fontSize: 20,
color: Colors.grey[500],
),),
onTap: () => {},
),
FlatButton(onPressed: (){
setState(() {
});
instagram.filterPosts(
DateFilter(
startDate: instagram.getPostsOrderByDate(instagram.posts).first.post_date,
endDate: instagram.getPostsOrderByDate(instagram.posts).last.post_date
),
NumberFilter(
maxValue: instagram.getPostsOrderByComments(instagram.posts).first.comments,
minValue: instagram.getPostsOrderByComments(instagram.posts).last.comments
),
NumberFilter(
minValue: filterLikes.start.toInt(),
maxValue: filterLikes.end.toInt()
),
[],
'asc',
2,
_likesFilter,
_commentsFilter,
_dateFilter,
);
},
child: Text('Ok')
)
],
),
);},
);},
);
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(Icons.filter_list, color: Colors.grey[500]),
))
],
centerTitle: true,
expandedHeight: 40,
floating: true,
primary: true,
pinned: true,
),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return Container(
child: buildPostCard(
context, instagram.posts.elementAt(index), instagram,
index),
margin: EdgeInsets.symmetric(horizontal: 40, vertical: 3),
);
},
childCount: instagram.posts.length,
),
)
],
),
),),
);
}
String formatNumber(number){
return NumberFormat.compact().format(number).toString();
}
GestureDetector buildPostCard(context,Post post, InstagramViewModel user,index) {
String formatDate(int date) =>
date < 10 ? '0' + date.toString() : date.toString();
String postDate(Post post) =>
'${formatDate(post.post_date.day)}/${formatDate(post.post_date.month)}/${formatDate(post.post_date.year)} - ${formatDate(post.post_date.hour)}:${formatDate(post.post_date.minute)}';
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, PostDetails.id, arguments: post);
},
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
shadowColor: Colors.blueGrey,
elevation: 0,
child: SizedBox(
child: Center(
child: Container(
height: 260,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.grey[200],
),
child: Stack(children: <Widget>[
Container(
height: 210,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
image: DecorationImage(
image: NetworkImage(post.media_url),
fit: BoxFit.cover),
color: Colors.transparent,
),
),
Container(
width: MediaQuery.of(context).size.width,
height: 210,
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 1, sigmaY: 1),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
color: Colors.black.withOpacity(0.6),
),
),
),
),
Positioned(
width: MediaQuery.of(context).size.width * 0.80,
top: 20,
left: 20,
child: Center(
child: Text(
"Post in: " + postDate(post),
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w300,
fontSize: 15),
),
),
),
Positioned(
top: 120,
width: MediaQuery.of(context).size.width * 0.80,
height: 60,
child: Container(
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Tooltip(
preferBelow: false,
message:
post.likes < 10 ? 'Post with Low Likes ' : '',
child: Icon(
Icons.favorite,
color: post.likes < 10
? Colors.orange[500]
: Colors.red[500],
size: 30,
)),
Text(
this.formatNumber(post.likes),
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500),
),
SizedBox(
width: 150,
),
Icon(
Icons.chat_bubble_outline,
color: Colors.white,
size: 30,
),
Text(
post.comments.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500),
)
],
),
)),
Positioned(
top: 155,
child: Container(
margin: EdgeInsets.only(left: 4, right: 4),
height: 60,
width: MediaQuery.of(context).size.width * 0.80,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
for (var text
in post.caption.replaceAll('\n', ' ').split(' '))
if (text.startsWith('#'))
Tooltip(
message: text,
child: GestureDetector(
onTap: () {
},
child: Chip(
backgroundColor: Colors.grey[200],
elevation: 0,
label: Text(text),
),
),
)
],
),
),
)
]),
),
),
),
),
);
}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype/lib | mirrored_repositories/Insta-Metrics-Prototype/lib/contracts/InstagramInterface.dart | abstract class InstagramInterface{
searchPosts(String username) async {}
} | 0 |
mirrored_repositories/Insta-Metrics-Prototype | mirrored_repositories/Insta-Metrics-Prototype/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:insta_metrics/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(FlashChat());
// 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/pokemon-provider | mirrored_repositories/pokemon-provider/lib/main.dart | import 'package:flutter/material.dart';
import 'package:pokemon/detail_screen.dart';
import 'package:pokemon/models/pokemon_list_model.dart';
import 'package:pokemon/provider/pokemon_detail_provider.dart';
import 'package:pokemon/provider/pokemon_list_provider.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => PokemonListProvider()..getPokemonList(),
),
ChangeNotifierProvider(create: (_) => PokemonDetailProvider()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Pokemon',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Pokemon'),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Result> result = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Consumer<PokemonListProvider>(
builder: (context, value, child) {
if (value.isLoading) {
return const Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
primary: true,
itemCount: value.pokemonList!.results!.length,
itemBuilder: (BuildContext content, int index) {
var result = value.pokemonList!.results;
String pokemonName = result![index]!.name.toString();
String pokemonUrl = result[index]!.url.toString();
return GestureDetector(
onTap: () {
showModalBottomSheet(
context: context,
builder: (context) {
return BottomSheet(
url: pokemonUrl,
);
},
);
},
child: Card(
color: const Color.fromARGB(255, 246, 247, 252),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
elevation: 4,
child: Container(
margin: const EdgeInsets.all(15.0),
padding: const EdgeInsets.all(20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
pokemonName,
)
],
),
),
),
);
},
);
},
),
);
}
}
class BottomSheet extends StatefulWidget {
final String url;
const BottomSheet({super.key, required this.url});
@override
State<BottomSheet> createState() => _BottomSheetState();
}
class _BottomSheetState extends State<BottomSheet> {
@override
Widget build(BuildContext context) {
Provider.of<PokemonListProvider>(context, listen: false).getPokemonList();
return Consumer<PokemonDetailProvider>(
builder: (BuildContext context, value, child) {
if (value.isLoading) {
return const Center(
child: CircularProgressIndicator(),
);
}
return Column(
children: [
Text(value.pokemonDetail!.name),
Image.network(value.pokemonDetail!.sprites.backDefault),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const DetailScreen(),
),
);
},
child: const Text('Show More'),
),
],
);
},
);
}
}
| 0 |
mirrored_repositories/pokemon-provider | mirrored_repositories/pokemon-provider/lib/detail_screen.dart | import 'package:flutter/material.dart';
import 'package:pokemon/provider/pokemon_detail_provider.dart';
import 'package:provider/provider.dart';
class DetailScreen extends StatefulWidget {
const DetailScreen({super.key});
@override
State<DetailScreen> createState() => _DetailScreenState();
}
class _DetailScreenState extends State<DetailScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Detail'),
),
body: Consumer<PokemonDetailProvider>(
builder: (BuildContext context, value, child) {
if (value.isLoading) {
return const Center(
child: CircularProgressIndicator(),
);
}
return Center(
child: Column(
children: [
Text(value.pokemonDetail!.name),
Image.network(value.pokemonDetail!.sprites.backDefault),
],
),
);
},
),
);
}
}
| 0 |
mirrored_repositories/pokemon-provider/lib | mirrored_repositories/pokemon-provider/lib/models/pokemon_detail_model.dart | import 'dart:convert';
PokemonDetailModel pokemonDetailModelFromJson(String str) =>
PokemonDetailModel.fromJson(json.decode(str));
String pokemonDetailModelToJson(PokemonDetailModel data) =>
json.encode(data.toJson());
class PokemonDetailModel {
PokemonDetailModel({
required this.abilities,
required this.baseExperience,
required this.forms,
required this.gameIndices,
required this.height,
required this.heldItems,
required this.id,
required this.isDefault,
required this.locationAreaEncounters,
required this.moves,
required this.name,
required this.order,
required this.pastTypes,
required this.species,
required this.sprites,
required this.stats,
required this.types,
required this.weight,
});
final List<Ability> abilities;
final int baseExperience;
final List<Species> forms;
final List<GameIndex> gameIndices;
final int height;
final List<dynamic> heldItems;
final int id;
final bool isDefault;
final String locationAreaEncounters;
final List<Move> moves;
final String name;
final int order;
final List<dynamic> pastTypes;
final Species species;
final Sprites sprites;
final List<Stat> stats;
final List<Type> types;
final int weight;
factory PokemonDetailModel.fromJson(Map<String, dynamic> json) =>
PokemonDetailModel(
abilities: List<Ability>.from(
json["abilities"].map((x) => Ability.fromJson(x))),
baseExperience: json["base_experience"],
forms:
List<Species>.from(json["forms"].map((x) => Species.fromJson(x))),
gameIndices: List<GameIndex>.from(
json["game_indices"].map((x) => GameIndex.fromJson(x))),
height: json["height"],
heldItems: List<dynamic>.from(json["held_items"].map((x) => x)),
id: json["id"],
isDefault: json["is_default"],
locationAreaEncounters: json["location_area_encounters"],
moves: List<Move>.from(json["moves"].map((x) => Move.fromJson(x))),
name: json["name"],
order: json["order"],
pastTypes: List<dynamic>.from(json["past_types"].map((x) => x)),
species: Species.fromJson(json["species"]),
sprites: Sprites.fromJson(json["sprites"]),
stats: List<Stat>.from(json["stats"].map((x) => Stat.fromJson(x))),
types: List<Type>.from(json["types"].map((x) => Type.fromJson(x))),
weight: json["weight"],
);
Map<String, dynamic> toJson() => {
"abilities": List<dynamic>.from(abilities.map((x) => x.toJson())),
"base_experience": baseExperience,
"forms": List<dynamic>.from(forms.map((x) => x.toJson())),
"game_indices": List<dynamic>.from(gameIndices.map((x) => x.toJson())),
"height": height,
"held_items": List<dynamic>.from(heldItems.map((x) => x)),
"id": id,
"is_default": isDefault,
"location_area_encounters": locationAreaEncounters,
"moves": List<dynamic>.from(moves.map((x) => x.toJson())),
"name": name,
"order": order,
"past_types": List<dynamic>.from(pastTypes.map((x) => x)),
"species": species.toJson(),
"sprites": sprites.toJson(),
"stats": List<dynamic>.from(stats.map((x) => x.toJson())),
"types": List<dynamic>.from(types.map((x) => x.toJson())),
"weight": weight,
};
}
class Ability {
Ability({
required this.ability,
required this.isHidden,
required this.slot,
});
final Species ability;
final bool isHidden;
final int slot;
factory Ability.fromJson(Map<String, dynamic> json) => Ability(
ability: Species.fromJson(json["ability"]),
isHidden: json["is_hidden"],
slot: json["slot"],
);
Map<String, dynamic> toJson() => {
"ability": ability.toJson(),
"is_hidden": isHidden,
"slot": slot,
};
}
class Species {
Species({
required this.name,
required this.url,
});
final String name;
final String url;
factory Species.fromJson(Map<String, dynamic> json) => Species(
name: json["name"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"name": name,
"url": url,
};
}
class GameIndex {
GameIndex({
required this.gameIndex,
required this.version,
});
final int gameIndex;
final Species version;
factory GameIndex.fromJson(Map<String, dynamic> json) => GameIndex(
gameIndex: json["game_index"],
version: Species.fromJson(json["version"]),
);
Map<String, dynamic> toJson() => {
"game_index": gameIndex,
"version": version.toJson(),
};
}
class Move {
Move({
required this.move,
required this.versionGroupDetails,
});
final Species move;
final List<VersionGroupDetail> versionGroupDetails;
factory Move.fromJson(Map<String, dynamic> json) => Move(
move: Species.fromJson(json["move"]),
versionGroupDetails: List<VersionGroupDetail>.from(
json["version_group_details"]
.map((x) => VersionGroupDetail.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"move": move.toJson(),
"version_group_details":
List<dynamic>.from(versionGroupDetails.map((x) => x.toJson())),
};
}
class VersionGroupDetail {
VersionGroupDetail({
required this.levelLearnedAt,
required this.moveLearnMethod,
required this.versionGroup,
});
final int levelLearnedAt;
final Species moveLearnMethod;
final Species versionGroup;
factory VersionGroupDetail.fromJson(Map<String, dynamic> json) =>
VersionGroupDetail(
levelLearnedAt: json["level_learned_at"],
moveLearnMethod: Species.fromJson(json["move_learn_method"]),
versionGroup: Species.fromJson(json["version_group"]),
);
Map<String, dynamic> toJson() => {
"level_learned_at": levelLearnedAt,
"move_learn_method": moveLearnMethod.toJson(),
"version_group": versionGroup.toJson(),
};
}
class GenerationV {
GenerationV({
required this.blackWhite,
});
final Sprites blackWhite;
factory GenerationV.fromJson(Map<String, dynamic> json) => GenerationV(
blackWhite: Sprites.fromJson(json["black-white"]),
);
Map<String, dynamic> toJson() => {
"black-white": blackWhite.toJson(),
};
}
class GenerationIv {
GenerationIv({
required this.diamondPearl,
required this.heartgoldSoulsilver,
required this.platinum,
});
final Sprites diamondPearl;
final Sprites heartgoldSoulsilver;
final Sprites platinum;
factory GenerationIv.fromJson(Map<String, dynamic> json) => GenerationIv(
diamondPearl: Sprites.fromJson(json["diamond-pearl"]),
heartgoldSoulsilver: Sprites.fromJson(json["heartgold-soulsilver"]),
platinum: Sprites.fromJson(json["platinum"]),
);
Map<String, dynamic> toJson() => {
"diamond-pearl": diamondPearl.toJson(),
"heartgold-soulsilver": heartgoldSoulsilver.toJson(),
"platinum": platinum.toJson(),
};
}
class Versions {
Versions({
required this.generationI,
required this.generationIi,
required this.generationIii,
required this.generationIv,
required this.generationV,
required this.generationVi,
required this.generationVii,
required this.generationViii,
});
final GenerationI generationI;
final GenerationIi generationIi;
final GenerationIii generationIii;
final GenerationIv generationIv;
final GenerationV generationV;
final Map<String, Home> generationVi;
final GenerationVii generationVii;
final GenerationViii generationViii;
factory Versions.fromJson(Map<String, dynamic> json) => Versions(
generationI: GenerationI.fromJson(json["generation-i"]),
generationIi: GenerationIi.fromJson(json["generation-ii"]),
generationIii: GenerationIii.fromJson(json["generation-iii"]),
generationIv: GenerationIv.fromJson(json["generation-iv"]),
generationV: GenerationV.fromJson(json["generation-v"]),
generationVi: Map.from(json["generation-vi"])
.map((k, v) => MapEntry<String, Home>(k, Home.fromJson(v))),
generationVii: GenerationVii.fromJson(json["generation-vii"]),
generationViii: GenerationViii.fromJson(json["generation-viii"]),
);
Map<String, dynamic> toJson() => {
"generation-i": generationI.toJson(),
"generation-ii": generationIi.toJson(),
"generation-iii": generationIii.toJson(),
"generation-iv": generationIv.toJson(),
"generation-v": generationV.toJson(),
"generation-vi": Map.from(generationVi)
.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
"generation-vii": generationVii.toJson(),
"generation-viii": generationViii.toJson(),
};
}
class Sprites {
Sprites({
required this.backDefault,
required this.backFemale,
required this.backShiny,
required this.backShinyFemale,
required this.frontDefault,
required this.frontFemale,
required this.frontShiny,
required this.frontShinyFemale,
required this.other,
required this.versions,
required this.animated,
});
final String backDefault;
final dynamic backFemale;
final String backShiny;
final dynamic backShinyFemale;
final String frontDefault;
final dynamic frontFemale;
final String frontShiny;
final dynamic frontShinyFemale;
final OtherP? other;
final Versions? versions;
final Animated? animated;
factory Sprites.fromJson(Map<String, dynamic> json) => Sprites(
backDefault: json["back_default"],
backFemale: json["back_female"],
backShiny: json["back_shiny"],
backShinyFemale: json["back_shiny_female"],
frontDefault: json["front_default"],
frontFemale: json["front_female"],
frontShiny: json["front_shiny"],
frontShinyFemale: json["front_shiny_female"],
// other: json["other"],
other: (json["other"] != null) ? OtherP.fromJson(json["other"]) : null,
versions: (json["versions"] != null)
? Versions.fromJson(json["versions"])
: null,
animated: (json["animated"] != null)
? Animated.fromJson(json["animated"])
: null,
);
Map<String, dynamic> toJson() => {
"back_default": backDefault,
"back_female": backFemale,
"back_shiny": backShiny,
"back_shiny_female": backShinyFemale,
"front_default": frontDefault,
"front_female": frontFemale,
"front_shiny": frontShiny,
"front_shiny_female": frontShinyFemale,
"other": other,
"versions": versions,
"animated": animated,
};
}
class GenerationI {
GenerationI({
required this.redBlue,
required this.yellow,
});
final RedBlue redBlue;
final RedBlue yellow;
factory GenerationI.fromJson(Map<String, dynamic> json) => GenerationI(
redBlue: RedBlue.fromJson(json["red-blue"]),
yellow: RedBlue.fromJson(json["yellow"]),
);
Map<String, dynamic> toJson() => {
"red-blue": redBlue.toJson(),
"yellow": yellow.toJson(),
};
}
class RedBlue {
RedBlue({
required this.backDefault,
required this.backGray,
required this.backTransparent,
required this.frontDefault,
required this.frontGray,
required this.frontTransparent,
});
final String backDefault;
final String backGray;
final String backTransparent;
final String frontDefault;
final String frontGray;
final String frontTransparent;
factory RedBlue.fromJson(Map<String, dynamic> json) => RedBlue(
backDefault: json["back_default"],
backGray: json["back_gray"],
backTransparent: json["back_transparent"],
frontDefault: json["front_default"],
frontGray: json["front_gray"],
frontTransparent: json["front_transparent"],
);
Map<String, dynamic> toJson() => {
"back_default": backDefault,
"back_gray": backGray,
"back_transparent": backTransparent,
"front_default": frontDefault,
"front_gray": frontGray,
"front_transparent": frontTransparent,
};
}
class GenerationIi {
GenerationIi({
required this.crystal,
required this.gold,
required this.silver,
});
final Crystal crystal;
final Gold gold;
final Gold silver;
factory GenerationIi.fromJson(Map<String, dynamic> json) => GenerationIi(
crystal: Crystal.fromJson(json["crystal"]),
gold: Gold.fromJson(json["gold"]),
silver: Gold.fromJson(json["silver"]),
);
Map<String, dynamic> toJson() => {
"crystal": crystal.toJson(),
"gold": gold.toJson(),
"silver": silver.toJson(),
};
}
class Crystal {
Crystal({
required this.backDefault,
required this.backShiny,
required this.backShinyTransparent,
required this.backTransparent,
required this.frontDefault,
required this.frontShiny,
required this.frontShinyTransparent,
required this.frontTransparent,
});
final String backDefault;
final String backShiny;
final String backShinyTransparent;
final String backTransparent;
final String frontDefault;
final String frontShiny;
final String frontShinyTransparent;
final String frontTransparent;
factory Crystal.fromJson(Map<String, dynamic> json) => Crystal(
backDefault: json["back_default"],
backShiny: json["back_shiny"],
backShinyTransparent: json["back_shiny_transparent"],
backTransparent: json["back_transparent"],
frontDefault: json["front_default"],
frontShiny: json["front_shiny"],
frontShinyTransparent: json["front_shiny_transparent"],
frontTransparent: json["front_transparent"],
);
Map<String, dynamic> toJson() => {
"back_default": backDefault,
"back_shiny": backShiny,
"back_shiny_transparent": backShinyTransparent,
"back_transparent": backTransparent,
"front_default": frontDefault,
"front_shiny": frontShiny,
"front_shiny_transparent": frontShinyTransparent,
"front_transparent": frontTransparent,
};
}
class Gold {
Gold({
required this.backDefault,
required this.backShiny,
required this.frontDefault,
required this.frontShiny,
required this.frontTransparent,
});
final String backDefault;
final String backShiny;
final String frontDefault;
final String frontShiny;
final String frontTransparent;
factory Gold.fromJson(Map<String, dynamic> json) => Gold(
backDefault: json["back_default"],
backShiny: json["back_shiny"],
frontDefault: json["front_default"],
frontShiny: json["front_shiny"],
frontTransparent: json["front_transparent"] ?? "",
);
Map<String, dynamic> toJson() => {
"back_default": backDefault,
"back_shiny": backShiny,
"front_default": frontDefault,
"front_shiny": frontShiny,
"front_transparent": frontTransparent,
};
}
class GenerationIii {
GenerationIii({
required this.emerald,
required this.fireredLeafgreen,
required this.rubySapphire,
});
final OfficialArtwork emerald;
final Gold fireredLeafgreen;
final Gold rubySapphire;
factory GenerationIii.fromJson(Map<String, dynamic> json) => GenerationIii(
emerald: OfficialArtwork.fromJson(json["emerald"]),
fireredLeafgreen: Gold.fromJson(json["firered-leafgreen"]),
rubySapphire: Gold.fromJson(json["ruby-sapphire"]),
);
Map<String, dynamic> toJson() => {
"emerald": emerald.toJson(),
"firered-leafgreen": fireredLeafgreen.toJson(),
"ruby-sapphire": rubySapphire.toJson(),
};
}
class OfficialArtwork {
OfficialArtwork({
required this.frontDefault,
required this.frontShiny,
});
final String frontDefault;
final String frontShiny;
factory OfficialArtwork.fromJson(Map<String, dynamic> json) =>
OfficialArtwork(
frontDefault: json["front_default"],
frontShiny: json["front_shiny"],
);
Map<String, dynamic> toJson() => {
"front_default": frontDefault,
"front_shiny": frontShiny,
};
}
class Home {
Home({
required this.frontDefault,
required this.frontFemale,
required this.frontShiny,
required this.frontShinyFemale,
});
final String frontDefault;
final dynamic frontFemale;
final String frontShiny;
final dynamic frontShinyFemale;
factory Home.fromJson(Map<String, dynamic> json) => Home(
frontDefault: json["front_default"],
frontFemale: json["front_female"],
frontShiny: json["front_shiny"],
frontShinyFemale: json["front_shiny_female"],
);
Map<String, dynamic> toJson() => {
"front_default": frontDefault,
"front_female": frontFemale,
"front_shiny": frontShiny,
"front_shiny_female": frontShinyFemale,
};
}
class GenerationVii {
GenerationVii({
required this.icons,
required this.ultraSunUltraMoon,
});
final DreamWorld icons;
final Home ultraSunUltraMoon;
factory GenerationVii.fromJson(Map<String, dynamic> json) => GenerationVii(
icons: DreamWorld.fromJson(json["icons"]),
ultraSunUltraMoon: Home.fromJson(json["ultra-sun-ultra-moon"]),
);
Map<String, dynamic> toJson() => {
"icons": icons.toJson(),
"ultra-sun-ultra-moon": ultraSunUltraMoon.toJson(),
};
}
class DreamWorld {
DreamWorld({
required this.frontDefault,
required this.frontFemale,
});
final String frontDefault;
final dynamic frontFemale;
factory DreamWorld.fromJson(Map<String, dynamic> json) => DreamWorld(
frontDefault: json["front_default"],
frontFemale: json["front_female"],
);
Map<String, dynamic> toJson() => {
"front_default": frontDefault,
"front_female": frontFemale,
};
}
class GenerationViii {
GenerationViii({
required this.icons,
});
final DreamWorld icons;
factory GenerationViii.fromJson(Map<String, dynamic> json) => GenerationViii(
icons: DreamWorld.fromJson(json["icons"]),
);
Map<String, dynamic> toJson() => {
"icons": icons.toJson(),
};
}
class OtherP {
OtherP({
required this.dreamWorld,
required this.home,
required this.officialArtwork,
});
final DreamWorld dreamWorld;
final Home home;
final OfficialArtwork officialArtwork;
factory OtherP.fromJson(Map<String, dynamic> json) => OtherP(
dreamWorld: DreamWorld.fromJson(json["dream_world"]),
home: Home.fromJson(json["home"]),
officialArtwork: OfficialArtwork.fromJson(json["official-artwork"]),
);
Map<String, dynamic> toJson() => {
"dream_world": dreamWorld.toJson(),
"home": home.toJson(),
"official-artwork": officialArtwork.toJson(),
};
}
class Stat {
Stat({
required this.baseStat,
required this.effort,
required this.stat,
});
final int baseStat;
final int effort;
final Species stat;
factory Stat.fromJson(Map<String, dynamic> json) => Stat(
baseStat: json["base_stat"],
effort: json["effort"],
stat: Species.fromJson(json["stat"]),
);
Map<String, dynamic> toJson() => {
"base_stat": baseStat,
"effort": effort,
"stat": stat.toJson(),
};
}
class Type {
Type({
required this.slot,
required this.type,
});
final int slot;
final Species type;
factory Type.fromJson(Map<String, dynamic> json) => Type(
slot: json["slot"],
type: Species.fromJson(json["type"]),
);
Map<String, dynamic> toJson() => {
"slot": slot,
"type": type.toJson(),
};
}
class Animated {
Animated({
required this.backDefault,
required this.backFemale,
required this.backShiny,
required this.backShinyFemale,
required this.frontDefault,
required this.frontFemale,
required this.frontShiny,
required this.frontShinyFemale,
});
final String? backDefault;
final dynamic backFemale;
final String? backShiny;
final dynamic backShinyFemale;
final String? frontDefault;
final dynamic frontFemale;
final String? frontShiny;
final dynamic frontShinyFemale;
factory Animated.fromJson(Map<String, dynamic> json) => Animated(
backDefault: json["back_default"],
backFemale: json["back_female"],
backShiny: json["back_shiny"],
backShinyFemale: json["back_shiny_female"],
frontDefault: json["front_default"],
frontFemale: json["front_female"],
frontShiny: json["front_shiny"],
frontShinyFemale: json["front_shiny_female"],
);
Map<String, dynamic> toJson() => {
"back_default": backDefault,
"back_female": backFemale,
"back_shiny": backShiny,
"back_shiny_female": backShinyFemale,
"front_default": frontDefault,
"front_female": frontFemale,
"front_shiny": frontShiny,
"front_shiny_female": frontShinyFemale,
};
}
| 0 |
mirrored_repositories/pokemon-provider/lib | mirrored_repositories/pokemon-provider/lib/models/pokemon_list_model.dart | // To parse this JSON data, do
//
// final pokemonListModel = pokemonListModelFromJson(jsonString);
import 'dart:convert';
PokemonListModel? pokemonListModelFromJson(String str) =>
PokemonListModel.fromJson(json.decode(str));
String pokemonListModelToJson(PokemonListModel? data) =>
json.encode(data!.toJson());
class PokemonListModel {
PokemonListModel({
this.count,
this.next,
this.previous,
this.results,
});
int? count;
String? next;
dynamic previous;
List<Result?>? results;
factory PokemonListModel.fromJson(Map<String, dynamic> json) =>
PokemonListModel(
count: json["count"],
next: json["next"],
previous: json["previous"],
results: json["results"] == null
? []
: List<Result?>.from(
json["results"]!.map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"count": count,
"next": next,
"previous": previous,
"results": results == null
? []
: List<dynamic>.from(results!.map((x) => x!.toJson())),
};
}
class Result {
Result({
this.name,
this.url,
});
String? name;
String? url;
factory Result.fromJson(Map<String, dynamic> json) => Result(
name: json["name"],
url: json["url"],
);
Map<String, dynamic> toJson() => {
"name": name,
"url": url,
};
}
| 0 |
mirrored_repositories/pokemon-provider/lib | mirrored_repositories/pokemon-provider/lib/provider/pokemon_detail_provider.dart | import 'package:flutter/material.dart';
import 'package:pokemon/models/pokemon_detail_model.dart';
import 'package:http/http.dart' as http;
class PokemonDetailProvider extends ChangeNotifier {
bool isLoading = false;
PokemonDetailModel? _pokemonDetail;
PokemonDetailModel? get pokemonDetail => _pokemonDetail;
Future<void> getPokemonDetail(url) async {
isLoading = true;
// notifyListeners();
final response = await http.get(Uri.parse(url));
_pokemonDetail = pokemonDetailModelFromJson(response.body);
isLoading = false;
notifyListeners();
}
// setUrl(String url) async {
// final response = await http.get(Uri.parse(url));
// _pokemonDetail = pokemonDetailModelFromJson(response.body);
// isLoading = false;
// notifyListeners();
// }
}
| 0 |
mirrored_repositories/pokemon-provider/lib | mirrored_repositories/pokemon-provider/lib/provider/pokemon_list_provider.dart | import 'package:flutter/material.dart';
import 'package:pokemon/models/pokemon_detail_model.dart';
import 'package:pokemon/models/pokemon_list_model.dart';
import 'package:http/http.dart' as http;
class PokemonListProvider extends ChangeNotifier {
bool isLoading = false;
PokemonListModel? _pokemonList;
PokemonListModel? get pokemonList => _pokemonList;
PokemonDetailModel? _pokemonDetail;
PokemonDetailModel? get pokemonDetail => _pokemonDetail;
Future<void> getPokemonList() async {
isLoading = true;
notifyListeners();
final response =
await http.get(Uri.parse('https://pokeapi.co/api/v2/pokemon/'));
_pokemonList = pokemonListModelFromJson(response.body);
isLoading = false;
notifyListeners();
}
setUrl(String url) async {
final response = await http.get(Uri.parse(url));
_pokemonDetail = pokemonDetailModelFromJson(response.body);
isLoading = false;
notifyListeners();
}
}
| 0 |
mirrored_repositories/pokemon-provider | mirrored_repositories/pokemon-provider/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:pokemon/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/FlutterTraining-ExpenseApp | mirrored_repositories/FlutterTraining-ExpenseApp/lib/main.dart | import 'package:expense_app/widgets/chart.dart';
import 'package:expense_app/widgets/new_transaction.dart';
import 'package:expense_app/widgets/transaction_list.dart';
import 'package:flutter/material.dart';
import 'package:expense_app/models/transaction.dart';
import 'package:flutter/services.dart';
import 'dart:io';
void main() {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Personal Expenses',
home: MyHomePage(),
theme: ThemeData(
primarySwatch: Colors.green,
//accentColor: Colors.amber,
fontFamily: 'Quicksand',
textTheme: ThemeData.light().textTheme.copyWith(
title: TextStyle(
fontFamily: 'OpenSans',
fontSize: 18,
),
button: TextStyle(color: Colors.white)),
appBarTheme: AppBarTheme(
textTheme: ThemeData.light().textTheme.copyWith(
title: TextStyle(
fontFamily: 'OpenSans',
fontSize: 20,
),
),
)),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final List<Transaction> _userTransaction = [];
List<Transaction> get _recentTransactions {
return _userTransaction.where((tx) {
return tx.date.isAfter(
DateTime.now().subtract(
Duration(days: 7),
),
);
}).toList();
}
void _addNewTransaction(
String txTitle, double txAmount, DateTime choosenDate) {
final newTx = Transaction(
title: txTitle,
amount: txAmount,
date: choosenDate,
id: DateTime.now().toString());
setState(() {
_userTransaction.add(newTx);
});
}
void _deleteTransaction(String id) {
setState(() {
_userTransaction.removeWhere((tx) {
return tx.id == id;
});
});
}
void _startAddNewTransaction(ctx) {
showModalBottomSheet(
context: ctx,
builder: (_) {
return NewTransaction(_addNewTransaction);
});
}
@override
Widget build(BuildContext context) {
final appBar = AppBar(
title: Text('Personal Expenses'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add_box),
onPressed: () => _startAddNewTransaction(context),
)
],
);
return Scaffold(
appBar: appBar,
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
height: (MediaQuery.of(context).size.height -
appBar.preferredSize.height -
MediaQuery.of(context).padding.top) *
0.3,
child: Chart(_recentTransactions)),
Container(
height: (MediaQuery.of(context).size.height -
appBar.preferredSize.height -
MediaQuery.of(context).padding.top) *
0.7,
child: TransactionList(_userTransaction, _deleteTransaction)),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: Platform.isIOS ? Container() : FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _startAddNewTransaction(context),
),
);
}
}
| 0 |
mirrored_repositories/FlutterTraining-ExpenseApp/lib | mirrored_repositories/FlutterTraining-ExpenseApp/lib/widgets/new_transaction.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:io';
class NewTransaction extends StatefulWidget {
final Function addTx;
NewTransaction(this.addTx);
@override
_NewTransactionState createState() => _NewTransactionState();
}
class _NewTransactionState extends State<NewTransaction> {
final _titleController = TextEditingController();
final _amountController = TextEditingController();
DateTime _selectedDate;
void _submitData() {
final inputTitle = _titleController.text;
final inputAmount = double.parse(_amountController.text);
if (inputTitle.isEmpty || inputAmount <= 0 || _selectedDate == null) {
return;
}
widget.addTx(inputTitle, inputAmount, _selectedDate);
Navigator.of(context).pop();
}
void _presentDatePicker() {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime.now())
.then((pickedDate) {
if (pickedDate == null) {
return;
} else {
setState(() {
_selectedDate = pickedDate;
});
}
});
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Card(
child: Container(
padding: EdgeInsets.only(
top: 10,
left: 10,
right: 10,
bottom: MediaQuery.of(context).viewInsets.bottom + 10),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Title'),
controller: _titleController,
onSubmitted: (_) => _submitData(),
),
TextField(
decoration: InputDecoration(labelText: 'Amout'),
controller: _amountController,
keyboardType: TextInputType.number,
onSubmitted: (_) => _submitData(),
),
Container(
height: 70,
child: Row(
children: <Widget>[
Flexible(
fit: FlexFit.tight,
child: Text(_selectedDate == null
? 'No Date Choosen !'
: DateFormat.d()
.add_MMM()
.add_y()
.format(_selectedDate))),
Platform.isIOS
? CupertinoButton(
child: Text(
'Choose a date',
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: _presentDatePicker,
)
: FlatButton(
textColor: Theme.of(context).primaryColor,
child: Text(
'Choose a date',
style: TextStyle(fontWeight: FontWeight.bold),
),
onPressed: _presentDatePicker,
)
],
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Theme.of(context).primaryColor,
textColor: Theme.of(context).textTheme.button.color,
child: Text("Add transaction"),
onPressed: _submitData,
),
],
),
)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/FlutterTraining-ExpenseApp/lib | mirrored_repositories/FlutterTraining-ExpenseApp/lib/widgets/transaction_list.dart | import 'package:expense_app/models/transaction.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
final Function deleteTx;
TransactionList(this.transactions, this.deleteTx);
@override
Widget build(BuildContext context) {
return transactions.isEmpty
? Column(
children: <Widget>[
Text(
'No transaction yet !',
style: Theme.of(context).textTheme.title,
),
SizedBox(
height: 30,
),
Container(
height: 200,
child: Image.asset(
'assets/images/waiting.png',
fit: BoxFit.cover,
),
),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 2,
margin: EdgeInsets.symmetric(vertical: 8, horizontal: 5),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(6),
child: FittedBox(
child: Text('${transactions[index].amount}€')),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.title,
),
subtitle: Text(
DateFormat.d()
.add_MMM()
.add_y()
.format(transactions[index].date),
),
trailing: IconButton(
icon: Icon(Icons.delete),
color: Theme.of(context).errorColor,
onPressed: () {
deleteTx(transactions[index].id);
},
),
),
);
},
itemCount: transactions.length,
);
}
}
| 0 |
mirrored_repositories/FlutterTraining-ExpenseApp/lib | mirrored_repositories/FlutterTraining-ExpenseApp/lib/widgets/chart.dart | import 'package:expense_app/models/transaction.dart';
import 'package:expense_app/widgets/chart_bar.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class Chart extends StatelessWidget {
final List<Transaction> recentTransactions;
Chart(this.recentTransactions);
List<Map<String, Object>> get groupeTransactionValues {
return List.generate(7, (index) {
final weekDay = DateTime.now().subtract(
Duration(days: index),
);
double totalSum = 0.0;
for (var i = 0; i < recentTransactions.length; i++) {
if (recentTransactions[i].date.day == weekDay.day &&
recentTransactions[i].date.month == weekDay.month &&
recentTransactions[i].date.year == weekDay.year) {
totalSum += recentTransactions[i].amount;
}
}
return {
'day': DateFormat.E().format(weekDay).substring(0, 1),
'amount': totalSum,
};
}).reversed.toList();
}
double get totalSpending {
return groupeTransactionValues.fold(0.0, (sum, item) {
return sum + item['amount'];
});
}
@override
Widget build(BuildContext context) {
print(groupeTransactionValues);
return Card(
elevation: 6,
margin: EdgeInsets.all(20),
child: Container(
padding: EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: groupeTransactionValues.map((data) {
return Flexible(
fit: FlexFit.tight,
child: ChartBar(
data['day'],
data['amount'],
totalSpending == 0.0
? 0.0
: (data['amount'] as double) / totalSpending),
);
}).toList(),
),
),
);
}
}
| 0 |
mirrored_repositories/FlutterTraining-ExpenseApp/lib | mirrored_repositories/FlutterTraining-ExpenseApp/lib/widgets/chart_bar.dart | import 'package:flutter/material.dart';
class ChartBar extends StatelessWidget {
final String label;
final double spendingAmount;
final double spendingPctOfTotal;
ChartBar(this.label, this.spendingAmount, this.spendingPctOfTotal);
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (ctx, constraint) {
return Column(
children: <Widget>[
Container(
height: constraint.maxHeight * 0.15,
child: FittedBox(
child: Text('${spendingAmount.toStringAsFixed(0)}€'))),
SizedBox(
height: constraint.maxHeight * 0.05,
),
Container(
height: constraint.maxHeight * 0.6,
width: 10,
child: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey, width: 1.0),
color: Color.fromRGBO(220, 220, 220, 1),
borderRadius: BorderRadius.circular(10),
),
),
FractionallySizedBox(
heightFactor: spendingPctOfTotal,
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.circular(10),
),
),
)
],
),
),
SizedBox(
height: constraint.maxHeight * 0.05,
),
Container(
height: constraint.maxHeight * 0.15,
child: FittedBox(
child: Text(label),
),
)
],
);
},
);
}
}
| 0 |
mirrored_repositories/FlutterTraining-ExpenseApp/lib | mirrored_repositories/FlutterTraining-ExpenseApp/lib/models/transaction.dart | import 'package:flutter/foundation.dart';
class Transaction {
final String id;
final String title;
final double amount;
final DateTime date;
Transaction({
@required this.id,
@required this.title,
@required this.amount,
@required this.date
});
} | 0 |
mirrored_repositories/FlutterTraining-ExpenseApp | mirrored_repositories/FlutterTraining-ExpenseApp/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:expense_app/main.dart';
void main() {
}
| 0 |
mirrored_repositories/Multi-language-support-Flutter-Example | mirrored_repositories/Multi-language-support-Flutter-Example/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_multiple_languages/screens/home.dart';
import 'localization/locale_constant.dart';
import 'localization/localizations_delegate.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
static void setLocale(BuildContext context, Locale newLocale) {
var state = context.findAncestorStateOfType<_MyAppState>();
state!.setLocale(newLocale);
}
@override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Locale _locale;
void setLocale(Locale locale) {
setState(() {
_locale = locale;
});
}
@override
void didChangeDependencies() async {
getLocale().then((locale) {
setState(() {
_locale = locale;
});
});
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) {
return MediaQuery(
child: child!,
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
);
},
title: 'Multi Language',
debugShowCheckedModeBanner: false,
locale: _locale,
home: Home(),
supportedLocales: [
Locale('en', ''),
Locale('ar', ''),
Locale('hi', '')
],
localizationsDelegates: [
AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
localeResolutionCallback: (locale, supportedLocales) {
for (var supportedLocale in supportedLocales) {
if (supportedLocale?.languageCode == locale?.languageCode &&
supportedLocale?.countryCode == locale?.countryCode) {
return supportedLocale;
}
}
return supportedLocales?.first;
},
);
}
}
| 0 |
mirrored_repositories/Multi-language-support-Flutter-Example/lib | mirrored_repositories/Multi-language-support-Flutter-Example/lib/model/language_data.dart |
class LanguageData {
final String flag;
final String name;
final String languageCode;
LanguageData(this.flag, this.name, this.languageCode);
static List<LanguageData> languageList() {
return <LanguageData>[
LanguageData("🇺🇸", "English", 'en'),
LanguageData("🇸🇦", "اَلْعَرَبِيَّةُ", "ar"),
LanguageData("🇮🇳", "हिंदी", 'hi'),
];
}
}
| 0 |
mirrored_repositories/Multi-language-support-Flutter-Example/lib | mirrored_repositories/Multi-language-support-Flutter-Example/lib/screens/home.dart | import 'package:flutter/material.dart';
import 'package:flutter_multiple_languages/localization/language/languages.dart';
import 'package:flutter_multiple_languages/localization/locale_constant.dart';
import 'package:flutter_multiple_languages/model/language_data.dart';
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() => HomeState();
}
class HomeState extends State<Home> {
@override
Widget build(BuildContext context) =>
Scaffold(
appBar: AppBar(
leading: Icon(
Icons.language,
color: Colors.white,
),
title: Text(Languages
.of(context)!
.appName),
),
body: Container(
margin: EdgeInsets.all(30),
child: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 80,
),
Text(
Languages
.of(context)!
.labelWelcome,
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Colors.black),
),
SizedBox(
height: 30,
),
Text(
Languages
.of(context)!
.labelInfo,
style: TextStyle(fontSize: 20, color: Colors.grey),
textAlign: TextAlign.center,
),
SizedBox(
height: 70,
),
_createLanguageDropDown()
],
),
),
),
);
_createLanguageDropDown() {
return DropdownButton<LanguageData>(
iconSize: 30,
hint: Text(Languages
.of(context)!
.labelSelectLanguage),
onChanged: (LanguageData? language) {
changeLanguage(context, language!.languageCode);
},
items: LanguageData.languageList()
.map<DropdownMenuItem<LanguageData>>(
(e) =>
DropdownMenuItem<LanguageData>(
value: e,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text(
e.flag,
style: TextStyle(fontSize: 30),
),
Text(e.name)
],
),
),
)
.toList(),
);
}
}
| 0 |
mirrored_repositories/Multi-language-support-Flutter-Example/lib | mirrored_repositories/Multi-language-support-Flutter-Example/lib/localization/localizations_delegate.dart | import 'package:flutter/material.dart';
import 'package:flutter_multiple_languages/localization/language/language_en.dart';
import 'package:flutter_multiple_languages/localization/language/language_hi.dart';
import 'language/language_ar.dart';
import 'language/languages.dart';
class AppLocalizationsDelegate extends LocalizationsDelegate<Languages> {
const AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) =>
['en', 'ar', 'hi'].contains(locale.languageCode);
@override
Future<Languages> load(Locale locale) => _load(locale);
static Future<Languages> _load(Locale locale) async {
switch (locale.languageCode) {
case 'en':
return LanguageEn();
case 'ar':
return LanguageAr();
case 'hi':
return LanguageHi();
default:
return LanguageEn();
}
}
@override
bool shouldReload(LocalizationsDelegate<Languages> old) => false;
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.