repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Chat/bot_msg.dart | import "package:flutter/material.dart";
class BotMsg extends StatelessWidget {
final String message;
BotMsg({required this.message});
Widget build(BuildContext context) {
return ClipRRect(
child: Container(
decoration: BoxDecoration(
color: const Color.fromARGB(255, 47, 90, 124),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0),
bottomLeft: Radius.circular(0.0),
bottomRight: Radius.circular(15.0),
),
),
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.fromLTRB(16.0, 16.0, 100.0, 16.0),
// decoration: BoxDecoration(borderRadius: BorderRadius.circular(1.0)),
constraints: BoxConstraints(
minHeight: 100, // Set your minimum height
maxHeight: double.infinity, // Optionally, set a maximum height
minWidth: MediaQuery.of(context).size.width * 0.99,
maxWidth: MediaQuery.of(context).size.width * 0.99,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.chat_bubble),
Text(
"bot",
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 20,
),
),
],
),
Text(message)
],
),
),
);
;
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Chat/a_user_msg.dart | import "package:flutter/material.dart";
class UserMsg extends StatelessWidget {
final String message;
UserMsg({required this.message});
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.blue[100],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(15.0),
topRight: Radius.circular(15.0),
bottomLeft: Radius.circular(15.0),
bottomRight: Radius.circular(0.0),
),
),
constraints: BoxConstraints(
minHeight: 100, // Set your minimum height
maxHeight: double.infinity, // Optionally, set a maximum height
minWidth: MediaQuery.of(context).size.width * 0.99,
maxWidth: MediaQuery.of(context).size.width * 0.99,
),
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.fromLTRB(
100.0,
16.016,
16.0,
16.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.person_off_outlined),
Text(
"user",
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 20,
),
),
],
),
Text(
message,
)
],
),
);
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Namer_app/NamerApp.dart | import 'package:english_words/english_words.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// void main() {
// runApp(MyApp());
// }
class MyApp extends StatelessWidget {
const MyApp({super.key}); //constructor
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyAppState(),
child: MaterialApp(
title: 'Namer App',
theme: ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
),
home: MyHomePage(),
),
);
}
}
class MyAppState extends ChangeNotifier {
var current = WordPair.random();
void getNext() {
current = WordPair.random();
notifyListeners();
}
var favorites = <WordPair>[];
void toggleFavorite() {
if (favorites.contains(current)) {
favorites.remove(current);
} else {
favorites.add(current);
}
print(favorites);
notifyListeners();
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var selectedIndex = 0;
@override
Widget build(BuildContext context) {
Widget page;
switch (selectedIndex) {
case 0:
page = GeneratorPage();
break;
case 1:
page = Placeholder();
break;
default:
throw UnimplementedError('no widget for $selectedIndex');
}
return Scaffold(
body: Row(
children: [
SafeArea(
child: NavigationRail(
extended: false,
destinations: [
NavigationRailDestination(
icon: Icon(Icons.home),
label: Text('Home'),
),
NavigationRailDestination(
icon: Icon(Icons.favorite),
label: Text('Favorites'),
),
],
selectedIndex: selectedIndex,
onDestinationSelected: (value) {
setState(() {
selectedIndex = value;
});
},
),
),
Expanded(
child: Container(
color: Theme.of(context).colorScheme.primaryContainer,
child: page,
),
),
],
),
);
}
}
class GeneratorPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
var appState = context.watch<MyAppState>();
var pair = appState.current;
IconData icon;
if (appState.favorites.contains(pair)) {
icon = Icons.favorite;
} else {
icon = Icons.favorite_border;
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
BigCard(pair: pair),
SizedBox(height: 10),
Row(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton.icon(
onPressed: () {
appState.toggleFavorite();
},
icon: Icon(icon),
label: Text('Like'),
),
SizedBox(width: 10),
ElevatedButton(
onPressed: () {
appState.getNext();
},
child: Text('Next'),
),
],
),
],
),
);
}
}
class BigCard extends StatelessWidget {
const BigCard({
super.key,
required this.pair,
});
final WordPair pair;
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
var style = theme.textTheme.displayMedium!.copyWith(
color: theme.colorScheme.onPrimary,
);
return Card(
color: theme.colorScheme.primary,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(pair.asLowerCase, style: style)),
);
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Sign_in and Sign_up/MyTextField.dart | import 'package:flutter/material.dart';
class MyTextField extends StatelessWidget {
final String labelText;
final bool obscureText;
final double width;
final double radius;
const MyTextField(
{required this.labelText,
required this.obscureText,
required this.width,
required this.radius});
Widget build(BuildContext context) {
return Container(
width: width,
child: TextField(
obscureText: obscureText,
// controller: textController2,
decoration: InputDecoration(
labelText: labelText,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.black),
borderRadius: BorderRadius.circular(radius),
),
),
),
);
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Sign_in and Sign_up/button.dart | import 'package:flutter/material.dart';
class Button extends StatelessWidget {
// final double radius;
final String label;
final double width;
final double height;
const Button(
{required this.label, required this.width, required this.height ,});
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 30.0, vertical: 8.0),
child: Expanded(
child: Container(
width: width,
height: height,
decoration: BoxDecoration(borderRadius: BorderRadius.circular(10.0) ,color: Colors.black,),
child: Center(
child: Text(
label,
style: TextStyle(color: Colors.white),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Sign_in and Sign_up/signin.dart | import 'package:flutter/material.dart';
import 'package:namer_app/Sign_in%20and%20Sign_up/signup.dart';
import './signup.dart';
import 'MyTextField.dart';
import 'button.dart';
class SignIn extends StatelessWidget {
final TextEditingController textController = TextEditingController();
final TextEditingController textController2 = TextEditingController();
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Sign in",
style: TextStyle(
fontSize: 40,
color: Color.fromARGB(255, 117, 116, 114),
fontWeight: FontWeight.w600)),
SizedBox(
height: 20,
width: 20,
),
MyTextField(
labelText: "User Name",
obscureText: false,
radius: 10,
width: 500,
),
MyTextField(
labelText: "password",
obscureText: true,
radius: 10,
width: 500,
),
Button(
label: "sign in ",
width: MediaQuery.of(context).size.width * 1,
height: 50),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 30.0, vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
child: Text(
"forget password? ",
style: TextStyle(color: Colors.blue[400]),
textAlign: TextAlign.left,
),
onPressed: () {},
),
TextButton(
child: Text(
"sign up",
style: TextStyle(color: Colors.blue[400]),
textAlign: TextAlign.right,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SignUp(),
));
},
),
]),
),
],
),
),
));
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Sign_in and Sign_up/signup.dart | import 'package:flutter/material.dart';
import 'package:namer_app/Sign_in%20and%20Sign_up/signin.dart';
import 'MyTextField.dart';
import 'button.dart';
class SignUp extends StatelessWidget {
final TextEditingController textController = TextEditingController();
final TextEditingController textController2 = TextEditingController();
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Sign Up",
style: TextStyle(
fontSize: 40,
color: Color.fromARGB(255, 117, 116, 114),
fontWeight: FontWeight.w600)),
MyTextField(
labelText: "User Name",
obscureText: false,
radius: 10,
width: 500,
),
MyTextField(
labelText: "Email",
obscureText: false,
radius: 10,
width: 500,
),
MyTextField(
labelText: "password",
obscureText: true,
radius: 10,
width: 500,
),
Button(
label: "sign up ",
width: MediaQuery.of(context).size.width * 1,
height: 50),
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 30.0, vertical: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
child: Text(
"sign in",
style: TextStyle(color: Colors.blue[400]),
textAlign: TextAlign.right,
),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SignIn()));
},
)
]),
),
],
),
),
// ),
));
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Demo/home_page.dart | import 'package:flutter/material.dart';
import 'package:namer_app/Demo/page2.dart';
class Home_page extends StatelessWidget {
Widget build(BuildContext context) {
return Center(
child: Container(
child: ElevatedButton(
child: Text("click"),
onPressed: () => {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => page2()))
},
)),
);
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Demo/profile.dart | import 'package:flutter/material.dart';
class Profile extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold() ;
}
} | 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Demo/page2.dart | import 'package:flutter/material.dart';
class page2 extends StatefulWidget {
State createState() => Page2State();
}
class Page2State extends State<page2> {
bool isSwitch = false;
bool? isCheckd = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: Text(
"page 2",
style: TextStyle(color: Colors.white),
),
automaticallyImplyLeading: false,
leading: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: Icon(
Icons.arrow_back_ios_new_rounded,
color: Colors.white,
)),
),
body: SingleChildScrollView(
child: Column(
children: [
Image.asset('black.jpg'),
Container(
margin: EdgeInsets.all(10.0),
padding: EdgeInsets.all(2.0),
height: 30,
width: double.infinity,
color: Colors.green,
child: Center(
child: Text(
"hello",
style: TextStyle(color: Colors.white),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: isSwitch ? Colors.blue : Colors.green,
),
onPressed: () => {},
child: Text(
"blue me ",
),
),
OutlinedButton(
onPressed: () => {},
child: Text(
"click me ",
),
),
TextButton(
onPressed: () => {},
child: Text(
"click me ",
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon(
Icons.local_fire_department,
color: Colors.green,
),
Icon(
Icons.local_fire_department,
color: Colors.green,
)
],
),
Switch(
value: isSwitch,
onChanged: (bool newBool) => {
setState(() {
isSwitch = newBool;
})
}),
Checkbox(
value: isCheckd,
onChanged: (bool? newBool) {
setState(() {
isCheckd = newBool;
});
})
],
),
)),
);
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey/lib | mirrored_repositories/The-Flutter-Odyssey/lib/Demo/demo.dart | import "package:curved_navigation_bar/curved_navigation_bar.dart";
import "package:flutter/material.dart";
import "package:namer_app/Demo/home_page.dart";
import "profile.dart";
class Demo extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.yellow,
),
home: RootPage(),
);
}
}
class RootPage extends StatefulWidget {
State createState() => RootPageState();
}
class RootPageState extends State<RootPage> {
int CurrentPage = 0;
Widget? body;
@override
Widget build(BuildContext context) {
void handeleNAvigetion(index) {
setState(() {
switch (index) {
case 0:
body = Home_page();
case 1:
body = Profile();
}
});
}
return Scaffold(
appBar: AppBar(
title: Text(
"Flutter",
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.green,
),
body: body,
floatingActionButton: FloatingActionButton(
onPressed: () => {},
child: Icon(Icons.ac_unit_sharp),
),
// bottomNavigationBar: NavigationBar(
// destinations: [
// NavigationDestination(icon: Icon(Icons.home), label: "home"),
// NavigationDestination(icon: Icon(Icons.person), label: "profile"),
// ],
// onDestinationSelected: (int index) {
// setState(() {
// CurrentPage = index;
// });
// },
// selectedIndex: CurrentPage,
// ),
// NavigationRail(
// destinations: [
// NavigationDestination(icon: Icon(Icons.home), label: "home"),
// NavigationDestination(icon: Icon(Icons.person), label: "profile"),
// ],
// onDestinationSelected: (int index) {
// setState(() {
// CurrentPage = index;
// });
// },
// selectedIndex: CurrentPage,
// ),
bottomNavigationBar: CurvedNavigationBar(
backgroundColor: Colors.white,
items: [
Icon(
Icons.home,
color: Colors.white,
),
Icon(
Icons.person,
color: Colors.white,
),
],
height: 75.0,
color: Colors.green,
onTap: (int index) {
handeleNAvigetion(index);
},
index: CurrentPage,
),
);
}
}
| 0 |
mirrored_repositories/The-Flutter-Odyssey | mirrored_repositories/The-Flutter-Odyssey/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:flutter_application_1/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/PardubiceMHD-Flutter | mirrored_repositories/PardubiceMHD-Flutter/lib/main.dart | import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';
import 'package:pardumhd/functions/fetch.dart';
import 'package:pardumhd/functions/get_url.dart';
import 'package:pardumhd/models/response.dart';
import 'package:pardumhd/widgets/download_button.dart';
import 'package:pardumhd/widgets/icon.dart';
import 'package:pardumhd/functions/location.dart';
import 'package:pardumhd/functions/modal.dart';
import 'package:pardumhd/models/bus_position.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:socket_io_client/socket_io_client.dart';
const String instantName = "instant";
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
runApp(
MaterialApp(
home: HomePage(sharedPreferences: prefs),
title: "Pardubice MHD",
),
);
}
class HomePage extends StatefulWidget {
final SharedPreferences sharedPreferences;
const HomePage({Key? key, required this.sharedPreferences}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late bool _isInstant;
static const int positionTime = 11, recalculateTime = 100;
late Timer _positionTimer;
late MapController _mapController;
List<BusPosition>? _oldPositions, _newPositions, _currentPosition;
Position? _position;
late int _sinceLastFetch;
@override
void initState() {
super.initState();
_mapController = MapController();
_sinceLastFetch = 0;
_isInstant = widget.sharedPreferences.getBool(instantName) ?? false;
_positionTimer = Timer.periodic(
const Duration(seconds: positionTime),
positionTimerTick,
);
Timer.periodic(
const Duration(milliseconds: recalculateTime),
calculatePositionTimerTick,
);
Future.delayed(Duration.zero, () async {
positionTimerTick(_positionTimer);
updateBuses(await fetchFromApi());
});
Socket socket =
io(getUrl(), OptionBuilder().setTransports(['websocket']).build());
socket.on('buses', (data) {
updateBuses(Response.fromJson(data).data);
});
}
Future<void> positionTimerTick(Timer timer) async {
final position = await determinePosition();
setState(() {
_position = position;
});
}
void updateBuses(List<BusPosition>? newBusses) {
if (newBusses == null) {
return;
}
_oldPositions = _currentPosition;
_newPositions = newBusses;
_sinceLastFetch = 0;
}
Future<void> calculatePositionTimerTick(Timer timer) async {
_sinceLastFetch++;
if (_isInstant || _oldPositions == null || _newPositions == null) {
if (_currentPosition != _newPositions) {
_newPositions!.sort(((a, b) => b.latitude.compareTo(a.latitude)));
setState(() {
_currentPosition = _newPositions;
});
}
return;
}
final percent = _sinceLastFetch * recalculateTime / 10000;
final currentPositions = _oldPositions!
.map((oldPos) {
final newPos = _newPositions!.where(
(newPos) => newPos.vid == oldPos.vid,
);
if (newPos.isEmpty) {
return null;
}
final latChange = newPos.first.latitude - oldPos.latitude;
final lonChange = newPos.first.longitude - oldPos.longitude;
final lat = oldPos.latitude + (latChange * percent);
final lon = oldPos.longitude + (lonChange * percent);
return BusPosition(
destination: newPos.first.destination,
lineName: newPos.first.lineName,
latitude: lat,
longitude: lon,
next: newPos.first.next,
last: newPos.first.last,
time: newPos.first.time,
vid: newPos.first.vid,
);
})
.where((element) => element != null)
.toList();
currentPositions.sort(((a, b) => b!.latitude.compareTo(a!.latitude)));
setState(() {
_currentPosition = List<BusPosition>.from(currentPositions);
});
}
void setInstant(bool value) {
setState(() {
_isInstant = value;
});
}
@override
void dispose() {
_positionTimer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_currentPosition == null) {
return SafeArea(
child: Container(
color: Colors.red,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
CircularProgressIndicator(color: Colors.white),
],
),
),
),
);
}
return Scaffold(
appBar: AppBar(
title: Row(
children: const [
Image(image: AssetImage("assets/Pardubice_logo.png"), height: 70),
Text("Pardubice MHD"),
],
),
backgroundColor: Colors.red,
actions: [
kIsWeb ? const DownloadAppButton() : Container(),
IconButton(
onPressed: () {
showDialog(
context: context,
builder: (context) => StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text("Nastavení",
style: TextStyle(fontSize: 20)),
CheckboxListTile(
activeColor: Colors.red,
title: const Text("Instantní mód"),
value: _isInstant,
onChanged: (value) async {
if (value != null) {
await widget.sharedPreferences
.setBool(instantName, value);
setState(() {
_isInstant = value;
});
}
},
),
],
),
actions: [
TextButton(
child: const Text("Zavřít",
style: TextStyle(color: Colors.white)),
onPressed: () {
Navigator.of(context).pop();
},
style: TextButton.styleFrom(
backgroundColor: Colors.red,
),
),
],
);
},
),
);
},
icon: const Icon(Icons.settings),
),
],
),
body: FlutterMap(
mapController: _mapController,
options: MapOptions(
center: LatLng(50.0317826, 15.7760577),
zoom: 13.0,
interactiveFlags: InteractiveFlag.pinchMove |
InteractiveFlag.pinchZoom |
InteractiveFlag.drag |
InteractiveFlag.doubleTapZoom,
maxZoom: 18,
minZoom: 11,
nePanBoundary: LatLng(50.1, 15.9),
swPanBoundary: LatLng(49.988, 15.7),
slideOnBoundaries: true,
),
layers: [
TileLayerOptions(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c'],
),
MarkerLayerOptions(
markers: [
...(_currentPosition?.map((p) => Marker(
width: 80.0,
height: 80.0,
point: LatLng(p.latitude, p.longitude),
builder: (ctx) => GestureDetector(
onTap: () {
ShowModal(context, p);
},
child: TrolleyIcon(
name: p.lineName,
),
),
)) ??
[]),
...(_position != null
? [
Marker(
point: LatLng(
_position!.latitude,
_position!.longitude,
),
builder: (ctx) => const Icon(
Icons.location_pin,
color: Colors.blue,
size: 40,
),
),
]
: []),
],
),
],
),
floatingActionButton: _position != null
? FloatingActionButton(
onPressed: () {
_mapController.move(
LatLng(_position!.latitude, _position!.longitude),
15,
);
},
child: const Icon(Icons.my_location),
backgroundColor: Colors.red,
)
: null,
);
}
}
| 0 |
mirrored_repositories/PardubiceMHD-Flutter/lib | mirrored_repositories/PardubiceMHD-Flutter/lib/widgets/icon.dart | import 'package:flutter/material.dart';
class TrolleyIcon extends StatelessWidget {
final String name;
const TrolleyIcon({required this.name, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
const double size = 40;
return SizedBox(
width: size,
height: size,
child: Stack(
alignment: Alignment.center,
children: [
const Image(
image: AssetImage("assets/trolley.png"),
width: size,
height: size,
),
Container(
alignment: Alignment.center,
child: Text(
name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/PardubiceMHD-Flutter/lib | mirrored_repositories/PardubiceMHD-Flutter/lib/widgets/download_button.dart | import 'package:flutter/material.dart';
import 'package:pardumhd/functions/get_url.dart';
import 'package:url_launcher/url_launcher.dart';
class DownloadAppButton extends StatelessWidget {
const DownloadAppButton({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: () async {
Uri _url = Uri.parse(getUrl() + "app.apk");
if (!await launchUrl(_url)) throw 'Could not launch $_url';
},
icon: const Icon(Icons.android),
);
}
}
| 0 |
mirrored_repositories/PardubiceMHD-Flutter/lib | mirrored_repositories/PardubiceMHD-Flutter/lib/models/response.dart | import 'package:pardumhd/models/bus_position.dart';
class Response {
Response({required this.success, required this.data});
bool success;
List<BusPosition> data;
Response.fromJson(Map<String, dynamic> json)
: success = json['success'],
data = (json['data'] as List<dynamic>)
.map((e) => BusPosition.fromJson(e))
.toList();
}
| 0 |
mirrored_repositories/PardubiceMHD-Flutter/lib | mirrored_repositories/PardubiceMHD-Flutter/lib/models/bus_position.dart | class BusPosition {
BusPosition({
required this.vid,
required this.lineName,
required this.latitude,
required this.longitude,
required this.time,
required this.last,
required this.next,
required this.destination,
});
String vid;
String lineName;
double latitude;
double longitude;
String? time;
String? last;
String? next;
String? destination;
BusPosition.fromJson(Map<String, dynamic> json)
: vid = json['vid'],
lineName = json['line_name'],
latitude = json['gps_latitude'],
longitude = json['gps_longitude'],
time = json['time_difference'],
last = json['last_stop_name'],
next = json['current_stop_name'],
destination = json['destination_name'];
}
| 0 |
mirrored_repositories/PardubiceMHD-Flutter/lib | mirrored_repositories/PardubiceMHD-Flutter/lib/functions/fetch.dart | import 'dart:convert';
import 'package:http/http.dart';
import 'package:pardumhd/functions/get_url.dart';
import 'package:pardumhd/models/bus_position.dart';
import 'package:pardumhd/models/response.dart' as response_model;
Future<List<BusPosition>?> fetchFromApi() async {
var url = getUrl() + "api/buses";
try {
var response = await post(Uri.parse(url));
var decodedResponse = jsonDecode(utf8.decode(response.bodyBytes));
var positions = response_model.Response.fromJson(decodedResponse).data;
return positions.where((element) => element.lineName != "MAN").toList();
} catch (e) {
return null;
}
}
| 0 |
mirrored_repositories/PardubiceMHD-Flutter/lib | mirrored_repositories/PardubiceMHD-Flutter/lib/functions/location.dart | import 'package:geolocator/geolocator.dart';
Future<Position?> determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return null;
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return null;
}
}
if (permission == LocationPermission.deniedForever) {
return null;
}
return await Geolocator.getCurrentPosition();
}
| 0 |
mirrored_repositories/PardubiceMHD-Flutter/lib | mirrored_repositories/PardubiceMHD-Flutter/lib/functions/modal.dart | import 'package:flutter/material.dart';
import 'package:pardumhd/models/bus_position.dart';
void ShowModal(BuildContext context, BusPosition busPosition) {
var isLate = busPosition.time == null ? null : busPosition.time?[0] == "-";
var parsedTime = isLate == null
? null
: isLate
? busPosition.time?.substring(1)
: busPosition.time;
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return ListView(
shrinkWrap: true,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text("Číslo linky : ", style: leftStyle),
Text("Cílová zastávka : ", style: leftStyle),
Text("Poslední zastávka : ", style: leftStyle),
Text("Další zastávka : ", style: leftStyle),
Text(isLate ?? true ? "Zpoždění : " : "Napřed : ",
style: leftStyle)
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(busPosition.lineName),
Text(busPosition.destination ?? "Není"),
Text(busPosition.last ?? "Není"),
Text(busPosition.next ?? "Není"),
Text(parsedTime ?? "Včas"),
],
),
],
),
),
],
);
},
);
}
TextStyle leftStyle = const TextStyle(
fontWeight: FontWeight.bold,
);
| 0 |
mirrored_repositories/PardubiceMHD-Flutter/lib | mirrored_repositories/PardubiceMHD-Flutter/lib/functions/get_url.dart | String getUrl() {
return "https://mhd.madsoft.cz/";
}
| 0 |
mirrored_repositories/ExpensePlus | mirrored_repositories/ExpensePlus/lib/expenses_store.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:mobx/mobx.dart';
import 'package:expensePlus/database/expense_provider.dart';
import 'package:expensePlus/database/settings_provider.dart';
import 'package:expensePlus/database/tag_provider.dart';
import 'package:expensePlus/models/tag.dart';
import 'package:expensePlus/models/expense.dart';
import 'package:expensePlus/pages/graphPage.dart';
part 'expenses_store.g.dart';
class MobxStore extends MobxStoreBase with _$MobxStore {
static final MobxStore st = MobxStore._();
MobxStore._();
}
abstract class MobxStoreBase with Store {
// #region VARIABLES
@observable
List<Expense> expenses = new List<Expense>();
@observable
List<Expense> selectedDateExpenses = new List<Expense>();
@observable
Map<ViewType, List<Expense>> graphSelectedDateExpenses = new Map();
@observable
DateTime graphSelectedDate;
@observable
DateTime selectedDate;
@observable
List<Tag> tags = new List<Tag>();
@observable
Tag editTag;
@observable
Expense thumbnailExpense;
@observable
Map<ViewType, double> limitMap = new Map();
@observable
bool isAutomatic;
@observable
bool isUseLimit;
@observable
Set<Expense> editing = <Expense>{};
@observable
int currentIndex = 1;
@observable
bool firstTime = false;
@observable
bool introDone = false;
@observable
String dateStyle = 'dd/mm';
GlobalKey<NavigatorState> navigatorKey;
@observable
Image icon;
// #endregion
//
// EXPENSE SECTION
//
// #region EXPENSE
@action
void addExpense(Expense expense, {bool setDatabase = false}) {
print('STORE:\t expense added ${expense.name}');
expenses = [...expenses, expense];
if (isSelectedDate(expense, selectedDate))
selectedDateExpenses = [...selectedDateExpenses, expense];
if (setDatabase) ExpenseProvider.db.createExpense(expense);
updateGraphSelectedDate(graphSelectedDate);
}
@action
void addAllExpenses(List<Expense> inputExpenses) {
expenses = [...expenses, ...inputExpenses];
inputExpenses.forEach((expense) {
if (isSelectedDate(expense, selectedDate))
selectedDateExpenses = [...selectedDateExpenses, expense];
});
print('STORE:\t expenses added $expenses');
}
@action
void deleteExpense(Expense expense) {
// expenses.removeWhere((element) => element.id == expense.id);
expenses = expenses.where((e) => e.id != expense.id).toList();
tags = List.from(tags);
if (isSelectedDate(expense, selectedDate))
selectedDateExpenses = selectedDateExpenses
.where((element) => element.id != expense.id)
.toList();
print('STORE:\texpense deleted ${expense.name}');
updateGraphSelectedDate(graphSelectedDate);
print('All expenses STORE=>$expenses');
}
@action
void deleteAll() {
expenses = [];
selectedDateExpenses = [];
graphSelectedDateExpenses = {
ViewType.Day: [],
ViewType.Week: [],
ViewType.Month: [],
};
}
@action
void updateExpense(Expense expense, {bool setDatabase = false}) {
Expense oldExp;
expenses = expenses.map((e) {
if (e.id == expense.id) {
oldExp = e;
return expense;
}
return e;
}).toList();
// if (oldExp.date == expense.date)
// selectedDateExpenses = selectedDateExpenses.map((e) {
// if (e.id == expense.id) return expense;
// return e;
// }).toList();
// else
updateSelectedDate(selectedDate);
if (setDatabase) ExpenseProvider.db.update(expense);
print('STORE:\texpense updated ${expense.name}');
}
@action
void updateSelectedDate(DateTime inputSelectedDate) {
selectedDate = inputSelectedDate;
selectedDateExpenses = expenses
?.where((expense) => isSelectedDate(expense, selectedDate))
?.toList() ??
[];
print(
'STORE:\tselectedDateUpdated. selectedDateExpenses ==> ${selectedDateExpenses.map((e) => e.name).join(' ')}');
}
// #endregion
//
// TAGS SECTION
//
// #region TAG
@action
void addTag(Tag newTag, {bool setDatabase = false}) {
var foundTag = searchTag(newTag);
if (foundTag != null) {
newTag.id = foundTag.id;
updateTag(newTag);
} else {
tags.add(newTag);
}
for (var expense in expenses) {
var tags = expense.tags;
expense.tags = tags.map((tag) {
if (tag.name == newTag.name) return newTag;
return tag;
}).toList();
if (expense.tags.any((tag) => tag.name == newTag.name)) {
updateExpense(expense);
// ExpenseProvider.db.update(expense);
}
}
print('STORE:\ttag added ${newTag.name}');
if (setDatabase) TagProvider.db.addTag(newTag);
}
@action
void addAllTags(List<Tag> inputTags) {
tags.addAll(inputTags);
}
@action
Future<void> deleteTag(Tag tagToDelete, {bool setDatabase = false}) async {
tags = tags.where((e) => e.id != tagToDelete.id).toList();
var expensesNeedUpdate = [];
//edit expenses if there is a expense that have a [tagToDelete]
expenses = expenses.fold([], (list, exp) {
if (exp.tags.contains(tagToDelete)) {
exp.tags = exp.tags.where((tag) => tag != tagToDelete).toList();
exp.tags = exp.tags.isEmpty ? [Tag.otherTag] : exp.tags;
expensesNeedUpdate.add(exp);
}
return [...list, exp];
});
for (final exp in expensesNeedUpdate) {
await ExpenseProvider.db.update(exp);
}
if (setDatabase) TagProvider.db.delete(tagToDelete);
print('STORE:\ttag deleted ${tagToDelete.name}');
}
@action
void deleteAllTags() {
final tagsToDelete = List.from(tags);
tagsToDelete.forEach((tag) => deleteTag(tag));
tags = [];
}
@action
void updateTag(Tag tagToUpdate, {bool setDatabase = false}) {
tags = tags.map((tag) {
if (tag.id == tagToUpdate.id) return tagToUpdate;
return tag;
}).toList();
bool found = false;
for (var expense in expenses) {
expense.tags = expense.tags.map(
(tag) {
if (tag.id == tagToUpdate.id) {
found = true;
return tagToUpdate;
}
return tag;
},
).toList();
if (found) {
updateExpense(expense);
ExpenseProvider.db.update(expense);
}
}
if (setDatabase) TagProvider.db.update(tagToUpdate);
}
@action
Tag searchTag(Tag tagToUpdate) {
final oldTag = tags
.where((element) {
return element.name == tagToUpdate.name ||
element.shorten == tagToUpdate.shorten;
})
.toList()
.asMap()[0];
if (oldTag?.name != null) print('STORE:\tfound tag ${oldTag?.name}');
return oldTag;
}
Tag getTagByName(String name) {
var found = tags
.where(
(element) => element.name == name || element.shorten == name,
)
.toList();
if (found.isEmpty) return null;
return found[0];
}
@action
setThumbnailExpense(Expense newExpense) {
thumbnailExpense = newExpense;
}
// #endregion
//
// GRAPH SECTION
//
// #region GRAPH
@action
void updateGraphSelectedDate(DateTime inputSelectedDate) {
// selectedDate = DateTime.parse(selectedDate.toIso8601String());
selectedDate = inputSelectedDate ?? graphSelectedDate;
graphSelectedDate = inputSelectedDate ?? graphSelectedDate;
graphSelectedDateExpenses = {
ViewType.Day: expenses
.where(
(element) => isSelectedDate(element, graphSelectedDate),
)
.toList(),
ViewType.Week: expenses
.where(
(element) =>
weekNumber(element.date) == weekNumber(graphSelectedDate) &&
element.date.year == graphSelectedDate.year,
)
.toList(),
ViewType.Month: expenses
.where(
(element) =>
element.date.month == graphSelectedDate.month &&
element.date.year == graphSelectedDate.year,
)
.toList(),
};
print('STORE:\t graph selected date updated. $graphSelectedDate');
}
int weekNumber(DateTime date) {
int dayOfYear = int.parse(DateFormat("D").format(date));
return ((dayOfYear - date.weekday + 10) / 7).floor();
}
@action
double getSelectedDateTotalPrice([DateTime inputSelectedDate]) {
if (inputSelectedDate == null && selectedDate == null)
inputSelectedDate = DateTime(
DateTime.now().year,
DateTime.now().month,
DateTime.now().day,
);
inputSelectedDate ??= selectedDate;
return expenses.fold(0, (prev, expense) {
if (isSelectedDate(expense, inputSelectedDate ?? selectedDate))
return prev + expense.getTotalExpense();
return prev;
});
}
Map<Tag, double> getTagTotalGraph(List<Expense> expenses) {
Map<Tag, double> rv = Map();
for (var expense in expenses) {
expense.tags.forEach((tag) {
rv[tag] ??= 0;
rv[tag] += expense.getTotalExpense();
});
}
return rv;
}
double getTotalExpenseByView(ViewType type) {
switch (type) {
case ViewType.Day:
return getSelectedDateTotalPrice(graphSelectedDate);
case ViewType.Month:
int month = graphSelectedDate.month;
int year = graphSelectedDate.year;
return expenses.fold(
0.0,
(prev, exp) {
if (exp.date.year == year && exp.date.month == month)
return prev + exp.getTotalExpense();
return prev;
},
);
case ViewType.Week:
var week = weekNumber(graphSelectedDate);
var year = graphSelectedDate.year;
return expenses.fold(
0.0,
(prev, exp) {
if (exp.date.year == year && weekNumber(exp.date) == week)
return prev + exp.getTotalExpense();
return prev;
},
);
default:
return getSelectedDateTotalPrice(graphSelectedDate);
}
}
// #endregion
//
// LIMIT SECTION
//
// #region LIMIT
@action
Future<void> setLimit(ViewType viewType, double limit,
{bool setDatabase = false}) async {
limitMap = {...limitMap, viewType: limit};
if (viewType == ViewType.Month && isAutomatic && limit == null)
limitMap = {
ViewType.Day: null,
ViewType.Month: null,
ViewType.Week: null
};
if (setDatabase) await SettingsProvider.db.updateLimit(limitMap);
}
@action
Future<void> automaticSet({bool setDatabase = false}) async {
final monthly = limitMap[ViewType.Month];
if (monthly != null) {
setLimit(
ViewType.Day,
double.parse((monthly / 30).toStringAsFixed(2)),
);
setLimit(
ViewType.Week,
double.parse((monthly / 30 * 7).toStringAsFixed(2)),
);
} else {
setLimit(
ViewType.Day,
null,
);
setLimit(
ViewType.Week,
null,
);
}
if (setDatabase) {
await SettingsProvider.db.updateLimit(limitMap);
await SettingsProvider.db.updateIsAutomatic(isAutomatic);
}
}
@action
Future<void> setUseLimit(bool inputUseLimit,
{bool setDatabase = false}) async {
isUseLimit = inputUseLimit;
if (setDatabase) {
await SettingsProvider.db.updateUseLimit(isUseLimit);
}
}
//#endregion
// #region HELPER FUNCTIONS
bool isSelectedDate(Expense exp, [DateTime dateInput]) {
if (dateInput == null)
dateInput ??= selectedDate ??
DateTime(
DateTime.now().year,
DateTime.now().month,
DateTime.now().day,
);
return exp.date.year == dateInput.year &&
exp.date.month == dateInput.month &&
exp.date.day == dateInput.day;
}
// #endregion
}
| 0 |
mirrored_repositories/ExpensePlus | mirrored_repositories/ExpensePlus/lib/main.dart | import 'package:expensePlus/pages/introPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:expensePlus/database/expense_provider.dart';
import 'package:expensePlus/utilities/dummy_data.dart';
import 'package:expensePlus/database/settings_provider.dart';
import 'package:expensePlus/database/tag_provider.dart';
import 'package:expensePlus/expenses_store.dart';
import 'package:expensePlus/pages/graphPage.dart';
import 'package:expensePlus/pages/settingsPage.dart';
import 'package:expensePlus/pages/tagsPage.dart';
import 'package:expensePlus/pages/trackPage.dart';
import 'package:time/time.dart';
void main() async {
runApp(MyApp());
}
class BottomItems {
const BottomItems(this.title, this.icon, this.widget);
final String title;
final IconData icon;
final Widget widget;
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final List<BottomItems> allDestinations = <BottomItems>[
BottomItems('Graph', Icons.trending_up, GraphPage()),
BottomItems('Add Expense', Icons.attach_money, TrackPage()),
BottomItems('Tags', Icons.bookmark_border, TagsPage()),
];
final navigatorKey = GlobalKey<NavigatorState>();
bool initDone = false;
bool delayDone = false;
bool introDone = false;
TextEditingController controller = new TextEditingController();
var focusNode = new FocusNode();
@override
void initState() {
super.initState();
Future.delayed(800.milliseconds).then((value) {
setState(() {
delayDone = true;
});
});
init().then((value) {
setState(() {
initDone = true;
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
title: 'Expense +',
home: SafeArea(
child: Observer(
builder: (context) {
MobxStore.st.introDone;
MobxStore.st.firstTime;
MobxStore.st.currentIndex;
// return splashScreen();
if (!initDone || !delayDone) return splashScreen();
MobxStore.st.navigatorKey ??= navigatorKey;
if (MobxStore.st.firstTime && !MobxStore.st.introDone)
return IntroPage();
return Scaffold(
appBar: appBar(context),
bottomNavigationBar: SizedBox(
height: 55,
child: bottomNavigationBar(),
),
body: allDestinations[MobxStore.st.currentIndex].widget,
);
},
),
),
);
}
AppBar appBar(BuildContext bc) {
return AppBar(
backgroundColor: Colors.grey[700],
title: Text(
'Expense Plus',
style: TextStyle(
fontSize: 20,
),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.help),
onPressed: () {
navigatorKey.currentState.push(
MaterialPageRoute(
builder: (_) => IntroPage(true),
),
);
},
),
IconButton(
icon: Icon(Icons.settings),
onPressed: () {
navigatorKey.currentState.push(
MaterialPageRoute(
builder: (_) => SettingsPage(),
),
);
},
),
],
);
}
BottomNavigationBar bottomNavigationBar() {
return BottomNavigationBar(
selectedItemColor: Colors.white,
selectedLabelStyle: TextStyle(
color: Colors.red,
),
backgroundColor: Colors.grey[700],
currentIndex: MobxStore.st.currentIndex,
onTap: (int index) {
setState(() {
MobxStore.st.currentIndex = index;
});
},
items: allDestinations.map((BottomItems destination) {
return BottomNavigationBarItem(
icon: Icon(
destination.icon,
size: 20,
),
title: Text(destination.title),
);
}).toList(),
);
}
Widget splashScreen() {
return Scaffold(
body: SizedBox.expand(
child: Container(
decoration: BoxDecoration(
color: Color(0xff1266D3),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Spacer(flex: 273),
Image(
image: AssetImage('assets/splashScreen/splashTextIcon.png'),
loadingBuilder:
(_, Widget child, ImageChunkEvent loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: Container(
color: Colors.black,
),
);
},
),
Spacer(flex: 715),
],
),
),
),
),
);
}
Future<void> init() async {
if (initDone) return;
// await SettingsProvider.db.resetFirstTime();
final store = MobxStore.st;
store.firstTime = await SettingsProvider.db.isFirstTime();
if (store.firstTime) {
print('${DummyData.tags()} ${DummyData.expenses()}');
for (var newTag in DummyData.tags()) {
await TagProvider.db.addTag(newTag);
}
for (var newExpense in DummyData.expenses()) {
await ExpenseProvider.db.createExpense(newExpense);
}
}
final futures = await Future.wait([
TagProvider.db.getAllTags(true),
SettingsProvider.db.getLimit(),
SettingsProvider.db.getIsAutomatic(),
SettingsProvider.db.getUseLimit(),
SettingsProvider.db.getDateStyle(),
]);
if (store.limitMap.isEmpty) store.limitMap = futures[1];
if (store.isAutomatic == null) store.isAutomatic = futures[2];
if (store.isUseLimit == null) store.isUseLimit = futures[3];
store.dateStyle = futures[4];
store.updateGraphSelectedDate(DateTime(
DateTime.now().year,
DateTime.now().month,
DateTime.now().day,
));
initDone = true;
setState(() {});
}
}
| 0 |
mirrored_repositories/ExpensePlus | mirrored_repositories/ExpensePlus/lib/expenses_store.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'expenses_store.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic
mixin _$MobxStore on MobxStoreBase, Store {
final _$expensesAtom = Atom(name: 'MobxStoreBase.expenses');
@override
List<Expense> get expenses {
_$expensesAtom.reportRead();
return super.expenses;
}
@override
set expenses(List<Expense> value) {
_$expensesAtom.reportWrite(value, super.expenses, () {
super.expenses = value;
});
}
final _$selectedDateExpensesAtom =
Atom(name: 'MobxStoreBase.selectedDateExpenses');
@override
List<Expense> get selectedDateExpenses {
_$selectedDateExpensesAtom.reportRead();
return super.selectedDateExpenses;
}
@override
set selectedDateExpenses(List<Expense> value) {
_$selectedDateExpensesAtom.reportWrite(value, super.selectedDateExpenses,
() {
super.selectedDateExpenses = value;
});
}
final _$graphSelectedDateExpensesAtom =
Atom(name: 'MobxStoreBase.graphSelectedDateExpenses');
@override
Map<ViewType, List<Expense>> get graphSelectedDateExpenses {
_$graphSelectedDateExpensesAtom.reportRead();
return super.graphSelectedDateExpenses;
}
@override
set graphSelectedDateExpenses(Map<ViewType, List<Expense>> value) {
_$graphSelectedDateExpensesAtom
.reportWrite(value, super.graphSelectedDateExpenses, () {
super.graphSelectedDateExpenses = value;
});
}
final _$graphSelectedDateAtom = Atom(name: 'MobxStoreBase.graphSelectedDate');
@override
DateTime get graphSelectedDate {
_$graphSelectedDateAtom.reportRead();
return super.graphSelectedDate;
}
@override
set graphSelectedDate(DateTime value) {
_$graphSelectedDateAtom.reportWrite(value, super.graphSelectedDate, () {
super.graphSelectedDate = value;
});
}
final _$selectedDateAtom = Atom(name: 'MobxStoreBase.selectedDate');
@override
DateTime get selectedDate {
_$selectedDateAtom.reportRead();
return super.selectedDate;
}
@override
set selectedDate(DateTime value) {
_$selectedDateAtom.reportWrite(value, super.selectedDate, () {
super.selectedDate = value;
});
}
final _$tagsAtom = Atom(name: 'MobxStoreBase.tags');
@override
List<Tag> get tags {
_$tagsAtom.reportRead();
return super.tags;
}
@override
set tags(List<Tag> value) {
_$tagsAtom.reportWrite(value, super.tags, () {
super.tags = value;
});
}
final _$editTagAtom = Atom(name: 'MobxStoreBase.editTag');
@override
Tag get editTag {
_$editTagAtom.reportRead();
return super.editTag;
}
@override
set editTag(Tag value) {
_$editTagAtom.reportWrite(value, super.editTag, () {
super.editTag = value;
});
}
final _$thumbnailExpenseAtom = Atom(name: 'MobxStoreBase.thumbnailExpense');
@override
Expense get thumbnailExpense {
_$thumbnailExpenseAtom.reportRead();
return super.thumbnailExpense;
}
@override
set thumbnailExpense(Expense value) {
_$thumbnailExpenseAtom.reportWrite(value, super.thumbnailExpense, () {
super.thumbnailExpense = value;
});
}
final _$limitMapAtom = Atom(name: 'MobxStoreBase.limitMap');
@override
Map<ViewType, double> get limitMap {
_$limitMapAtom.reportRead();
return super.limitMap;
}
@override
set limitMap(Map<ViewType, double> value) {
_$limitMapAtom.reportWrite(value, super.limitMap, () {
super.limitMap = value;
});
}
final _$isAutomaticAtom = Atom(name: 'MobxStoreBase.isAutomatic');
@override
bool get isAutomatic {
_$isAutomaticAtom.reportRead();
return super.isAutomatic;
}
@override
set isAutomatic(bool value) {
_$isAutomaticAtom.reportWrite(value, super.isAutomatic, () {
super.isAutomatic = value;
});
}
final _$isUseLimitAtom = Atom(name: 'MobxStoreBase.isUseLimit');
@override
bool get isUseLimit {
_$isUseLimitAtom.reportRead();
return super.isUseLimit;
}
@override
set isUseLimit(bool value) {
_$isUseLimitAtom.reportWrite(value, super.isUseLimit, () {
super.isUseLimit = value;
});
}
final _$editingAtom = Atom(name: 'MobxStoreBase.editing');
@override
Set<Expense> get editing {
_$editingAtom.reportRead();
return super.editing;
}
@override
set editing(Set<Expense> value) {
_$editingAtom.reportWrite(value, super.editing, () {
super.editing = value;
});
}
final _$currentIndexAtom = Atom(name: 'MobxStoreBase.currentIndex');
@override
int get currentIndex {
_$currentIndexAtom.reportRead();
return super.currentIndex;
}
@override
set currentIndex(int value) {
_$currentIndexAtom.reportWrite(value, super.currentIndex, () {
super.currentIndex = value;
});
}
final _$firstTimeAtom = Atom(name: 'MobxStoreBase.firstTime');
@override
bool get firstTime {
_$firstTimeAtom.reportRead();
return super.firstTime;
}
@override
set firstTime(bool value) {
_$firstTimeAtom.reportWrite(value, super.firstTime, () {
super.firstTime = value;
});
}
final _$introDoneAtom = Atom(name: 'MobxStoreBase.introDone');
@override
bool get introDone {
_$introDoneAtom.reportRead();
return super.introDone;
}
@override
set introDone(bool value) {
_$introDoneAtom.reportWrite(value, super.introDone, () {
super.introDone = value;
});
}
final _$deleteTagAsyncAction = AsyncAction('MobxStoreBase.deleteTag');
@override
Future<void> deleteTag(Tag tagToDelete, {bool setDatabase = false}) {
return _$deleteTagAsyncAction
.run(() => super.deleteTag(tagToDelete, setDatabase: setDatabase));
}
final _$setLimitAsyncAction = AsyncAction('MobxStoreBase.setLimit');
@override
Future<void> setLimit(ViewType viewType, double limit,
{bool setDatabase = false}) {
return _$setLimitAsyncAction
.run(() => super.setLimit(viewType, limit, setDatabase: setDatabase));
}
final _$automaticSetAsyncAction = AsyncAction('MobxStoreBase.automaticSet');
@override
Future<void> automaticSet({bool setDatabase = false}) {
return _$automaticSetAsyncAction
.run(() => super.automaticSet(setDatabase: setDatabase));
}
final _$setUseLimitAsyncAction = AsyncAction('MobxStoreBase.setUseLimit');
@override
Future<void> setUseLimit(bool inputUseLimit, {bool setDatabase = false}) {
return _$setUseLimitAsyncAction
.run(() => super.setUseLimit(inputUseLimit, setDatabase: setDatabase));
}
final _$MobxStoreBaseActionController =
ActionController(name: 'MobxStoreBase');
@override
void addExpense(Expense expense, {bool setDatabase = false}) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.addExpense');
try {
return super.addExpense(expense, setDatabase: setDatabase);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void addAllExpenses(List<Expense> inputExpenses) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.addAllExpenses');
try {
return super.addAllExpenses(inputExpenses);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void deleteExpense(Expense expense) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.deleteExpense');
try {
return super.deleteExpense(expense);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void deleteAll() {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.deleteAll');
try {
return super.deleteAll();
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void updateExpense(Expense expense, {bool setDatabase = false}) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.updateExpense');
try {
return super.updateExpense(expense, setDatabase: setDatabase);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void updateSelectedDate(DateTime inputSelectedDate) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.updateSelectedDate');
try {
return super.updateSelectedDate(inputSelectedDate);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void addTag(Tag newTag, {bool setDatabase = false}) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.addTag');
try {
return super.addTag(newTag, setDatabase: setDatabase);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void addAllTags(List<Tag> inputTags) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.addAllTags');
try {
return super.addAllTags(inputTags);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void deleteAllTags() {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.deleteAllTags');
try {
return super.deleteAllTags();
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void updateTag(Tag tagToUpdate, {bool setDatabase = false}) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.updateTag');
try {
return super.updateTag(tagToUpdate, setDatabase: setDatabase);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
Tag searchTag(Tag tagToUpdate) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.searchTag');
try {
return super.searchTag(tagToUpdate);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
dynamic setThumbnailExpense(Expense newExpense) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.setThumbnailExpense');
try {
return super.setThumbnailExpense(newExpense);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
void updateGraphSelectedDate(DateTime inputSelectedDate) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.updateGraphSelectedDate');
try {
return super.updateGraphSelectedDate(inputSelectedDate);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
double getSelectedDateTotalPrice([DateTime inputSelectedDate]) {
final _$actionInfo = _$MobxStoreBaseActionController.startAction(
name: 'MobxStoreBase.getSelectedDateTotalPrice');
try {
return super.getSelectedDateTotalPrice(inputSelectedDate);
} finally {
_$MobxStoreBaseActionController.endAction(_$actionInfo);
}
}
@override
String toString() {
return '''
expenses: ${expenses},
selectedDateExpenses: ${selectedDateExpenses},
graphSelectedDateExpenses: ${graphSelectedDateExpenses},
graphSelectedDate: ${graphSelectedDate},
selectedDate: ${selectedDate},
tags: ${tags},
editTag: ${editTag},
thumbnailExpense: ${thumbnailExpense},
limitMap: ${limitMap},
isAutomatic: ${isAutomatic},
isUseLimit: ${isUseLimit},
editing: ${editing},
currentIndex: ${currentIndex},
firstTime: ${firstTime},
introDone: ${introDone}
''';
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/widgets/expenseTile.dart | import 'package:expensePlus/models/tag.dart';
import 'package:expensePlus/pages/tagDetailPage.dart';
import 'package:flutter/material.dart';
import 'package:expensePlus/models/expense.dart';
import 'package:expensePlus/expenses_store.dart';
class ExpenseTile extends StatefulWidget {
Expense expense;
bool isThumbnail;
ExpenseTile({
this.expense,
this.isThumbnail,
}) {
expense ??= Expense.empty();
}
@override
_ExpenseTileState createState() => _ExpenseTileState();
}
class _ExpenseTileState extends State<ExpenseTile> {
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(6),
color: Colors.grey[50],
boxShadow: [
BoxShadow(
color: Colors.black54,
offset: Offset(0, 1.5),
blurRadius: 1,
)
]),
child: Row(
children: <Widget>[
// Container(
// width: 5,
// height: 92,
// child: Column(
// children: widget.expense.tags
// .map(
// (tag) => Expanded(
// child: Container(color: tag.color),
// ),
// )
// .toList(),
// ),
// ),
Expanded(
child: expenseTile(
widget.expense,
),
),
],
),
);
}
Widget expenseTile(Expense expense) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 4),
width: double.infinity,
height: 80,
child: Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
//BUTTON SECTION
// buttonsHeader(),
//TEXT SECTION
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(flex: 5, child: expenseNameText(expense)),
Expanded(flex: 3, child: tagRow(expense)),
],
),
),
),
priceSection(expense)
],
),
);
}
Widget expenseNameText(Expense expense) {
return Container(
child: Center(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Align(
alignment: FractionalOffset.centerLeft,
child: Text(
expense?.name ?? '',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
),
),
),
);
}
Widget tagRow(Expense expense) {
if (expense.tags == null || expense.tags.isEmpty) {
expense.tags = [Tag.otherTag];
}
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: expense.tags.map((tag) {
return GestureDetector(
onTap: () => MobxStore.st.navigatorKey.currentState.push(
MaterialPageRoute(
builder: (_) => TagDetailPage(tag),
),
),
child: Container(
padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 6),
margin: const EdgeInsets.symmetric(vertical: 2, horizontal: 3),
constraints: BoxConstraints(
maxWidth: 150,
),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: tag.color,
blurRadius: 2,
offset: Offset(0, 1),
)
],
borderRadius: BorderRadius.circular(3),
border: Border.all(
color: tag.color,
width: 1,
)),
child: Text(
tag.name,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: tag.color,
),
),
),
);
}).toList(),
));
}
Widget priceSection(Expense expense) {
if (expense.prices == null) {
expense.prices = [0];
}
double totalPrice = expense?.getTotalExpense() ?? 0;
return Container(
padding: EdgeInsets.symmetric(vertical: 6, horizontal: 8),
child: Row(
children: <Widget>[
SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Builder(
builder: (bc) {
if (expense.prices.length <= 1) return Container();
return Column(
children: expense.prices.map((price) {
return Container(
constraints: BoxConstraints(
minWidth: 30,
minHeight: 30,
),
padding: const EdgeInsets.symmetric(
vertical: 3, horizontal: 4),
margin: const EdgeInsets.symmetric(
vertical: 4, horizontal: 6),
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black87,
blurRadius: 1,
offset: Offset(0, 1),
)
],
color: Colors.grey[100],
borderRadius: BorderRadius.circular(50),
),
child: Center(
child: Text(
price.toString(),
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w500,
color: Colors.blue[700],
),
),
),
);
}).toList(),
);
},
),
),
SizedBox(
width: 5,
),
Container(
constraints: BoxConstraints(
minWidth: 70,
minHeight: 70,
),
padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 5),
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black87,
blurRadius: 1,
offset: Offset(0, 1),
)
],
borderRadius: BorderRadius.circular(50),
color: Colors.grey[100],
),
child: Center(
child: Text(
totalPrice.toString(),
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Colors.blue[700],
),
),
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/widgets/tagTile.dart | import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:expensePlus/expenses_store.dart';
import 'package:expensePlus/models/tag.dart';
import 'package:expensePlus/pages/tagDetailPage.dart';
class TagTile extends StatelessWidget {
const TagTile({
Key key,
@required this.tag,
@required this.editButtonCallback,
}) : super(key: key);
final Tag tag;
final Function editButtonCallback;
@override
Widget build(BuildContext context) {
final double width = MediaQuery.of(context).size.width;
return GestureDetector(
onTap: () => MobxStore.st.navigatorKey.currentState.push(
MaterialPageRoute(
builder: (_) => TagDetailPage(tag),
),
),
child: Slidable(
actionPane: SlidableStrechActionPane(),
direction: Axis.horizontal,
actionExtentRatio: 0.5,
actions: <Widget>[
IconSlideAction(
caption: 'Edit',
color: Colors.blue,
icon: Icons.edit,
onTap: () => editButtonPressed(),
),
],
secondaryActions: <Widget>[
IconSlideAction(
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
onTap: () => deleteButtonPressed(),
),
],
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(child: Center(child: tagContainer(tag.name, width))),
Expanded(child: Center(child: tagContainer(tag.shorten, width))),
],
),
),
);
}
Widget tagContainer(String str, double width) {
return Container(
margin: EdgeInsets.symmetric(
vertical: 5,
),
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
border: Border.all(color: tag.color, width: 1.5),
borderRadius: BorderRadius.circular(3),
),
child: Text(
str,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 18,
letterSpacing: 1,
color: tag.color,
),
),
);
}
deleteButtonPressed() async {
await MobxStore.st.deleteTag(
tag,
setDatabase: true,
);
Fluttertoast.showToast(
msg: 'Tag has been deleted',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.red[400],
textColor: Colors.white,
fontSize: 14.0,
);
}
editButtonPressed() {
MobxStore.st.editTag = tag;
editButtonCallback();
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/utilities/dummy_data.dart | import 'package:flutter/material.dart';
import 'package:expensePlus/models/expense.dart';
import '../models/tag.dart';
class DummyData {
static List<Expense> expenses() {
return [
new Expense(
name: 'Taxi',
tags: [
new Tag(
name: 'travel', hexCode: Colors.purple[400].value, shorten: 't'),
],
prices: [25.0],
text: 'Taxi .t 15',
date: DateTime(
DateTime.now().year,
DateTime.now().month,
DateTime.now().day,
),
),
new Expense(
name: 'Bowling',
tags: [
new Tag(name: 'bowling', hexCode: Colors.black.value, shorten: 'b'),
new Tag(
name: 'friends', hexCode: Colors.red[400].value, shorten: 'f'),
],
prices: [15.0, 5.0],
text: 'Bowling .b .f 30 20',
date: DateTime(
DateTime.now().year,
DateTime.now().month,
DateTime.now().day,
),
),
new Expense(
name: 'Hangout',
tags: [
new Tag(
name: 'friends', hexCode: Colors.red[400].value, shorten: 'f'),
],
prices: [45],
text: 'Hangout .bowling 45',
date: DateTime(
DateTime.now().year,
DateTime.now().month,
DateTime.now().day,
).add(
Duration(
days: 1,
),
),
),
];
}
static List<Tag> tags() {
return [
new Tag(name: 'travel', hexCode: Colors.purple[400].value, shorten: 't'),
new Tag(name: 'bowling', hexCode: Colors.black.value, shorten: 'b'),
new Tag(name: 'friends', hexCode: Colors.red[400].value, shorten: 'f'),
];
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/utilities/regex.dart | import 'package:expensePlus/expenses_store.dart';
import 'package:expensePlus/models/tag.dart';
import 'package:expensePlus/models/expense.dart';
class Regex {
//REGEX
static RegExp priceRegex =
RegExp(r'((?<=\s|^)\d+\.*\d*(?=\s|$))', caseSensitive: false);
static RegExp tagRegex =
RegExp(r'(?<=^|\s)[\.#]([^\.#\s]+)', caseSensitive: false);
static RegExp limitRegex = RegExp(r'(-lim+)', caseSensitive: false);
static RegExp dateRegex = RegExp(
r'[!](([0-9]+)+([a-z]+))|[!]([a-z]+)|[!](\d+\.*\d*)',
caseSensitive: false);
static DateTime dateFormatter(Map<String, dynamic> map) {
DateTime now =
DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);
int howMany = map['howMany'];
switch (map['keyword']) {
case 'tommorrow':
case 'tom':
return now.add(Duration(days: 1));
case 'today':
case 'tod':
case 't':
return now;
case 'yesterday':
case 'yest':
case 'y':
return now.subtract(Duration(days: 1));
case 'lastweek':
return now.subtract(Duration(days: 7));
case 'weeks':
case 'week':
case 'w':
return now.add(Duration(days: 7 * howMany));
case 'days':
case 'day':
case 'd':
return now.add(Duration(days: 1 * howMany));
}
return null;
}
///input [str] for regex
/// returns tags, prices and isLimit
static Future<Expense> doRegex(
String str,
DateTime selectedDate,
bool submitted,
) async {
String text = str;
String name;
List<Tag> tags = new List();
List<double> prices = new List();
bool limit;
DateTime date;
str = str.trim();
priceRegex.allMatches(str).forEach(
(el) {
double price = double.parse(double.parse(el[1]).toStringAsFixed(2));
final upperLimit = 99999;
if (price > upperLimit) {
while (price > upperLimit) price = (price / 10).floor().toDouble();
}
prices.add(price);
},
);
str = str.replaceAll(priceRegex, '');
dateRegex.allMatches(str).forEach((el) {
//#29 #9.12 style
if (el[5] != null) {
final map = el[5].split('.').asMap();
int month;
if (map[1] != null) {
if (map[1].isNotEmpty) month = int.parse(map[1]);
}
month ??= DateTime.now().month;
int day = int.parse(map[0]);
date = new DateTime(
DateTime.now().year,
month,
day,
);
//todo wrong date entered handle it
if (date.month != month || date.day != day) {
date = selectedDate;
}
} else {
var howMany = el[2] != null ? int.parse(el[2]) : 1;
var keyword = el[3] ?? el[4];
Map<String, dynamic> map = {
'keyword': keyword,
'howMany': howMany,
};
date = dateFormatter(map);
}
});
date ??= selectedDate;
str = str.replaceAll(dateRegex, '');
//TAG
if (tagRegex.allMatches(str).isEmpty) tags = [Tag.other()];
for (final el in tagRegex.allMatches(str)) {
String name = el[1];
Tag tag = MobxStore.st.getTagByName(name);
if (tag == null) {
tag = new Tag(
name: name,
);
if (submitted) MobxStore.st.addTag(tag, setDatabase: true);
}
tags.add(tag);
}
str = str.replaceAll(tagRegex, '');
limitRegex.allMatches(str).forEach((el) {
if (el[1] != null) limit = false;
str = str.replaceRange(el.start, el.end, '');
});
str = str.replaceAll(limitRegex, '');
str = str.replaceAll(new RegExp(r'[\.!#]+'), '');
str = str.trim();
prices = prices.isEmpty ? [0] : prices;
limit ??= true;
tags = tags.toSet().toList();
name = str.isEmpty || str == null ? tags.map((e) => e.name).join(' ') : str;
if (tags.length > 5) tags = tags.sublist(0, 5);
Expense rv = new Expense(
name: name,
tags: tags,
prices: prices,
text: text,
limit: limit,
date: date,
);
return rv;
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/utilities/richText.dart | library rich_text_controller;
import 'package:expensePlus/expenses_store.dart';
import 'package:expensePlus/utilities/regex.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class RichTextController extends TextEditingController {
final Map<RegExp, TextStyle> patternMap;
final Function(List<String> match) onMatch;
final double kFontSize = 20;
RichTextController(this.patternMap, {this.onMatch})
: assert(patternMap != null);
@override
TextSpan buildTextSpan({TextStyle style, bool withComposing}) {
List<TextSpan> children = new List();
List<RegExpMatch> matches = new List();
for (final regex in patternMap.keys) {
final matchesNeedsAdd = regex.allMatches(text);
if (matchesNeedsAdd.isNotEmpty)
matches = [...matches, ...matchesNeedsAdd];
}
matches.sort((a, b) => a.start - b.start);
int start = 0, end;
for (final match in matches) {
end = match.start;
children.add(
TextSpan(
style: TextStyle(color: Colors.black, fontSize: kFontSize),
text: text.substring(start, end),
),
);
children.add(
TextSpan(
style: match.pattern != Regex.tagRegex
? patternMap[match.pattern].merge(
TextStyle(
fontSize: kFontSize,
),
)
: TextStyle(
fontSize: kFontSize,
color: MobxStore.st.getTagByName(match[1])?.color ??
patternMap[match.pattern].color,
),
text: text.substring(match.start, match.end),
),
);
start = match.end;
}
children.add(TextSpan(
style: TextStyle(color: Colors.black, fontSize: kFontSize),
text: text.substring(start),
));
if (children.isNotEmpty) return TextSpan(children: children);
return TextSpan(style: TextStyle(color: Colors.black, fontSize: kFontSize));
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/database/tag_provider.dart | import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sembast/sembast.dart';
import 'package:sembast/sembast_io.dart';
import 'package:expensePlus/database/expense_provider.dart';
import 'package:expensePlus/expenses_store.dart';
import 'package:expensePlus/models/expense.dart';
import 'package:expensePlus/models/tag.dart';
class TagProvider {
static Database _database;
static final TagProvider db = TagProvider._();
TagProvider._();
static const String TAG_STORE_NAME = 'tags';
final _tagStore = intMapStoreFactory.store(TAG_STORE_NAME);
Future<Database> get database async {
if (_database != null) return _database;
// get the application documents directory
var dir = await getApplicationDocumentsDirectory();
// make sure it exists
await dir.create(recursive: true);
// build the database path
var dbPath = join(dir.path, 'tag_database.db');
// open the database
_database = await databaseFactoryIo.openDatabase(dbPath);
return _database;
}
/// Insert expense on database and returns as int
Future<Tag> createTag(String name, String shorten, int hexCode) async {
if (shorten.isEmpty) shorten = name;
Tag newTag = new Tag(
name: name,
shorten: shorten,
color: Color(hexCode),
hexCode: hexCode,
);
//look for same name or shorten
final map = (await Future.wait([
searchTag(name),
searchTag(shorten),
]))
.asMap();
var oldTag = map[0] ?? map[1];
if (oldTag != null) {
newTag.id = oldTag.id;
await update(newTag);
} else {
int key = await addTag(newTag);
newTag.id = key;
}
return newTag;
}
Future<int> addTag(Tag newTag) async {
var key = await _tagStore.add(
await database,
newTag.toJson(),
);
newTag.id = key;
update(newTag);
print('DATABASE:\ttag added ${newTag.name}');
return key;
}
Future update(Tag newTag) async {
_tagStore.record(newTag.id).update(await database, newTag.toJson());
print('DATABASE:\t tag updated $newTag');
}
Future delete(Tag newTag) async {
await _tagStore.delete(await database,
finder: Finder(
filter: Filter.byKey(newTag.id),
));
await getAllTags().then(
(value) => print('DATABASE:\ttag deleted => $value'),
);
}
Future deleteAll() async {
await _tagStore.delete(
await database,
);
print('DATABASE:\tall tags deleted');
}
Future<List<Tag>> getAllTags([bool isGetExpenses = false]) async {
final records = await _tagStore.find(
await database,
);
List<Tag> rv;
rv = [];
if (records.isNotEmpty) {
rv = records.map(
(record) {
Tag tag = Tag.fromJson(record.value);
tag.id = record.key;
return tag;
},
).toList();
}
if (isGetExpenses) {
if (MobxStore.st.tags.isEmpty) MobxStore.st.addAllTags(rv);
List<Expense> expenses = await ExpenseProvider.db.getAllExpenses();
if (expenses.isEmpty) {
print('Database value ==> is empty');
} else {
MobxStore.st.addAllExpenses(expenses);
}
}
return rv;
}
Future<Tag> searchTag(String str) async {
final tags = await getAllTags();
if (tags == null) return null;
return tags
.where(
(element) => element.name == str || element.shorten == str,
)
.toList()
.asMap()[0];
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/database/settings_provider.dart | import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sembast/sembast.dart';
import 'package:sembast/sembast_io.dart';
import 'package:expensePlus/pages/graphPage.dart';
class SettingsProvider {
var needsUpdate = false;
static Database _database;
static final SettingsProvider db = SettingsProvider._();
SettingsProvider._();
static const String SETTINGS_STORE_NAME = 'settings';
final _settingsStore = intMapStoreFactory.store(SETTINGS_STORE_NAME);
Future<Database> get database async {
if (_database != null) return _database;
// get the application documents directory
var dir = await getApplicationDocumentsDirectory();
// make sure it exists
await dir.create(recursive: true);
// build the database path
var dbPath = join(dir.path, 'limit_database.db');
// open the database
_database = await databaseFactoryIo.openDatabase(dbPath);
return _database;
}
/// Insert limit on database and returns as int
Future<void> updateLimit(Map<ViewType, double> limitMap) async {
await _settingsStore.record(0).put(
await database,
{
'day': limitMap[ViewType.Day],
'week': limitMap[ViewType.Week],
'month': limitMap[ViewType.Month],
},
);
}
/// Insert limit on database and returns as int
Future<Map<ViewType, double>> getLimit() async {
final val = await _settingsStore.record(0).get(
await database,
);
if (val == null) {
await updateLimit({
ViewType.Day: null,
ViewType.Week: null,
ViewType.Month: null,
});
return <ViewType, double>{
ViewType.Day: null,
ViewType.Week: null,
ViewType.Month: null,
};
}
return <ViewType, double>{
ViewType.Day: val['day'],
ViewType.Week: val['week'],
ViewType.Month: val['month'],
};
}
Future<void> updateIsAutomatic(bool isAutomatic) async {
await _settingsStore.record(1).put(
await database,
{
'isAutomatic': isAutomatic,
},
);
}
Future<bool> getIsAutomatic() async {
final val = await _settingsStore.record(1).get(
await database,
);
if (val == null) {
await updateIsAutomatic(true);
return true;
}
return val['isAutomatic'];
}
//USE LIMIT
Future<void> updateUseLimit(bool useLimit) async {
await _settingsStore.record(2).put(
await database,
{
'useLimit': useLimit,
},
);
}
Future<bool> getUseLimit() async {
final val = await _settingsStore.record(2).get(
await database,
);
if (val == null) {
await updateUseLimit(false);
return false;
}
return val['useLimit'];
}
Future<bool> isFirstTime() async {
final val = await _settingsStore.record(3).get(
await database,
);
if (val == null) {
await _settingsStore.record(3).put(
await database,
{
'firstTime': false,
},
);
return true;
}
return false;
}
Future<void> resetFirstTime() async {
await _settingsStore.record(3).delete(
await database,
);
}
Future<String> getDateStyle() async {
final val = await _settingsStore.record(4).get(
await database,
);
if (val == null) {
await _settingsStore.record(4).put(
await database,
{
'dateStyle': 'dd/mm',
},
);
return 'dd/mm';
}
return val['dateStyle'];
}
Future<void> changeDateStyle(String style) async {
await _settingsStore.record(4).update(
await database,
{
'dateStyle': '$style',
},
);
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/database/expense_provider.dart | import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sembast/sembast.dart';
import 'package:sembast/sembast_io.dart';
import 'package:expensePlus/models/expense.dart';
import 'package:expensePlus/models/expense.dart';
import 'package:expensePlus/models/tag.dart';
class ExpenseProvider {
var needsUpdate = false;
static Database _database;
static final ExpenseProvider db = ExpenseProvider._();
ExpenseProvider._();
static const String EXPENSES_STORE_NAME = 'expenses';
final _expenseStore = intMapStoreFactory.store(EXPENSES_STORE_NAME);
Future<Database> get database async {
if (_database != null) return _database;
// get the application documents directory
var dir = await getApplicationDocumentsDirectory();
// make sure it exists
await dir.create(recursive: true);
// build the database path
var dbPath = join(dir.path, 'expense_database.db');
// open the database
_database = await databaseFactoryIo.openDatabase(dbPath);
return _database;
}
/// Insert expense on database and returns as int
Future<int> createExpense(Expense newExpense) async {
var key = await _expenseStore.add(
await database,
newExpense.toJson(),
);
newExpense.id = key;
await update(newExpense);
print('DATABASE:\texpense added ${newExpense.name}');
return key;
}
Future update(Expense newExpense) async {
_expenseStore
.record(newExpense.id)
.update(await database, newExpense.toJson());
print('DATABASE:\texpense updated ');
}
Future updateTags(Tag tag) async {
var records = await _expenseStore.find(await database);
for (var record in records) {
var exp = Expense.fromJson(record.value);
exp.tags = exp.tags.map((e) {
if (tag.name == tag.name) {
needsUpdate = true;
return tag;
}
return tag;
}).toList();
update(exp);
}
}
Future delete(Expense newExpense) async {
await _expenseStore.delete(await database,
finder: Finder(
filter: Filter.byKey(newExpense.id),
));
await getAllExpenses().then(
(value) => print('DATABASE:\texpense deleted => $value'),
);
}
Future deleteAll() async {
await _expenseStore.delete(
await database,
);
print('DATABASE:\tall expenses deleted');
}
Future<List<Expense>> getAllExpenses() async {
final records = await _expenseStore.find(
await database,
);
if (records.isEmpty) return [];
List<Expense> rv = records.map(
(record) {
Expense exp = Expense.fromJson(record.value);
exp.id = record.key;
return exp;
},
).toList();
return rv;
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/pages/tagsPage.dart | import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:expensePlus/database/tag_provider.dart';
import 'package:expensePlus/expenses_store.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:expensePlus/models/tag.dart';
import 'package:expensePlus/widgets/tagTile.dart';
class TagsPage extends HookWidget {
BuildContext context;
ValueNotifier<Color> currentColor;
ValueNotifier<String> buttonName;
TextEditingController nameController = new TextEditingController();
TextEditingController shortenController = new TextEditingController();
final store = MobxStore.st;
FocusNode focusNode;
final Color kDefaultColor = Colors.blue[500];
FToast fToast;
ValueNotifier<String> conflict, confirmButtonName;
@override
Widget build(BuildContext context) {
if (fToast == null) fToast = new FToast(context);
currentColor = useState(Color(kDefaultColor.value));
this.context = context;
double kHeight = 40.0;
buttonName = useState('');
conflict = useState(null);
confirmButtonName = useState('Add');
useEffect(() {
store.editTag = null;
nameController.text = '';
shortenController.text = '';
return () {};
}, []);
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Container(
width: MediaQuery.of(context).size.width,
color: Color(0xfff9f9f9),
child: Column(
children: <Widget>[
Stack(
children: <Widget>[
Container(
width: double.infinity,
height: kHeight + 20,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
),
width: double.infinity,
height: kHeight,
),
Positioned.fill(
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
padding: EdgeInsets.symmetric(
vertical: 10,
),
decoration: BoxDecoration(
color: kDefaultColor,
borderRadius: BorderRadius.circular(5)),
width: 150,
height: 50,
child: Center(
child: Text(
'ADD TAG',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 18,
letterSpacing: 1.5,
color: Colors.white.withOpacity(0.8)),
),
),
),
),
),
],
),
tagAdder(),
Stack(
children: <Widget>[
Container(
height: kHeight + 20,
),
Positioned.fill(
top: 25,
child: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
),
),
),
Positioned.fill(
child: Align(
alignment: Alignment.topCenter,
child: Container(
padding: EdgeInsets.symmetric(
vertical: 10,
),
decoration: BoxDecoration(
color: kDefaultColor,
borderRadius: BorderRadius.circular(5)),
width: 150,
height: 50,
child: Center(
child: Text(
'TAGS',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 18,
letterSpacing: 1.5,
color: Colors.white.withOpacity(0.8)),
),
),
),
),
),
],
),
Observer(
builder: (_) {
return Container(
width: double.infinity,
height: store.tags.isNotEmpty ? null : 0,
decoration: BoxDecoration(
color: Colors.grey[200],
),
child: Text(
'Hint: Swipe Right To Edit, Left To Delete And Click A Tag for more info',
style: TextStyle(
fontSize: 12, fontWeight: FontWeight.w200),
),
);
},
),
tagList(),
],
),
),
),
),
);
}
Widget tagAdder() {
return Observer(
builder: (_) {
store.editTag;
store.tags;
const double kSize = 40;
return Container(
margin: const EdgeInsets.symmetric(vertical: 20),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 8, vertical: 25),
width: 200,
child: TextField(
textInputAction: TextInputAction.send,
controller: nameController,
decoration: InputDecoration(
hintText: '(e.g. travel)',
labelText: 'Tag Name',
floatingLabelBehavior: FloatingLabelBehavior.auto),
onChanged: (str) {
buttonName.value = str;
conflictChecker(str);
focusNode.requestFocus();
},
),
),
),
Expanded(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 8, vertical: 25),
width: 200,
child: TextField(
focusNode: focusNode,
controller: shortenController,
decoration: InputDecoration(
labelText: 'Short Name',
hintText: '(e.g. t)',
floatingLabelBehavior: FloatingLabelBehavior.auto,
),
onChanged: (str) {
conflictChecker(str);
},
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
FlatButton(
onPressed: changeTagColorPressed,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
side: BorderSide(color: currentColor.value)),
hoverColor: currentColor.value,
child: Text('Change Tag Color'),
color: Colors.white,
textColor: currentColor.value,
),
FlatButton(
color: conflict.value != null
? Colors.grey
: currentColor.value.withOpacity(0.1),
onPressed: conflict.value != null
? null
: () async => await addTagButtonPressed(),
splashColor: currentColor.value.withOpacity(0.5),
child: Container(
padding: EdgeInsets.all(3),
child: Row(
children: <Widget>[
Text(
confirmButtonName.value ?? 'Add',
style: TextStyle(
color: conflict.value != null
? Colors.grey
: currentColor.value,
),
),
Icon(
Icons.check_circle_outline,
color: conflict.value != null
? Colors.grey
: currentColor.value,
size: 36,
),
],
),
),
),
Container(
decoration: BoxDecoration(
color: Colors.red[400],
borderRadius: BorderRadius.circular(10),
),
width: store.editTag != null ? null : 0,
child: IconButton(
constraints: BoxConstraints(
maxHeight: kSize,
maxWidth: kSize,
),
onPressed: editCancelPressed,
icon: Icon(
Icons.clear,
color: Colors.white,
),
highlightColor: Colors.red,
),
),
],
),
SizedBox(height: buttonName.value.isEmpty ? 0 : 15),
buttonName.value.isNotEmpty
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Preview:'),
SizedBox(width: 10),
Container(
padding: const EdgeInsets.symmetric(
vertical: 5, horizontal: 6),
margin: const EdgeInsets.symmetric(
vertical: 2, horizontal: 3),
constraints: BoxConstraints(
maxWidth: 150,
),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: currentColor.value,
blurRadius: 2,
offset: Offset(0, 1),
)
],
borderRadius: BorderRadius.circular(3),
border: Border.all(
color: currentColor.value,
width: 1,
)),
child: Text(
buttonName.value,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: currentColor.value,
),
),
),
],
)
: Container(),
SizedBox(height: buttonName.value.isEmpty ? 20 : 10),
],
),
);
},
);
}
Widget tagList() {
return Observer(builder: (_) {
return SingleChildScrollView(
child: Container(
width: double.infinity,
constraints: BoxConstraints(minHeight: 300),
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.grey[200],
),
child: store.tags.isEmpty
? noTagsText()
: Column(
children: store.tags
.map((tag) => TagTile(
tag: tag,
editButtonCallback: editButtonPressed,
))
.toList(),
),
),
);
});
}
Widget noTagsText() {
return Text(
'No Tag Has Been Added Yet!',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: FontWeight.w500,
letterSpacing: 0.2,
),
);
}
conflictChecker(String str) {
var name = store.getTagByName(str)?.name;
bool isEditing = store.editTag != null,
isFoundAnotherOnStore = name != null && store.editTag?.name != name,
isConflict = conflict.value != null;
if (isEditing && isFoundAnotherOnStore)
//conflict when updating
conflict.value = name;
else if (!isEditing && isFoundAnotherOnStore)
//conflict when adding
conflict.value = name;
else if (isConflict)
//check if value changed
conflict.value = null;
//check if value changed
String oldVal = confirmButtonName.value;
String newVal;
if (conflict.value != null)
newVal = 'Conflict';
else if (isEditing)
newVal = 'Update';
else
newVal = 'Add';
if (oldVal != newVal) {
confirmButtonName.value = newVal;
}
}
// #region LOGIC
Future addTagButtonPressed() async {
if (conflict.value != null) return;
if (nameController.text.isEmpty) return;
//DB and STORE
Tag tag;
String msg = 'Tag has been added';
Color color = Colors.green[400];
bool update = false;
if (conflict.value != null || store.editTag != null) {
msg = 'Tag has been updated';
color = Colors.blue[400];
update = true;
}
if (!update)
tag = await TagProvider.db.createTag(
nameController.text,
shortenController.text,
currentColor.value.value,
);
else
tag = new Tag(
name: nameController.text,
shorten: shortenController.text,
hexCode: currentColor.value.value,
);
Fluttertoast.showToast(
msg: msg,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: color,
textColor: Colors.white,
fontSize: 16.0,
);
if (update) {
tag.id = store.editTag.id;
MobxStore.st.updateTag(tag, setDatabase: true);
} else {
MobxStore.st.addTag(tag);
}
store.editTag = null;
confirmButtonName.value = 'Add';
currentColor.value = Color(kDefaultColor.value);
buttonName.value = '';
nameController.text = '';
shortenController.text = '';
FocusScope.of(context).unfocus();
}
void changeTagColorPressed() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
titlePadding: const EdgeInsets.all(0.0),
contentPadding: const EdgeInsets.all(0.0),
content: SingleChildScrollView(
child: MaterialPicker(
pickerColor: currentColor.value,
onColorChanged: (color) {
currentColor.value = color;
Navigator.pop(context);
FocusScope.of(context).unfocus();
},
enableLabel: false,
),
),
);
},
);
}
editButtonPressed() {
nameController.text = store.editTag.name;
shortenController.text = store.editTag.shorten;
currentColor.value = store.editTag.color;
buttonName.value = store.editTag.name;
confirmButtonName.value = 'Update';
}
editCancelPressed() {
nameController.text = '';
shortenController.text = '';
currentColor.value = kDefaultColor;
buttonName.value = '';
confirmButtonName.value = 'Add';
store.editTag = null;
}
// #endregion
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/pages/graphPage.dart | import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:expensePlus/expenses_store.dart';
import 'package:expensePlus/models/tag.dart';
import 'package:expensePlus/pages/tagDetailPage.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
enum ViewType { Day, Week, Month }
class GraphPage extends HookWidget {
CalendarController calendarController = new CalendarController();
final store = MobxStore.st;
TabController _controller;
// void initState() {}
@override
Widget build(BuildContext context) {
_controller = useTabController(initialLength: 3);
return Scaffold(
body: Container(
color: const Color(0xfff9f9f9),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
calendar(),
graph(),
],
),
),
),
);
}
// #region CALENDAR
Widget calendar() {
return Observer(builder: (_) {
store.selectedDate; //for update
store.tags;
store.expenses;
return TableCalendar(
calendarController: calendarController,
startingDayOfWeek: StartingDayOfWeek.monday,
rowHeight: 55,
initialSelectedDay: store.graphSelectedDate ??
DateTime(
DateTime.now().year,
DateTime.now().month,
DateTime.now().day,
),
availableGestures: AvailableGestures.horizontalSwipe,
headerStyle: HeaderStyle(
formatButtonVisible: false,
),
onDaySelected: (day, events) {
store.updateGraphSelectedDate(day);
store.updateSelectedDate(day);
_controller.animateTo(0);
},
builders: CalendarBuilders(
selectedDayBuilder: (context, date, events) {
return calendarTile(context, date, events,
textColor: Colors.white, backgroundColor: Colors.blue[200]);
},
todayDayBuilder: (context, date, events) {
return calendarTile(context, date, events,
textColor: Colors.black, backgroundColor: Colors.blue[50]);
},
weekendDayBuilder: (context, date, events) {
return calendarTile(
context,
date,
events,
textColor: Colors.red,
);
},
outsideDayBuilder: (context, date, events) {
return calendarTile(
context,
date,
events,
textColor: date.weekday > 5 ? Colors.red : null,
dateWeight: FontWeight.w200,
expenseWeight: FontWeight.w100,
);
},
outsideWeekendDayBuilder: (context, date, events) {
return calendarTile(
context,
date,
events,
textColor: Colors.red,
dateWeight: FontWeight.w200,
expenseWeight: FontWeight.w100,
);
},
dayBuilder: (context, date, events) {
return calendarTile(
context,
date,
events,
);
},
),
calendarStyle: CalendarStyle(),
);
});
}
Widget calendarTile(
BuildContext context,
DateTime date,
List<dynamic> events, {
Color textColor,
Color backgroundColor,
FontWeight dateWeight,
FontWeight expenseWeight,
}) {
String expenseText = MobxStore.st.getSelectedDateTotalPrice(date) == 0
? ''
: MobxStore.st.getSelectedDateTotalPrice(date).toString();
bool limitextended = false;
bool isUseLimit = store.limitMap[ViewType.Day] != null && store.isUseLimit;
if (isUseLimit)
limitextended = MobxStore.st.getSelectedDateTotalPrice(date) >
store.limitMap[ViewType.Day];
return Container(
margin: EdgeInsets.all(0.3),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(10),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
child: Text(
date.day.toString(),
style: TextStyle(
fontWeight: dateWeight ?? FontWeight.w500,
fontSize: 16,
color: textColor,
),
),
),
Text(
expenseText,
overflow: TextOverflow.fade,
maxLines: 1,
style: TextStyle(
fontWeight: !limitextended
? expenseWeight ?? FontWeight.w300
: FontWeight.w400,
fontSize: !limitextended ? 12 : 13,
color: !limitextended ? Colors.black : Colors.red,
),
),
],
),
);
}
// #endregion
// #region Graph
Widget graph() {
return Observer(builder: (_) {
store.graphSelectedDateExpenses;
store.graphSelectedDate;
store.tags;
store.expenses;
print('All expenses GRAPH=>${store.expenses}');
return Container(
margin: EdgeInsets.symmetric(
vertical: 7,
horizontal: 7,
),
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue[700],
width: 2,
),
borderRadius: BorderRadius.circular(12),
),
child: TabBar(
controller: _controller,
indicatorSize: TabBarIndicatorSize.tab,
indicatorPadding: EdgeInsets.symmetric(horizontal: 20),
indicator: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.blue[100],
),
indicatorWeight: 3,
tabs: [
Tab(
icon: Icon(
Icons.view_day,
color: Colors.blue[700],
),
child: Text(
'Day',
style: TextStyle(
color: Colors.blue[700],
),
),
),
Tab(
icon: Icon(
Icons.view_week,
color: Colors.blue[700],
),
child: Text(
'Week',
style: TextStyle(
color: Colors.blue[700],
),
),
),
Tab(
icon: Icon(
Icons.view_comfy,
color: Colors.blue[700],
),
child: Text(
'Month',
style: TextStyle(
color: Colors.blue[700],
),
),
),
],
),
),
Container(
height: 400,
child: TabBarView(
controller: _controller,
children: <Widget>[
tabViewElement(
ViewType.Day,
),
tabViewElement(
ViewType.Week,
),
tabViewElement(
ViewType.Month,
),
],
),
),
],
),
);
});
}
Widget tabViewElement(ViewType type) {
Map<Tag, double> tags =
store.getTagTotalGraph(store.graphSelectedDateExpenses[type]);
var entries = tags.entries.toList();
var percent;
entries.sort((a, b) => -a.value.compareTo(b.value));
double totalExpenseOfTags = store.getTotalExpenseByView(type);
bool limitextended = false;
bool isUseLimit = store.limitMap[type] != null && store.isUseLimit;
if (isUseLimit) limitextended = totalExpenseOfTags > store.limitMap[type];
Color color = limitextended ? Colors.red[700] : Colors.black;
FontWeight fontWeight = limitextended ? FontWeight.w700 : FontWeight.w500;
double fontSize = limitextended ? 19 : 17;
return SingleChildScrollView(
child: entries.isEmpty
? Container(
height: 100,
child: Center(
child: Text(
'No Expense Found',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: FontWeight.w500,
letterSpacing: 0.2,
),
),
),
)
: Container(
height: 400,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Hint: Click A Tag For More Info',
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w200),
),
Container(
//total expense
height: 50,
width: double.infinity,
margin: EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
border: Border.all(
width: 2,
color: color,
),
),
child: Center(
child: Text(
isUseLimit
? 'Total / Limit : $totalExpenseOfTags / ${store.limitMap[type]}'
: 'Total Expense: $totalExpenseOfTags ',
style: TextStyle(
fontSize: fontSize,
fontWeight: fontWeight,
color: color,
letterSpacing: 1.2,
),
),
),
),
...entries.map((entry) {
var tag = entry.key;
var expenseOfTag = entry.value;
percent = (expenseOfTag / totalExpenseOfTags) * 100;
return graphTile(tag, expenseOfTag, percent);
}).toList(),
],
),
),
);
}
Widget graphTile(Tag tag, double expenseOfTag, double percent) {
return GestureDetector(
onTap: () => MobxStore.st.navigatorKey.currentState.push(
MaterialPageRoute(
builder: (_) => TagDetailPage(tag),
),
),
child: Container(
margin: EdgeInsets.symmetric(vertical: 4),
decoration: BoxDecoration(
color: Colors.grey[200],
),
height: 70,
child: Row(
children: <Widget>[
Container(
width: 15,
decoration: BoxDecoration(
color: tag.color,
),
),
SizedBox(width: 8),
SingleChildScrollView(
child: Container(
constraints: BoxConstraints(maxWidth: 150),
child: Text(
tag.name.toUpperCase(),
style: TextStyle(
letterSpacing: 0.75,
fontSize: 15,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
Spacer(),
Container(
constraints: BoxConstraints(minWidth: 60),
child: Text(
'${percent.toStringAsFixed(2)}%',
style: TextStyle(
letterSpacing: 0.75,
fontSize: 15,
),
),
),
Container(constraints: BoxConstraints(maxWidth: 50)),
Container(
constraints: BoxConstraints(minWidth: 60),
child: Text(
expenseOfTag.toString(),
style: TextStyle(
letterSpacing: 0.75,
fontSize: 15,
),
),
),
],
),
),
);
}
// #endregion Graph
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/pages/introPage.dart | import 'package:expensePlus/expenses_store.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:carousel_slider/carousel_slider.dart';
class IntroPage extends HookWidget {
CarouselController carouselController = CarouselController();
ValueNotifier<int> _current;
ValueNotifier<bool> _resetState;
bool introDone = false;
List<Widget> buttons = new List();
final bool isHelpButton;
IntroPage([this.isHelpButton = false]);
@override
Widget build(BuildContext context) {
_current = useState(0);
_resetState = useState(false);
return introPage(context);
}
List<Widget> imagesList() {
List<String> list = [
'ZERO',
'FIRST',
'SECOND',
'THIRD',
'FOURTH',
'FIFTH',
'SIXTH'
];
return list
.map((str) => Container(
child: Image(
image: AssetImage('assets/$str PAGE.png'),
fit: BoxFit.fitHeight,
),
))
.toList();
}
Widget introPage(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Stack(
children: <Widget>[
Positioned.fill(
child: CarouselSlider.builder(
carouselController: carouselController,
options: CarouselOptions(
height: MediaQuery.of(context).size.height,
viewportFraction: 1.0,
enlargeCenterPage: false,
disableCenter: true,
enableInfiniteScroll: false,
initialPage: 0,
aspectRatio: 1.949,
scrollPhysics: NeverScrollableScrollPhysics(),
onPageChanged: (index, reason) {
_current.value = index;
}),
itemCount: imagesList().length,
itemBuilder: (BuildContext context, int itemIndex) {
return imagesList()[itemIndex];
},
),
),
Positioned(
left: 0,
right: 0,
bottom: 10,
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: carouselButtons(context),
),
navigationDots()
],
),
),
],
),
),
);
}
List<Widget> carouselButtons(BuildContext context) {
final button = (IconData icon, onTap) => GestureDetector(
onTap: onTap,
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.grey[400].withOpacity(0.4),
),
child: Icon(icon),
),
);
if (buttons?.length != 1) {
buttons = [
button(Icons.navigate_before, () => carouselController.previousPage()),
button(Icons.navigate_next, () => carouselController.nextPage()),
];
if (_current.value == imagesList().length - 1) //Last page
buttons[1] = button(
Icons.check,
() {
_resetState.value = !_resetState.value;
if (!isHelpButton) {
buttons = [Text('Loading...')];
Future.delayed(
Duration(milliseconds: 100),
() => MobxStore.st.introDone = true,
);
} else {
Navigator.pop(context, '');
}
},
);
}
return buttons;
}
Widget navigationDots() {
int index = -1;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: imagesList().map((number) {
index++;
return Container(
width: 8.0,
height: 8.0,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _current.value == index
? Colors.white
: Colors.black.withOpacity(0.5),
),
);
}).toList(),
);
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/pages/trackPage.dart | import 'dart:ui';
import 'package:expensePlus/utilities/richText.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:expensePlus/database/expense_provider.dart';
import 'package:expensePlus/expenses_store.dart';
import 'package:expensePlus/models/expense.dart';
import 'package:expensePlus/pages/graphPage.dart';
import 'package:expensePlus/utilities/regex.dart';
import 'package:expensePlus/widgets/expenseTile.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:expensePlus/models/tag.dart';
class TrackPage extends HookWidget {
Map<int, double> opacity = new Map();
RichTextController _controller;
var focusNode = new FocusNode();
GlobalKey<AnimatedListState> listKey = GlobalKey();
final store = MobxStore.st;
DateTime selectedDate;
double calendarHeight;
CalendarController _calendarController;
List<Expense> selectedDateExpenses;
Expense thumbnailExpense;
bool showThumbnail = false, isKeyboardActive = false;
ValueNotifier<bool> setState;
void initState() {
_controller = RichTextController({
Regex.tagRegex: TextStyle(
color: Colors.orange[700],
),
Regex.priceRegex: TextStyle(
color: Colors.deepPurple[700],
),
Regex.dateRegex: TextStyle(
color: Colors.green[700],
),
});
store.editing = <Expense>{};
selectedDate = DateTime(
DateTime.now().year,
DateTime.now().month,
DateTime.now().day,
);
if (store.selectedDate == null) store.updateSelectedDate(selectedDate);
_calendarController = CalendarController();
calendarHeight = 0;
KeyboardVisibility.onChange.listen((bool visible) {
isKeyboardActive = visible;
//keybard opening when calendar is enable
if (isKeyboardActive && calendarHeight > 0) {
calendarHeight = 0;
setState.value = !setState.value;
}
//delete
if (!isKeyboardActive && store.editing.isNotEmpty) {
store.editing = {};
_controller.text = '';
setState.value = !setState.value;
}
if (!isKeyboardActive && showThumbnail) {
showThumbnail = false;
store.thumbnailExpense = null;
_controller.text = '';
FocusScope.of(focusNode.context).unfocus();
setState.value = !setState.value;
}
});
}
@override
Widget build(BuildContext context) {
setState = useState(false);
useEffect(() {
initState();
return () {};
}, []);
return Scaffold(
body: SafeArea(
child: Container(
color: const Color(0xfff9f9f9),
child: Observer(builder: (_) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
calendarShowSection(),
calendar(),
store.selectedDateExpenses.isNotEmpty
? Text(
'Hint: Swipe Right To Edit, Left To Delete And Click A Tag For More Info',
style: TextStyle(
fontSize: 12, fontWeight: FontWeight.w200),
)
: Container(),
expensesListWidget(),
totalPriceWidget(),
thumbnailWidget(),
addPriceWidget(),
],
);
}),
),
),
);
}
//---------------CALENDAR---------------
// #region
Widget calendar() {
return Container(
height: calendarHeight,
child: SingleChildScrollView(
child: Observer(
builder: (_) {
return TableCalendar(
calendarController: _calendarController,
startingDayOfWeek: StartingDayOfWeek.monday,
initialSelectedDay: store.selectedDate,
calendarStyle: CalendarStyle(),
availableGestures: AvailableGestures.horizontalSwipe,
headerStyle: HeaderStyle(
formatButtonVisible: false,
),
rowHeight: 35,
onDaySelected: (day, events) {
// focusNode.unfocus();;
selectedDate = new DateTime(day.year, day.month, day.day);
store.updateSelectedDate(selectedDate);
store.updateGraphSelectedDate(selectedDate);
calendarHeight = 0;
setState.value = !setState.value;
},
);
},
),
),
);
}
Widget calendarShowSection() {
return Observer(builder: (_) {
store.selectedDate;
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.blue[700],
),
onPressed: calendarHeight != 0
? null
: () {
var newDate = store.selectedDate.subtract(
Duration(
days: 1,
),
);
store.updateSelectedDate(newDate);
store.updateGraphSelectedDate(newDate);
},
),
Expanded(
child: Container(
padding: const EdgeInsets.all(4.0),
margin: const EdgeInsets.only(top: 4),
decoration: BoxDecoration(
// color: Colors.grey[400],
border: Border.all(
color: Colors.blue[700],
width: 2,
),
borderRadius: BorderRadius.circular(12),
),
height: 60,
child: GestureDetector(
onTap: calendarButtonPressed,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Observer(builder: (_) {
var date = store.selectedDate;
return Container(
padding: const EdgeInsets.all(4.0),
margin: const EdgeInsets.only(top: 4),
child: Text(
store.dateStyle == 'dd/mm'
? '${date.day.toString().padLeft(2, '0')} / ${date.month.toString().padLeft(2, '0')} / ${date.year}'
: '${date.month.toString().padLeft(2, '0')} / ${date.day.toString().padLeft(2, '0')} / ${date.year}',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.blue[700],
fontSize: 20,
fontWeight: FontWeight.w500,
letterSpacing: 1.5,
),
),
);
}),
),
IconButton(
icon: Icon(
calendarHeight == 0
? Icons.arrow_drop_down
: Icons.arrow_drop_up,
color: Colors.blue[700],
),
onPressed: () async => calendarButtonPressed(),
)
],
),
)),
),
IconButton(
icon: Icon(
Icons.arrow_forward,
color: Colors.blue[700],
),
onPressed: calendarHeight != 0
? null
: () {
var newDate = store.selectedDate.add(
Duration(
days: 1,
),
);
store.updateSelectedDate(newDate);
store.updateGraphSelectedDate(newDate);
},
),
],
);
});
}
// #endregion
//---------------EXPENSES LIST WIDGET---------------
// #region
Widget expensesListWidget() {
return Expanded(
child: Container(
margin: const EdgeInsets.symmetric(vertical: 5),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: Colors.grey[200],
),
child: listViewExpenses(),
));
}
Widget listViewExpenses() {
return Observer(
builder: (_) {
store.selectedDate;
store.expenses;
List<Expense> selectedDateExpenses = store.selectedDateExpenses;
return new AnimatedList(
key: listKey,
initialItemCount:
100, // needs to be higher because we change the item count
itemBuilder: (bc, i, anim) {
if (selectedDateExpenses.length <= i) return null;
Expense expense = selectedDateExpenses[i];
return Container(
margin: const EdgeInsets.symmetric(vertical: 2),
child: Slidable(
actionPane: SlidableStrechActionPane(),
direction: Axis.horizontal,
actions: <Widget>[
IconSlideAction(
caption: 'Edit',
color: Colors.blue,
icon: Icons.edit,
onTap: () => editButtonPressed(expense.id),
),
],
secondaryActions: <Widget>[
IconSlideAction(
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
onTap: () => deleteButtonPressed(expense.id),
),
],
child: FadeTransition(
opacity: anim,
child: ExpenseTile(
expense: expense,
),
),
),
);
},
);
},
);
}
Widget thumbnailWidget() {
return Opacity(
opacity: 0.5,
child: Observer(builder: (_) {
store.thumbnailExpense;
store.editing;
Expense expenseToShow = store.thumbnailExpense;
if (showThumbnail && store.thumbnailExpense == null)
expenseToShow = Expense(
tags: [Tag.otherTag],
name: 'other',
prices: [0.0],
);
if (showThumbnail || store.editing.isNotEmpty) {
return ExpenseTile(
expense: store.thumbnailExpense,
);
} else {
return Container();
}
}),
);
}
Widget totalPriceWidget() {
return Observer(builder: (_) {
store.selectedDate;
store.limitMap;
store.editing;
var totalPrice = store.getSelectedDateTotalPrice();
//text styles
bool limitextended;
bool isUseLimit =
store.limitMap[ViewType.Day] != null && store.isUseLimit;
if (isUseLimit)
limitextended = totalPrice > store.limitMap[ViewType.Day];
else
limitextended = false;
Color color = limitextended ? Colors.red[700] : Colors.blue[700];
FontWeight fontWeight = limitextended ? FontWeight.w700 : FontWeight.w500;
double fontSize = limitextended ? 21 : 19;
return GestureDetector(
child: Container(
padding: const EdgeInsets.all(4.0),
margin: const EdgeInsets.only(bottom: 5),
decoration: BoxDecoration(
border: Border.all(
color: color,
width: 2,
),
borderRadius: BorderRadius.circular(12),
),
height: !showThumbnail ? 60 : 0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
isUseLimit
? 'Total / Limit : $totalPrice / ${store.limitMap[ViewType.Day]}'
: 'Total Expense : $totalPrice ',
style: TextStyle(
fontSize: fontSize,
fontWeight: fontWeight,
letterSpacing: 1.2,
color: color,
),
),
],
),
),
);
});
}
// #endregion
//---------------ADD PRICE TEXT FIELD---------------
Widget addPriceWidget() {
return Container(
padding: const EdgeInsets.all(4.0),
margin: const EdgeInsets.only(bottom: 5),
decoration: BoxDecoration(
color: Colors.blue[200],
border: Border.all(
color: Colors.black,
width: 2,
),
borderRadius: BorderRadius.circular(12),
),
height: 80,
child: Row(
children: <Widget>[
Expanded(
child: TextField(
onChanged: (text) async {
store.setThumbnailExpense(
await Regex.doRegex(
text,
store.selectedDate,
false,
),
);
},
onTap: () {
if (store.editing.isNotEmpty) return;
if (calendarHeight == null) {
calendarHeight = 0;
setState.value = !setState.value;
}
if (!showThumbnail) {
showThumbnail = true;
setState.value = !setState.value;
}
},
focusNode: focusNode,
textInputAction: TextInputAction.send,
controller: _controller,
maxLines: null,
minLines: null,
onSubmitted: (value) => textFieldSubmitted(_controller),
textAlignVertical: TextAlignVertical.center,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w400,
letterSpacing: 1.6,
),
decoration: InputDecoration(
contentPadding:
EdgeInsets.symmetric(horizontal: 10, vertical: 5),
hintText: 'Enter a expense',
helperText:
' . prefix to add tag (.travel .food) or shorten it (.t .f)'),
),
),
editCancelButton(),
],
),
);
}
Widget editCancelButton() {
return Observer(builder: (_) {
const double kSize = 40;
return Container(
decoration: BoxDecoration(
color: Colors.red[400],
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.symmetric(horizontal: 7),
width: store.editing.isNotEmpty ? null : 0,
child: IconButton(
onPressed: editCancelPressed,
constraints: BoxConstraints(
maxHeight: kSize,
maxWidth: kSize,
),
icon: Icon(
Icons.clear,
color: Colors.white,
),
highlightColor: Colors.red,
),
);
});
}
//
//--------------LOGIC--------------
// #region Logic
textFieldSubmitted(TextEditingController _controller) async {
Expense regexExpense = await Regex.doRegex(
_controller.text,
store.selectedDate,
true,
);
print('regexExpense:\t $regexExpense');
showThumbnail = false;
store.thumbnailExpense = null;
_controller.text = '';
if (store.editing.isNotEmpty) {
//EDITING PART
Expense expenseToAdd = regexExpense;
expenseToAdd.id = store.editing.first.id;
store.updateExpense(expenseToAdd, setDatabase: true);
store.editing = {};
} else {
//ADDING PART
store.addExpense(regexExpense, setDatabase: true);
if (isSelectedDate(regexExpense))
listKey.currentState.insertItem(store.selectedDateExpenses.length - 1);
}
showThumbnail = false;
setState.value = !setState.value;
}
deleteButtonPressed(int id) {
Expense expense =
store.selectedDateExpenses.firstWhere((element) => element.id == id);
ExpenseProvider.db.delete(expense).then((value) {
print('deleted');
});
AnimatedListRemovedItemBuilder builder = (context, anim) {
return FadeTransition(
opacity: anim,
child: ExpenseTile(
expense: expense,
),
);
};
listKey.currentState.removeItem(
store.selectedDateExpenses.indexOf(expense),
builder,
duration: Duration(milliseconds: 500),
);
store.deleteExpense(expense);
setState.value = !setState.value;
}
editButtonPressed(int id) {
Expense expense = store.selectedDateExpenses.firstWhere(
(element) => element.id == id,
);
store.editing = {expense};
focusNode.requestFocus();
//to set state of total expense widget
store.selectedDate = DateTime.parse(store.selectedDate.toIso8601String());
_controller.text = expense.text;
_controller.buildTextSpan(
style: TextStyle(
color: Colors.red,
),
);
showThumbnail = true;
store.thumbnailExpense = expense;
}
Future calendarButtonPressed() async {
if (isKeyboardActive) {
focusNode.unfocus();
await Future.doWhile(() async {
await Future.delayed(Duration(milliseconds: 200));
return isKeyboardActive;
});
}
if (calendarHeight != null)
calendarHeight = null;
else
calendarHeight = 0;
setState.value = !setState.value;
}
bool isSelectedDate(Expense exp) {
return exp.date.year == store.selectedDate.year &&
exp.date.month == store.selectedDate.month &&
exp.date.day == store.selectedDate.day;
}
editCancelPressed() {
store.editing = {};
focusNode.unfocus();
_controller.text = '';
}
// #endregion
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/pages/settingsPage.dart | import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:expensePlus/database/expense_provider.dart';
import 'package:expensePlus/database/settings_provider.dart';
import 'package:expensePlus/database/tag_provider.dart';
import 'package:expensePlus/pages/graphPage.dart';
import '../expenses_store.dart';
enum Data {
tag,
expense,
all,
}
class SettingsPage extends HookWidget {
ValueNotifier<double> amount;
ValueNotifier<String> dateStyle;
final store = MobxStore.st;
@override
Widget build(BuildContext context) {
amount = useState(null);
dateStyle = useState(store.dateStyle);
return SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey[700],
title: Text(
'Settings',
style: TextStyle(
fontSize: 20,
),
),
),
body: SingleChildScrollView(
child: Observer(builder: (_) {
store.limitMap;
store.isAutomatic;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// #region LIMIT
Container(
padding: EdgeInsets.symmetric(vertical: 15, horizontal: 10),
child: Text(
'Configure Limit',
style: TextStyle(
fontSize: 18,
letterSpacing: 1,
color: Colors.blue[700],
fontWeight: FontWeight.w600,
),
),
),
ListTile(
leading: Switch(
value: store.isUseLimit ?? false,
onChanged: (isChecked) {
store.setUseLimit(
isChecked,
setDatabase: true,
);
},
)
//todo implent
,
title: Text(
'Use Limit',
style: TextStyle(
fontSize: 16,
letterSpacing: 0.3,
fontWeight: FontWeight.w400,
),
),
),
Divider(
thickness: 1,
),
ListTile(
enabled: (store.isUseLimit ?? false),
leading: Checkbox(
value: store.isAutomatic,
onChanged: (store.isUseLimit ?? false)
? (isChecked) {
store.isAutomatic = isChecked;
if (store.isAutomatic)
store.automaticSet(setDatabase: true);
}
: null,
),
title: Text(
'Automatic Limits By Month',
style: TextStyle(
fontSize: 16,
letterSpacing: 0.3,
fontWeight: FontWeight.w400,
),
),
),
Divider(
thickness: 1,
),
ListTile(
enabled: store.isUseLimit ?? false,
title: Text(
'Configure Monthly Limit',
style: TextStyle(
fontSize: 18,
letterSpacing: 0.3,
fontWeight: FontWeight.w400,
),
),
subtitle: Text(
store.limitMap[ViewType.Month]?.toString() ??
'Not configured',
),
onTap: () => configureLimit(context, ViewType.Month),
trailing: deleteLimitButton(ViewType.Month)),
Divider(
thickness: 1,
),
ListTile(
enabled: (store.isUseLimit ?? false) && !store.isAutomatic,
title: Text(
'Configure Weekly Limit',
style: TextStyle(
fontSize: 18,
letterSpacing: 0.3,
fontWeight: FontWeight.w400,
),
),
subtitle: Text(
store.limitMap[ViewType.Week]?.toString() ??
'Not configured',
),
onTap: () => configureLimit(context, ViewType.Week),
trailing: deleteLimitButton(ViewType.Week),
),
Divider(
thickness: 1,
),
ListTile(
enabled: (store.isUseLimit ?? false) && !store.isAutomatic,
title: Text(
'Configure Daily Limit',
style: TextStyle(
fontSize: 18,
letterSpacing: 0.3,
fontWeight: FontWeight.w400,
),
),
subtitle: Text(
store.limitMap[ViewType.Day]?.toString() ??
'Not configured',
),
onTap: () => configureLimit(context, ViewType.Day),
trailing: deleteLimitButton(ViewType.Day),
),
Divider(
thickness: 1,
),
// #endregion
// #region DATA
Container(
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: Text(
'Data',
style: TextStyle(
fontSize: 18,
letterSpacing: 1,
color: Colors.blue[700],
fontWeight: FontWeight.w600,
),
),
),
ListTile(
title: Text(
'Delete Data',
style: TextStyle(
fontSize: 18,
letterSpacing: 0.3,
fontWeight: FontWeight.w400,
),
),
onTap: () async => await deleteDataPressed(context),
),
Divider(
thickness: 1,
),
// #endregion
// #region DateStyle
Container(
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: Text(
'Date Style',
style: TextStyle(
fontSize: 18,
letterSpacing: 1,
color: Colors.blue[700],
fontWeight: FontWeight.w600,
),
),
),
ListTile(
title: Text(
'Set Date Style',
style: TextStyle(
fontSize: 18,
letterSpacing: 0.3,
fontWeight: FontWeight.w400,
),
),
onTap: () async => await configureDateStyle(context),
),
Divider(
thickness: 1,
),
// #endregion
],
);
}),
),
),
);
}
Widget deleteLimitButton(ViewType type) {
bool disabled = false;
if (type != ViewType.Month && store.isAutomatic) disabled = true;
if (store.limitMap[type] == null) disabled = true;
if (!store.isUseLimit) disabled = true;
const double kSize = 40;
return Container(
decoration: BoxDecoration(
color: !disabled ? Colors.red[400] : Colors.grey[400],
borderRadius: BorderRadius.circular(10),
),
child: IconButton(
constraints: BoxConstraints(
maxHeight: kSize,
maxWidth: kSize,
),
onPressed: !disabled
? () {
store.setLimit(type, null);
}
: null,
icon: Icon(
Icons.clear,
color: Colors.white,
),
highlightColor: Colors.red,
),
);
}
// #region LOGIC
Future<void> deleteDataPressed(BuildContext bc) async {
TextStyle style = new TextStyle(
fontSize: 18,
letterSpacing: 1,
);
switch (await showDialog(
context: bc,
builder: (context) {
return SimpleDialog(
title: Text(
'What do you want to delete?',
style: TextStyle(
fontSize: 18,
),
),
children: <Widget>[
SimpleDialogOption(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
onPressed: () {
Navigator.pop(context, Data.tag);
},
child: Text(
'Delete Tags',
style: style,
),
),
SimpleDialogOption(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
onPressed: () {
Navigator.pop(context, Data.expense);
},
child: Text(
'Delete Expenses',
style: style,
),
),
SimpleDialogOption(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
onPressed: () {
Navigator.pop(context, Data.all);
},
child: Text(
'Delete Both',
style: style,
),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, '');
},
child: Center(
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(color: Colors.red[100]),
child: Text(
'Cancel',
style: style,
),
),
),
),
],
);
},
)) {
case Data.expense:
await ExpenseProvider.db.deleteAll();
MobxStore.st.deleteAll();
break;
case Data.tag:
await TagProvider.db.deleteAll();
MobxStore.st.deleteAllTags();
break;
case Data.all:
await ExpenseProvider.db.deleteAll();
MobxStore.st.deleteAll();
await TagProvider.db.deleteAll();
MobxStore.st.deleteAllTags();
break;
default:
}
}
Future<void> configureLimit(BuildContext bc, ViewType viewType) async {
var amountEntered;
TextStyle style = new TextStyle(
fontSize: 18,
letterSpacing: 1,
);
String viewtypeToString(ViewType vt) => {
ViewType.Day: 'Daily',
ViewType.Month: 'Monthly',
ViewType.Week: 'Weekly,'
}[vt];
final controller = TextEditingController();
amount.value = await showDialog(
context: bc,
builder: (context) {
return SimpleDialog(
title: Text(
'Set ${viewtypeToString(viewType)} Limit',
style: TextStyle(
fontSize: 18,
),
),
children: <Widget>[
SimpleDialogOption(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 30),
child: TextField(
controller: controller,
keyboardType: TextInputType.number,
onSubmitted: (data) {
print('onSubmit $data');
amountEntered = data;
if (data.isEmpty)
Navigator.pop(context, null);
else
Navigator.pop(
context,
double.parse(data),
);
},
decoration: InputDecoration(
contentPadding:
EdgeInsets.symmetric(horizontal: 15, vertical: 10),
border: OutlineInputBorder(),
hintText: 'Enter a amount',
hintStyle: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
),
),
SimpleDialogOption(
onPressed: () {
amountEntered = null;
if (controller.text.isNotEmpty && controller.text != null)
amountEntered = double.parse(controller.text);
Navigator.pop(context, amountEntered);
},
child: Center(
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(color: Colors.green[100]),
child: Text(
'Submit',
style: style,
),
),
),
),
],
);
},
);
if (amount.value != null) {
store.setLimit(
viewType,
amount.value,
setDatabase: true,
);
if (store.isAutomatic) store.automaticSet(setDatabase: true);
}
}
Future<void> configureDateStyle(BuildContext bc) async {
TextStyle style = new TextStyle(
fontSize: 18,
letterSpacing: 1,
);
dateStyle.value = await showDialog(
context: bc,
builder: (context) {
return SimpleDialog(
title: Text(
'Set Date Style',
style: TextStyle(
fontSize: 18,
),
),
children: <Widget>[
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, 'dd/mm');
},
child: Center(
child: Container(
color: store.dateStyle == 'dd/mm'? Colors.blue[100]:null,
padding: EdgeInsets.all(10),
child: Text(
'dd/mm/yyyy',
style: style,
),
),
),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, 'mm/dd');
},
child: Center(
child: Container(
color: store.dateStyle == 'mm/dd'? Colors.blue[100]:null,
padding: EdgeInsets.all(10),
child: Text(
'mm/dd/yyyy',
style: style,
),
),
),
),
],
);
},
);
if (dateStyle?.value != null) {
await SettingsProvider.db.changeDateStyle(dateStyle.value);
store.dateStyle = dateStyle.value;
final date = DateTime.parse(store.selectedDate.toIso8601String());
store.updateSelectedDate(date);
store.updateGraphSelectedDate(date);
}
}
// #endregion
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/pages/tagDetailPage.dart | import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:expensePlus/expenses_store.dart';
import 'package:expensePlus/models/expense.dart';
import 'package:expensePlus/models/tag.dart';
import 'package:expensePlus/widgets/expenseTile.dart';
class TagDetailPage extends HookWidget {
TagDetailPage(this.tag);
final Tag tag;
final store = MobxStore.st;
ValueNotifier<bool> isExpensesExist;
ValueNotifier<List<Tag>> checkboxs;
ValueNotifier<DateTime> from;
ValueNotifier<DateTime> to;
@override
Widget build(BuildContext context) {
checkboxs = useState([tag]);
from = useState(null);
to = useState(null);
isExpensesExist = useState(expensesNeedsShow().isNotEmpty);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.grey[700],
title: Text(
'Tag Details',
style: TextStyle(
fontSize: 20,
),
),
elevation: 0,
),
body: SizedBox.expand(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
filterSection(context),
isExpensesExist.value
? Text(
'Hint: Click An Expense To Go Add Expense Page',
style:
TextStyle(fontSize: 12, fontWeight: FontWeight.w200),
)
: Container(),
tagExpenseList(),
],
),
),
),
);
}
// #region UI
Widget filterSection(BuildContext context) {
return Container(
constraints: BoxConstraints(minHeight: 60),
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
offset: Offset(0, 1),
blurRadius: 2,
color: Colors.black87,
),
],
color: Colors.blue[700],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Text(
'Filters:',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 16,
),
),
),
Expanded(
child: Container(
constraints: BoxConstraints(
minWidth: 160,
),
child: filterBox(
onTap: () async =>
await handleMultipleTagSelection(context),
text: 'Select Tags',
),
),
),
Expanded(
child: Container(
constraints: BoxConstraints(
minWidth: 120,
),
child: filterBox(
onTap: () async => await handleDateSelection(context),
text: 'Select Dates',
),
),
),
],
),
],
),
);
}
Widget filterBox({Function onTap, String text}) {
return GestureDetector(
onTap: onTap,
child: Container(
padding: EdgeInsets.all(10),
margin: EdgeInsets.symmetric(horizontal: 5, vertical: 15),
decoration: BoxDecoration(
color: Colors.blue[600],
border: Border.all(
width: 1.5,
color: Colors.white,
),
borderRadius: BorderRadius.circular(5),
boxShadow: [
BoxShadow(
offset: Offset(0, 1),
blurRadius: 1,
color: Colors.white,
)
]),
child: Center(
child: Text(
text,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
),
),
);
}
Widget tagExpenseList() {
return Builder(builder: (context) {
return Container(
child: SingleChildScrollView(
child: tagExpenses(),
),
);
});
}
Widget tagExpenses() {
List<MapEntry<DateTime, List<Expense>>> entries = expensesNeedsShow();
entries.sort((me1, me2) => me1.key.compareTo(me2.key));
List<Widget> listTiles = new List();
entries.forEach((entry) {
var date = entry.key;
var expenses = entry.value;
Color calendarTileColor = Colors.blue[700];
listTiles.add(
Container(
margin: EdgeInsets.only(top: 5, bottom: 2),
decoration: BoxDecoration(
border: Border.all(
color: calendarTileColor,
width: 2,
),
borderRadius: BorderRadius.circular(5),
),
child: ListTile(
title: Text(
store.dateStyle == 'dd/mm'
? '${date.day.toString().padLeft(2, '0')} / ${date.month.toString().padLeft(2, '0')} / ${date.year}'
: '${date.month.toString().padLeft(2, '0')} / ${date.day.toString().padLeft(2, '0')} / ${date.year}',
style: TextStyle(
color: calendarTileColor, fontWeight: FontWeight.w500),
),
leading: Icon(Icons.calendar_today, color: calendarTileColor),
),
),
);
listTiles.addAll(
expenses.map((e) => GestureDetector(
onTap: () {
MobxStore.st.currentIndex = 1;
store.updateSelectedDate(e.date);
store.updateGraphSelectedDate(e.date);
MobxStore.st.navigatorKey.currentState.pop();
},
child: ExpenseTile(
expense: e,
),
)),
);
});
return Column(
children: listTiles,
);
}
// #endregion
// #region LOGIC
List<MapEntry<DateTime, List<Expense>>> expensesNeedsShow() {
List<Expense> selectedExpense = store.expenses.fold(
[],
(prev, exp) {
if (needsToShow(exp)) return [...prev, exp];
return prev;
},
);
Map<DateTime, List<Expense>> map = selectedExpense.fold(
{},
(prev, exp) {
DateTime date = exp.date;
if (prev[date] == null) prev[date] = [];
prev[date].add(exp);
return prev;
},
);
List<MapEntry<DateTime, List<Expense>>> entries = map.entries.toList();
return entries;
}
handleMultipleTagSelection(BuildContext context) async {
await showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return SimpleDialog(
title: Text(
'What tags do you want to choose?',
style: TextStyle(
fontSize: 18,
),
),
children: <Widget>[
...store.tags.map((t) {
return CheckboxListTile(
value: checkboxs.value.contains(t),
activeColor: t.color,
title: Row(
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(
vertical: 5, horizontal: 6),
margin: const EdgeInsets.symmetric(
vertical: 2, horizontal: 3),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: t.color,
blurRadius: 2,
offset: Offset(0, 1),
)
],
borderRadius: BorderRadius.circular(3),
border: Border.all(
color: t.color,
width: 1,
)),
child: Text(
t.name,
textAlign: TextAlign.left,
overflow: TextOverflow.fade,
maxLines: 1,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: t.color,
),
),
),
Spacer()
],
),
onChanged: (check) {
setState(() {
if (check)
checkboxs.value = [...checkboxs.value, t];
else if (checkboxs.value.length == 1)
return;
else
checkboxs.value = new List.from(checkboxs.value)
..remove(t);
isExpensesExist.value = expensesNeedsShow().isNotEmpty;
});
},
);
}).toList(),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, checkboxs);
},
child: Center(
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(color: Colors.green[100]),
child: Text(
'Submit',
style: TextStyle(
fontSize: 18,
letterSpacing: 1,
),
),
),
),
),
],
);
},
);
},
);
}
handleDateSelection(BuildContext context) async {
VoidCallback checkFromTo = () {
if (to.value != null && from.value != null) {
if (from.value.isAfter(to.value)) {
//from must before to
final oldEarlyValue = to.value;
to.value = from.value;
from.value = oldEarlyValue;
}
}
};
await showDialog(
context: context,
builder: (context) {
return StatefulBuilder(builder: (context, setState) {
return SimpleDialog(
title: Text(
'What days do you want to choose?',
style: TextStyle(
fontSize: 18,
),
),
children: <Widget>[
//FROM
SimpleDialogOption(
onPressed: () async {
from.value = await showDatePicker(
helpText: 'Select Initial Date',
context: context,
initialDate: from.value ?? store.selectedDate,
firstDate: DateTime(2010),
lastDate: DateTime(2030),
);
checkFromTo();
setState(() {});
},
child: Center(
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
border:
Border.all(color: Colors.blue[700], width: 1.5)),
child: Text(
from.value != null
? store.dateStyle == 'dd/mm'
? ' From: ${from.value.day.toString().padLeft(2, '0')}/${from.value.month.toString().padLeft(2, '0')}/${from.value.year}'
: ' From: ${from.value.month.toString().padLeft(2, '0')}/${from.value.day.toString().padLeft(2, '0')}/${from.value.year}'
: ' From: Not Selected',
style: TextStyle(
color: Colors.blue[700], fontWeight: FontWeight.w600),
),
),
),
),
//TO
SimpleDialogOption(
onPressed: () async {
to.value = await showDatePicker(
helpText: 'Select Initial Date',
context: context,
initialDate: to.value ?? store.selectedDate,
firstDate: DateTime(2010),
lastDate: DateTime(2030),
);
checkFromTo();
setState(() {});
},
child: Center(
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
border:
Border.all(color: Colors.blue[700], width: 1.5)),
child: Text(
to.value != null
? store.dateStyle == 'dd/mm'
? 'To: ${to.value.day.toString().padLeft(2, '0')}/${to.value.month.toString().padLeft(2, '0')}/${to.value.year}'
: 'To: ${to.value.month.toString().padLeft(2, '0')}/${to.value.day.toString().padLeft(2, '0')}/${to.value.year}'
: 'To: Not Selected',
style: TextStyle(
color: Colors.blue[700], fontWeight: FontWeight.w600),
),
),
),
),
SimpleDialogOption(
onPressed: () {
to.value = null;
from.value = null;
setState(() {});
},
child: Center(
child: Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(color: Colors.red[100]),
child: Text(
'Clear Dates',
style: TextStyle(fontSize: 12),
),
),
),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, checkboxs);
},
child: Center(
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(color: Colors.green[100]),
child: Text(
'Submit',
style: TextStyle(
fontSize: 18,
letterSpacing: 1,
),
),
),
),
),
],
);
});
},
);
}
bool needsToShow(Expense expense) {
List<Tag> tags = expense.tags;
DateTime date = expense.date;
var needs = false;
final isSameDay = (DateTime date1, DateTime date2) =>
date1.day == date2.day &&
date1.month == date2.month &&
date1.year == date2.year;
for (var checked in checkboxs.value) {
bool after = from.value != null
? date.isAfter(from.value) || isSameDay(date, from.value)
: true;
bool before = to.value != null
? date.isBefore(to.value) || isSameDay(date, to.value)
: true;
if (tags.contains(checked) && after && before) {
needs = true;
break;
}
}
return needs;
}
// #endregion
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/models/tag.dart | import 'package:flutter/material.dart';
class Tag {
String name, shorten;
int hexCode, id;
Color color;
static Tag otherTag = Tag(
name: 'other',
hexCode: 0xff9e9e9e,
);
Tag({this.id, this.name, this.shorten, this.hexCode, this.color}) {
shorten ??= name;
if (color == null)
hexCode ??= 0xFFFFA726;
else
hexCode = color.value;
color ??= Color(hexCode);
}
factory Tag.fromJson(Map<String, dynamic> json) => Tag(
id: json["id"],
name: json["name"],
shorten: json["shorten"],
hexCode: json["hexCode"],
color: Color(json["hexCode"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"shorten": shorten,
"hexCode": hexCode,
};
static Tag other() {
return Tag.otherTag;
}
@override
String toString() {
return 'ID:$id Name:$name shorten:$shorten Color:$color';
}
}
| 0 |
mirrored_repositories/ExpensePlus/lib | mirrored_repositories/ExpensePlus/lib/models/expense.dart | import 'package:expensePlus/expenses_store.dart';
import 'tag.dart';
class Expense {
int id;
String name;
String text;
List<Tag> tags;
List<double> prices;
bool limit;
DateTime date;
Expense({
this.id,
this.text,
this.name,
this.tags,
this.prices,
this.limit,
this.date,
}) {
prices = prices == null ? [0] : prices.isEmpty ? [0] : prices;
date ??= DateTime.now();
date = DateTime(
date.year,
date.month,
date.day,
);
}
static Expense empty() {
return new Expense(
name: '',
prices: [0],
tags: [
Tag.otherTag,
],
limit: true,
);
}
double getTotalExpense() =>
prices.reduce((value, element) => value + element);
factory Expense.fromJson(Map<String, dynamic> json) {
List<Tag> tags = List();
json["tags"].forEach((element) {
if (element['name'] == 'other')
tags.add(Tag.otherTag);
else
tags.add(MobxStore.st.getTagByName(element['name']));
});
List<double> prices = List();
json["prices"]?.forEach((element) {
prices.add(element);
});
prices = prices.isEmpty || prices == null ? [0] : prices;
DateTime date = json["date"] != null ? DateTime.parse(json["date"]) : null;
date = DateTime(date.year, date.month, date.day);
return Expense(
id: json["id"],
text: json["text"],
name: json["name"],
tags: tags,
prices: prices,
limit: json["limit"],
date: date,
);
}
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"text": text,
"tags": tags.map((e) => e.toJson()).toList(),
"prices": prices,
"limit": limit,
"date": date?.toIso8601String(),
};
String toString() {
return 'ID:$id Text:$text Name:$name Tags:$tags Prices:$prices Limit:$limit Date:$date\n';
}
}
| 0 |
mirrored_repositories/FacebookClone-Flutter | mirrored_repositories/FacebookClone-Flutter/lib/main.dart | import 'package:facebookclone/Screens/Home.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: HomePage(),
);
}
}
| 0 |
mirrored_repositories/FacebookClone-Flutter/lib | mirrored_repositories/FacebookClone-Flutter/lib/Screens/Home.dart | import 'package:facebookclone/Screens/HomeScreen.dart';
import 'package:facebookclone/Screens/OnDemandPostScreen.dart';
import 'package:facebookclone/Widget/AppBarButton.dart';
import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
void main() {
runApp(HomePage());
}
class HomePage extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{
final TrackingScrollController scrollController = TrackingScrollController();
TabController controller;
@override
void initState() {
super.initState();
controller = new TabController(length: 4, vsync: this);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: new SafeArea(
child: DefaultTabController(
length: 4,
child: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
PreferredSize(
preferredSize: Size.fromHeight(50.0),
child: SliverAppBar(
pinned: false,
brightness: Brightness.light,
backgroundColor: Colors.white,
title: Text(
'facebook',
style: const TextStyle(
color: Color(0xFF1777F2),
fontSize: 28.0,
fontWeight: FontWeight.bold,
letterSpacing: -1.2,
),
),
centerTitle: false,
floating: true,
actions: [
AppBarButton(
icon: Icons.search,
iconSize: 25.0,
onPressed: () => print('Search'),
),
AppBarButton(
icon: MdiIcons.facebookMessenger,
iconSize: 25.0,
onPressed: () => print('Messenger'),
),
],
),
),
SliverPersistentHeader(
delegate: _SliverAppBarDelegate(
TabBar(
controller: controller,
labelColor: Color(0xFF1777F2),
unselectedLabelColor: Colors.grey,
tabs: [
Tab(icon: Icon(Icons.home, size: 25,)),
Tab(icon: Icon(Icons.ondemand_video,size: 25)),
Tab(icon: Icon(MdiIcons.bellOutline,size: 25)),
Tab(icon: Icon(Icons.menu,size: 25)),
],
),
),
pinned: true,
),
];
},
body: TabBarView(
controller: controller,
children: [
HomeScreen(),
OnDemaindPostScreen(),
Center(
child: Text('Notification'),
),
Center(
child: Text('Morer'),
)
],
)
),
),
),
);
}
}
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
_SliverAppBarDelegate(this._tabBar);
final TabBar _tabBar;
@override
double get minExtent => _tabBar.preferredSize.height;
@override
double get maxExtent => _tabBar.preferredSize.height;
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return new Container(
color: Colors.white,
child: _tabBar,
);
}
@override
bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
return false;
}
} | 0 |
mirrored_repositories/FacebookClone-Flutter/lib | mirrored_repositories/FacebookClone-Flutter/lib/Screens/HomeScreen.dart | import 'package:facebookclone/Widget/CreateRoom.dart';
import 'package:facebookclone/Widget/Post.dart';
import 'package:facebookclone/Widget/Stories.dart';
import 'package:flutter/material.dart';
import 'package:facebookclone/Widget/AddPost.dart';
void main() {
runApp(HomeScreen());
}
class HomeScreen extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return HomeScreenPage();
}
}
class HomeScreenPage extends StatefulWidget {
HomeScreenPage({Key key, this.title}) : super(key: key);
final String title;
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreenPage> {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.grey[300],
child: SingleChildScrollView(
child: Column(
children: <Widget>[
AddPost(),
CreateRoomScreen(),
Container(
height: 280,
child: Card(
elevation: 0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
StoriesScreen(StoryImage: "https://images.unsplash.com/photo-1598240087583-2f610faf1eaf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1275&q=80",userImage: "https://images.unsplash.com/photo-1598211686290-a8ef209d87c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3334&q=80", userName: "Tony",first: true,),
StoriesScreen(StoryImage: "https://images.unsplash.com/flagged/photo-1556746834-1cb5b8fabd54?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2252&q=80",userImage: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80", userName: "Alex",first: false),
StoriesScreen(StoryImage: "https://images.unsplash.com/photo-1575997759258-91792eaaf87b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60",userImage: "https://images.unsplash.com/photo-1544725176-7c40e5a71c5e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2247&q=80", userName: "Luis Villasmil",first: false),
StoriesScreen(StoryImage: "https://images.unsplash.com/photo-1505391847043-8b6e24dd6c28?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60",userImage: "https://images.unsplash.com/photo-1527980965255-d3b416303d12?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80", userName: "Nicolos Horn",first: false),
StoriesScreen(StoryImage: "https://images.unsplash.com/photo-1594463750939-ebb28c3f7f75?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60",userImage: "https://images.unsplash.com/photo-1528763380143-65b3ac89a3ff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", userName: "Ben Parker",first: false),
StoriesScreen(StoryImage: "https://images.unsplash.com/photo-1505391847043-8b6e24dd6c28?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60",userImage: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", userName: "Minh Pham",first: false),
StoriesScreen(StoryImage: "https://images.unsplash.com/photo-1585128993280-9456c19c987d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1872&q=80",userImage: "https://images.unsplash.com/photo-1544724107-6d5c4caaff30?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", userName: "Charles",first: false),
],
),
),
),
PostScreen(userImage: 'https://images.unsplash.com/photo-1544724107-6d5c4caaff30?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Charles', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '3hrs', imageUrl: null, likes: '32', comments: '10',shares: '9',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Minh Pham', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '7hrs', imageUrl: "https://images.unsplash.com/photo-1593642532454-e138e28a63f4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '432', comments: '120',shares: '90',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1528763380143-65b3ac89a3ff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Ben Parker', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '8hrs', imageUrl: null, likes: '232', comments: '110',shares: '100',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1527980965255-d3b416303d12?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80', username: 'Nicolos Horn', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '10hrs', imageUrl: "https://images.unsplash.com/photo-1598225176697-e7fc9857917b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '22', comments: '130',shares: '30',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1544725176-7c40e5a71c5e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2247&q=80', username: 'Luis Villasmil', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '12hrs', imageUrl: "https://images.unsplash.com/photo-1558980664-3a031cf67ea8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '522', comments: '152',shares: '20',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80', username: 'Alex', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '2 days', imageUrl: null, likes: '123', comments: '12',shares: '1',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1598211686290-a8ef209d87c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3334&q=80', username: 'Tony', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '2 days', imageUrl: "https://images.unsplash.com/photo-1598259812920-0f409c9d3f14?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '125', comments: '13',shares: '4',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1528763380143-65b3ac89a3ff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Charles', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '1 week', imageUrl: null, likes: '534', comments: '423',shares: '103',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Minh Pham', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '2 week', imageUrl: "https://images.unsplash.com/photo-1558981033-f5e2ddd9c57e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '23', comments: '13',shares: '1',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80', username: 'Nicolos', caption: 'This is a facebook clone app developed only for learning purpose. Thank you.', timeAgo: '2 week', imageUrl: "https://images.unsplash.com/photo-1593642532781-03e79bf5bec2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '21', comments: '20',shares: '23',),
],
),
)
);
}
}
| 0 |
mirrored_repositories/FacebookClone-Flutter/lib | mirrored_repositories/FacebookClone-Flutter/lib/Screens/OnDemandPostScreen.dart | import 'package:facebookclone/Widget/CreateRoom.dart';
import 'package:facebookclone/Widget/Post.dart';
import 'package:facebookclone/Widget/Stories.dart';
import 'package:flutter/material.dart';
import 'package:facebookclone/Widget/AddPost.dart';
void main() {
runApp(OnDemaindPostScreen());
}
class OnDemaindPostScreen extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return OnDemaindPostPage();
}
}
class OnDemaindPostPage extends StatefulWidget {
OnDemaindPostPage({Key key, this.title}) : super(key: key);
final String title;
@override
_OnDemandPostScreenState createState() => _OnDemandPostScreenState();
}
class _OnDemandPostScreenState extends State<OnDemaindPostPage> {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.grey[300],
child: SingleChildScrollView(
child: Column(
children: <Widget>[
PostScreen(userImage: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80', username: 'Nicolos', caption: '', timeAgo: '2 week', imageUrl: "https://images.unsplash.com/photo-1593642532781-03e79bf5bec2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '21', comments: '20',shares: '23',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Minh Pham', caption: '', timeAgo: '2 week', imageUrl: "https://images.unsplash.com/photo-1558981033-f5e2ddd9c57e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '23', comments: '13',shares: '1',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1598211686290-a8ef209d87c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3334&q=80', username: 'Tony', caption: '', timeAgo: '2 days', imageUrl: "https://images.unsplash.com/photo-1598259812920-0f409c9d3f14?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '125', comments: '13',shares: '4',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80', username: 'Alex', caption: '', timeAgo: '2 days', imageUrl: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '123', comments: '12',shares: '1',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1544725176-7c40e5a71c5e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2247&q=80', username: 'Luis Villasmil', caption: '', timeAgo: '12hrs', imageUrl: "https://images.unsplash.com/photo-1558980664-3a031cf67ea8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '522', comments: '152',shares: '20',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1527980965255-d3b416303d12?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80', username: 'Nicolos Horn', caption: '', timeAgo: '10hrs', imageUrl: "https://images.unsplash.com/photo-1598225176697-e7fc9857917b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '22', comments: '130',shares: '30',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1528763380143-65b3ac89a3ff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Ben Parker', caption: '', timeAgo: '8hrs', imageUrl: "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1600&q=80", likes: '232', comments: '110',shares: '100',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Minh Pham', caption: '', timeAgo: '7hrs', imageUrl: "https://images.unsplash.com/photo-1593642532454-e138e28a63f4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60", likes: '432', comments: '120',shares: '90',),
PostScreen(userImage: 'https://images.unsplash.com/photo-1544724107-6d5c4caaff30?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60', username: 'Charles', caption: '', timeAgo: '3hrs', imageUrl: "https://images.unsplash.com/photo-1598211686290-a8ef209d87c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3334&q=80", likes: '32', comments: '10',shares: '9',),
],
),
)
);
}
}
| 0 |
mirrored_repositories/FacebookClone-Flutter/lib | mirrored_repositories/FacebookClone-Flutter/lib/Widget/Post.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:facebookclone/Widget/CreateRoom.dart';
import 'package:facebookclone/Widget/Stories.dart';
import 'package:flutter/material.dart';
import 'package:facebookclone/Widget/AddPost.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
void main() {
runApp(PostScreen());
}
class PostScreen extends StatelessWidget {
// This widget is the root of your application.
String userImage, username, caption, timeAgo, imageUrl, likes, comments, shares, profileImage;
PostScreen({Key key,this.userImage, this.username, this.caption, this.timeAgo, this.imageUrl, this.likes, this.comments, this.shares, this.profileImage });
@override
Widget build(BuildContext context) {
return PostScreenPage(userImage: this.userImage, username: this.username, caption: this.caption, timeAgo: this.timeAgo, imageUrl: this.imageUrl, likes: this.likes, comments: this.comments,shares: this.shares, profileImage: this.profileImage,);
}
}
class PostScreenPage extends StatefulWidget {
String userImage, username, caption, timeAgo, imageUrl, likes, comments, shares, profileImage;
PostScreenPage({Key key,this.userImage, this.username, this.caption, this.timeAgo, this.imageUrl, this.likes, this.comments, this.shares, this.profileImage });
@override
_PostScreenState createState() => _PostScreenState();
}
class _PostScreenState extends State<PostScreenPage> {
@override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.symmetric(
vertical: 5.0,
horizontal: 0.0,
),
elevation: 0.0,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
color: Colors.white,
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_PostHeader(profileImage: widget.userImage,username: widget.username, timeAgo: widget.timeAgo,),
const SizedBox(height: 4.0),
Text(widget.caption),
widget.imageUrl != null
? const SizedBox.shrink()
: const SizedBox(height: 6.0),
],
),
),
widget.imageUrl!= null
? Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Image.network(widget.imageUrl),
)
: const SizedBox.shrink(),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: _PostStats(likes: widget.likes,comments: widget.comments,share: widget.shares,),
),
],
),
),
);
}
}
class _PostHeader extends StatelessWidget {
final String profileImage;
final String username;
final String timeAgo;
const _PostHeader({
Key key,
@required this.profileImage,
@required this.username,
@required this.timeAgo,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
children: [
_AvatarImage(profileAvatarImage: profileImage,),
const SizedBox(width: 8.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
username,
style: const TextStyle(
fontWeight: FontWeight.w600,
),
),
Row(
children: [
Text(
'${timeAgo} • ',
style: TextStyle(
color: Colors.grey[600],
fontSize: 12.0,
),
),
Icon(
Icons.public,
color: Colors.grey[600],
size: 12.0,
)
],
),
],
),
),
IconButton(
icon: const Icon(Icons.more_horiz),
onPressed: () => print('More'),
),
],
);
}
}
class _PostStats extends StatelessWidget {
final String likes, comments, share;
const _PostStats({
Key key,
@required this.likes,
@required this.comments,
@required this.share,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(4.0),
decoration: BoxDecoration(
color: Color(0xFF1777F2),
shape: BoxShape.circle,
),
child: const Icon(
Icons.thumb_up,
size: 10.0,
color: Colors.white,
),
),
const SizedBox(width: 4.0),
Expanded(
child: Text(
'${likes}',
style: TextStyle(
color: Colors.grey[600],
),
),
),
Text(
'${comments} Comments',
style: TextStyle(
color: Colors.grey[600],
),
),
const SizedBox(width: 8.0),
Text(
'${share} Shares',
style: TextStyle(
color: Colors.grey[600],
),
)
],
),
const Divider(),
Row(
children: [
_PostButton(
icon: Icon(
MdiIcons.thumbUpOutline,
color: Colors.grey[600],
size: 20.0,
),
label: 'Like',
onTap: () => print('Like'),
),
_PostButton(
icon: Icon(
MdiIcons.commentOutline,
color: Colors.grey[600],
size: 20.0,
),
label: 'Comment',
onTap: () => print('Comment'),
),
_PostButton(
icon: Icon(
MdiIcons.shareOutline,
color: Colors.grey[600],
size: 25.0,
),
label: 'Share',
onTap: () => print('Share'),
)
],
),
],
);
}
}
class _PostButton extends StatelessWidget {
final Icon icon;
final String label;
final Function onTap;
const _PostButton({
Key key,
@required this.icon,
@required this.label,
@required this.onTap,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
height: 25.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
icon,
const SizedBox(width: 4.0),
Text(label),
],
),
),
),
),
);
}
}
class _AvatarImage extends StatelessWidget{
final String profileAvatarImage;
const _AvatarImage({
Key key,
@required this.profileAvatarImage,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
child: Stack(
children: [
CircleAvatar(
radius: 20.0,
backgroundColor: Colors.grey[200],
backgroundImage: NetworkImage(profileAvatarImage!=null?profileAvatarImage:"https://qph.fs.quoracdn.net/main-qimg-11ef692748351829b4629683eff21100.webp"),
),
]
),
);
}
}
| 0 |
mirrored_repositories/FacebookClone-Flutter/lib | mirrored_repositories/FacebookClone-Flutter/lib/Widget/AddPost.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
void main() {
runApp(AddPost());
}
class AddPost extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return AddPostPage();
}
}
class AddPostPage extends StatefulWidget {
AddPostPage({Key key, this.title}) : super(key: key);
final String title;
@override
_AddPostState createState() => _AddPostState();
}
class _AddPostState extends State<AddPostPage> {
@override
Widget build(BuildContext context) {
return Card(
elevation: 0.0,
child: Container(
padding: const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, 0.0),
color: Colors.white,
child: Column(
children: [
Row(
children: [
Stack(
children: [
CircleAvatar(
radius: 20.0,
backgroundColor: Color(0xFF1777F2),
child: CircleAvatar(
radius: 20.0,
backgroundColor: Colors.grey[200],
backgroundImage: NetworkImage(
"https://qph.fs.quoracdn.net/main-qimg-11ef692748351829b4629683eff21100.webp"),
),
),
],
),
const SizedBox(width: 20.0),
Expanded(
child: TextField(
decoration: InputDecoration.collapsed(
hintText: 'What\'s on your mind?',
),
),
)
],
),
const Divider(height: 20.0, thickness: 0.5),
Container(
height: 40.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton.icon(
onPressed: () => print('Live'),
icon: const Icon(
MdiIcons.videoImage,
color: Colors.red,
size: 20,
),
label: Text('Live'),
),
const VerticalDivider(
width: 8.0,
),
ElevatedButton.icon(
onPressed: () => print('Photo'),
icon: const Icon(
Icons.photo_library,
color: Colors.lightGreen,
size: 20,
),
label: Text('Photo'),
),
const VerticalDivider(width: 8.0),
ElevatedButton.icon(
onPressed: () => print('Room'),
icon: const Icon(
Icons.video_call,
color: Colors.deepPurpleAccent,
size: 20,
),
label: Text('Room'),
),
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/FacebookClone-Flutter/lib | mirrored_repositories/FacebookClone-Flutter/lib/Widget/AppBarButton.dart | import 'package:flutter/material.dart';
class AppBarButton extends StatelessWidget {
final IconData icon;
final double iconSize;
final Function onPressed;
const AppBarButton({
Key key,
@required this.icon, this.iconSize, this.onPressed,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
height: 40,
width: 40,
margin: const EdgeInsets.all(6.0),
decoration: BoxDecoration(
color: Color(0xFFe6eef5),
shape: BoxShape.circle,
),
child: IconButton(
icon: Icon(icon),
iconSize: iconSize,
color: Colors.black,
onPressed: onPressed,
),
);
}
} | 0 |
mirrored_repositories/FacebookClone-Flutter/lib | mirrored_repositories/FacebookClone-Flutter/lib/Widget/Stories.dart | import 'package:facebookclone/Widget/CreateRoom.dart';
import 'package:flutter/material.dart';
import 'package:facebookclone/Widget/AddPost.dart';
void main() {
runApp(StoriesScreen());
}
class StoriesScreen extends StatelessWidget {
String StoryImage;
String userImage;
String userName;
bool first = false;
StoriesScreen({Key key, this.StoryImage, this.userImage, this.userName, this.first}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return StoriesScreenPage(StoryImage: this.StoryImage, userImage: this.userImage, userName: this.userName, first: this.first,);
}
}
class StoriesScreenPage extends StatefulWidget {
StoriesScreenPage({Key key, this.StoryImage, this.userName, this.userImage, this.first}) : super(key: key);
String StoryImage;
String userImage;
String userName;
bool first = false;
@override
_StoriesScreenState createState() => _StoriesScreenState();
}
class _StoriesScreenState extends State<StoriesScreenPage> {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(left: 10,bottom: 10,top: 10),
child: AspectRatio(
aspectRatio: 1.6/2.6,
child: Container(
margin: EdgeInsets.only(right: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
image: DecorationImage(
image: NetworkImage(widget.first?"https://qph.fs.quoracdn.net/main-qimg-11ef692748351829b4629683eff21100.webp":widget.StoryImage),
fit: BoxFit.cover
),
),
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
gradient: LinearGradient(
begin: Alignment.bottomRight,
colors: [
Colors.black.withOpacity(.9),
Colors.black.withOpacity(.1),
]
)
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
widget.first?
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
border: Border.all(color: Colors.white, width: 2),
),
child: Icon(Icons.add,color: Color(0xFF1777F2),),
)
:
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.white, width: 2),
image: DecorationImage(
image: NetworkImage(widget.userImage),
fit: BoxFit.cover
)
),
),
Text(widget.userName, style: TextStyle(color: Colors.white),)
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/FacebookClone-Flutter/lib | mirrored_repositories/FacebookClone-Flutter/lib/Widget/CreateRoom.dart | import 'package:flutter/material.dart';
import 'package:facebookclone/Widget/AddPost.dart';
void main() {
runApp(CreateRoomScreen());
}
class CreateRoomScreen extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return CreateRoomScreenPage();
}
}
class CreateRoomScreenPage extends StatefulWidget {
CreateRoomScreenPage({Key key, this.title}) : super(key: key);
final String title;
@override
_CreateRoomState createState() => _CreateRoomState();
}
class _CreateRoomState extends State<CreateRoomScreenPage> {
@override
Widget build(BuildContext context) {
return Card(
elevation: 0.0,
child: Container(
height: 80.0,
color: Colors.white,
child: Row(
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: _CreateRoomButton(),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: Row(
children: [
_AvatarImage(
profileAvatarImage:
"https://i.insider.com/57bf2f13956abc1d008b45f9?width=957&format=jpeg",
),
_AvatarImage(
profileAvatarImage:
"https://vignette.wikia.nocookie.net/marvelcinematicuniverse/images/0/0a/Nick_Fury_Textless_AoU_Poster.jpg/revision/latest/top-crop/width/360/height/360?cb=20161119163035",
),
_AvatarImage(
profileAvatarImage:
"https://cnet4.cbsistatic.com/img/hajPWxWk1aqwW7RiIRRZlIYsHBg=/940x0/2019/05/06/b8c3ae69-a9e4-4542-bc28-7a88e890b7cd/spider-man-far-from-home-sony.png",
),
],
),
)
],
),
),
);
}
}
class _GradientButtonRoom extends StatelessWidget {
_GradientButtonRoom({this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return ShaderMask(
shaderCallback: (bounds) {
return RadialGradient(
center: Alignment.topLeft,
radius: 1,
colors: [Colors.blue, Colors.pinkAccent],
tileMode: TileMode.clamp,
).createShader(bounds);
},
child: child,
);
}
}
class _AvatarImage extends StatelessWidget {
final String profileAvatarImage;
const _AvatarImage({
Key key,
@required this.profileAvatarImage,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
child: Stack(children: [
CircleAvatar(
radius: 20.0,
backgroundColor: Colors.grey[200],
backgroundImage: NetworkImage(profileAvatarImage != ""
? profileAvatarImage
: "https://qph.fs.quoracdn.net/main-qimg-11ef692748351829b4629683eff21100.webp"),
),
Positioned(
bottom: 0.0,
right: 0.0,
child: Container(
height: 15.0,
width: 15.0,
decoration: BoxDecoration(
color: Color(0xFF50b525),
shape: BoxShape.circle,
border: Border.all(
width: 2.0,
color: Colors.white,
),
),
),
)
]),
);
}
}
class _CreateRoomButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: 50,
width: 120,
child: OutlinedButton(
onPressed: () {
print('create Room');
},
style: OutlinedButton.styleFrom(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(35.0)),
side: BorderSide(color: Colors.blue[100], width: 1.0), // HERE
),
child: Row(
children: [
_GradientButtonRoom(
child: Icon(
Icons.video_call,
size: 25,
color: Colors.white,
),
),
const SizedBox(width: 7.0),
Text('Create\nRoom'),
],
),
),
);
}
}
| 0 |
mirrored_repositories/FacebookClone-Flutter | mirrored_repositories/FacebookClone-Flutter/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:facebookclone/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/flutter_network_call_base | mirrored_repositories/flutter_network_call_base/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_network_call_base/screens/user_list.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: UserListScreen(),
theme: ThemeData(useMaterial3: false),
);
}
}
| 0 |
mirrored_repositories/flutter_network_call_base/lib | mirrored_repositories/flutter_network_call_base/lib/models/user.dart | class User {
final int id;
final String name;
final String email;
final String avatar;
User(this.id, this.name, this.email, this.avatar);
factory User.fromJson(Map<String, dynamic> json) {
return User(
json["id"],
json["first_name"] + " " + json["last_name"],
json["email"],
json["avatar"],
);
}
static List<User> parseList(List<dynamic> list) {
return list.map((i) => User.fromJson(i)).toList();
}
}
| 0 |
mirrored_repositories/flutter_network_call_base/lib | mirrored_repositories/flutter_network_call_base/lib/util/network.dart | import 'dart:convert';
import 'package:flutter_network_call_base/models/user.dart';
import 'package:http/http.dart' as http;
const String BASE_URL = "https://reqres.in/api/";
Future<List<User>> getUserList() async {
final response = await http.get(Uri.parse("${BASE_URL}users?per_page=12"));
var jsonData = json.decode(response.body);
return User.parseList(jsonData["data"]);
}
Future<User> getUserDetail(int userId) async {
final response = await http.get(Uri.parse("${BASE_URL}users/$userId"));
var jsonData = json.decode(response.body);
return User.fromJson(jsonData["data"]);
}
| 0 |
mirrored_repositories/flutter_network_call_base/lib | mirrored_repositories/flutter_network_call_base/lib/util/base.dart | import 'dart:async';
import 'package:flutter/material.dart';
abstract class BaseStatefulWidget extends StatefulWidget {
String getTitle();
Widget body(dynamic data);
Future<dynamic> future();
@override
State<StatefulWidget> createState() => BaseState(getTitle());
}
class BaseState extends State<BaseStatefulWidget> {
final String title;
late Future<dynamic> future;
BaseState(this.title);
@override
void initState() {
super.initState();
future = widget.future();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: FutureBuilder(
future: future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
return snapshot.connectionState == ConnectionState.done
? snapshot.hasData
? widget.body(snapshot.data)
: InkWell(
child: Center(
child: Text("Failed to connect ! Tap to retry !!"),
),
onTap: () => setState(() => future = widget.future()),
)
: Center(child: CircularProgressIndicator());
},
),
);
}
}
| 0 |
mirrored_repositories/flutter_network_call_base/lib | mirrored_repositories/flutter_network_call_base/lib/screens/user_list.dart | import 'package:flutter/material.dart';
import 'package:flutter_network_call_base/models/user.dart';
import 'package:flutter_network_call_base/screens/user_detail.dart';
import 'package:flutter_network_call_base/util/base.dart';
import 'package:flutter_network_call_base/util/network.dart';
class UserListScreen extends BaseStatefulWidget {
@override
Widget body(dynamic data) {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
User user = data[index];
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UserDetailScreen(
user.id,
user.name,
),
),
);
},
child: Card(
child: ListTile(
leading: CircleAvatar(
child: Image.network(user.avatar),
backgroundColor: Colors.transparent,
),
title: Text(user.name),
subtitle: Text(user.email),
),
),
);
},
);
}
@override
Future<List<User>> future() => getUserList();
@override
String getTitle() => "Users";
}
| 0 |
mirrored_repositories/flutter_network_call_base/lib | mirrored_repositories/flutter_network_call_base/lib/screens/user_detail.dart | import 'package:flutter/material.dart';
import 'package:flutter_network_call_base/models/user.dart';
import 'package:flutter_network_call_base/util/base.dart';
import 'package:flutter_network_call_base/util/network.dart';
class UserDetailScreen extends BaseStatefulWidget {
final int id;
final String name;
UserDetailScreen(this.id, this.name);
@override
Widget body(dynamic data) {
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: <Widget>[
Image.network(
data.avatar,
height: 160,
width: 160,
),
Container(height: 24),
Card(
child: ListTile(
title: Text("Name"),
subtitle: Text(data.name),
),
),
Card(
child: ListTile(
title: Text("Email"),
subtitle: Text(data.email),
),
),
],
),
);
}
@override
Future<User> future() => getUserDetail(id);
@override
String getTitle() => name;
}
| 0 |
mirrored_repositories/Productos-App-Flutter | mirrored_repositories/Productos-App-Flutter/lib/main.dart | import 'package:flutter/material.dart';
import 'package:productos_app/screens/screens.dart';
import 'package:productos_app/services/services.dart';
import 'package:provider/provider.dart';
void main() => runApp(AppState());
class AppState extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => AuthService()),
ChangeNotifierProvider(create: (_) => ProductsService()),
],
child: MyApp(),
);
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Productos App',
initialRoute: 'login',
routes: {
'login': (_) => LoginScreen(),
'register': (_) => RegisterScreen(),
'home': (_) => HomeScreen(),
'product': (_) => ProductScreen(),
'checking': (_) => CheckAuthScreen(),
},
scaffoldMessengerKey: NotificationsService.messengerKey,
theme: ThemeData.light().copyWith(
scaffoldBackgroundColor: Colors.grey[300],
appBarTheme: AppBarTheme(elevation: 0, color: Colors.indigo[900]),
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: Colors.indigo[900],
elevation: 0,
)),
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/widgets/product_image.dart | import 'dart:io';
import 'package:flutter/material.dart';
class ProductImage extends StatelessWidget {
final String? url;
const ProductImage({Key? key, this.url}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(left: 10, right: 10, top: 10),
child: Container(
decoration: _buildBoxDecoration(),
width: double.infinity,
height: 450,
child: Opacity(
opacity: 0.9,
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(45), topRight: Radius.circular(45)),
child: getImage(url)),
),
),
);
}
BoxDecoration _buildBoxDecoration() => BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(45), topRight: Radius.circular(45)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 10,
offset: Offset(0, 5))
]);
Widget getImage(String? picture) {
if (picture == null)
//this.url == null
return Image(
image: AssetImage('assets/no-image.png'),
fit: BoxFit.cover,
);
if (picture.startsWith('http'))
return FadeInImage(
image: NetworkImage(this.url!),
placeholder: AssetImage('assets/jar-loading.gif'),
fit: BoxFit.cover,
);
return Image.file(
File(picture),
fit: BoxFit.cover,
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/widgets/card_container.dart | import 'package:flutter/material.dart';
class CardContainer extends StatelessWidget {
final Widget child;
const CardContainer({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 30),
child: Container(
width: double.infinity,
padding: EdgeInsets.all(20),
decoration: _createCardShape(),
child: this.child,
),
);
}
BoxDecoration _createCardShape() => BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(25),
boxShadow: [
BoxShadow(
color: Colors.black12, blurRadius: 15, offset: Offset(0, 5))
]);
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/widgets/auth_background.dart | import 'package:flutter/material.dart';
class AuthBackground extends StatelessWidget {
final Widget child;
const AuthBackground({Key? key, required this.child}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
//color: Colors.red,
width: double.infinity,
height: double.infinity,
child: Stack(
children: [
_PurpleBox(),
_HeaderIcon(),
this.child,
],
),
);
}
}
class _HeaderIcon extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Container(
width: double.infinity,
margin: EdgeInsets.only(top: 30),
child: Icon(Icons.person_pin, color: Colors.white, size: 100),
),
);
}
}
class _PurpleBox extends StatelessWidget {
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Container(
width: double.infinity,
height: size.height * 0.45,
decoration: _purpleBackground(),
child: Stack(
children: [
Positioned(child: _Bubble(), top: 90, left: 30),
Positioned(child: _Bubble(), top: -40, left: -30),
Positioned(child: _Bubble(), top: -50, right: -20),
Positioned(child: _Bubble(), bottom: -50, left: 10),
Positioned(child: _Bubble(), bottom: 120, left: 20),
],
),
);
}
BoxDecoration _purpleBackground() => BoxDecoration(
gradient: LinearGradient(colors: [
Color.fromRGBO(63, 63, 156, 1),
Color.fromRGBO(90, 70, 178, 1)
]));
}
class _Bubble extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
width: 100,
height: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
color: Color.fromRGBO(255, 255, 255, 0.05)),
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/widgets/product_card.dart | import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:productos_app/models/models.dart';
class ProductCard extends StatelessWidget {
final Product product;
const ProductCard({Key? key, required this.product}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Container(
margin: EdgeInsets.only(top: 30, bottom: 50),
width: double.infinity,
height: 400,
decoration: _cardBorders(),
child: Stack(
alignment: Alignment.bottomLeft,
children: [
_BackgroundImage(product.picture),
_ProductDetails(
title: product.name,
subtitle: product.id!,
),
Positioned(top: 0, right: 0, child: _PriceTag(product.price)),
if (!product.available)
Positioned(top: 0, left: 0, child: _NotAvailable())
],
),
),
);
}
BoxDecoration _cardBorders() => BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(25),
boxShadow: [
BoxShadow(
color: Colors.black12, offset: Offset(0, 7), blurRadius: 10)
]);
}
class _NotAvailable extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: FittedBox(
fit: BoxFit.contain,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Text(
'No disponible',
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
width: 100,
height: 70,
decoration: BoxDecoration(
color: Colors.yellow[800],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(25), bottomRight: Radius.circular(25))),
);
}
}
class _PriceTag extends StatelessWidget {
final double price;
const _PriceTag(this.price);
@override
Widget build(BuildContext context) {
return Container(
child: FittedBox(
fit: BoxFit.contain,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Text('\$$price',
style: TextStyle(color: Colors.white, fontSize: 20))),
),
width: 100,
height: 70,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.indigo[900],
borderRadius: BorderRadius.only(
topRight: Radius.circular(25), bottomLeft: Radius.circular(25))),
);
}
}
class _ProductDetails extends StatelessWidget {
final String title;
final String subtitle;
const _ProductDetails({required this.title, required this.subtitle});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(right: 50),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
width: double.infinity,
height: 70,
decoration: _buildBoxDecoration(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontSize: 20,
color: Colors.white,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Text(
subtitle,
style: TextStyle(
fontSize: 15,
color: Colors.white,
),
)
],
),
),
);
}
BoxDecoration _buildBoxDecoration() => BoxDecoration(
color: Colors.indigo[900],
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(25), topRight: Radius.circular(25)));
}
class _BackgroundImage extends StatelessWidget {
final String? url;
const _BackgroundImage(this.url);
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Container(
width: double.infinity,
height: 400,
child: url == null
? Image(
image: AssetImage('assets/no-image.png'),
fit: BoxFit.cover,
)
: FadeInImage(
placeholder: AssetImage('assets/jar-loading.gif'),
image: NetworkImage(url!),
fit: BoxFit.cover,
),
),
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/widgets/widgets.dart | export 'package:productos_app/widgets/auth_background.dart';
export 'package:productos_app/widgets/card_container.dart';
export 'package:productos_app/widgets/product_card.dart';
export 'package:productos_app/widgets/product_image.dart';
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/models/product.dart | // To parse this JSON data, do
//
// final product = productFromMap(jsonString);
import 'dart:convert';
class Product {
Product(
{required this.available,
required this.name,
this.picture,
required this.price,
this.id});
bool available;
String name;
String? picture;
double price;
String? id;
factory Product.fromJson(String str) => Product.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Product.fromMap(Map<String, dynamic> json) => Product(
available: json["available"],
name: json["name"],
picture: json["picture"],
price: json["price"].toDouble(),
);
Map<String, dynamic> toMap() => {
"available": available,
"name": name,
"picture": picture,
"price": price,
};
Product copy() => Product(
available: this.available,
name: this.name,
picture: this.picture,
price: this.price,
id: this.id,
);
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/models/models.dart | export 'package:productos_app/models/product.dart';
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/ui/input_decorations.dart | import 'package:flutter/material.dart';
class InputDecorations {
static InputDecoration authInputDecoration(
{required String hintText,
required String labelText,
IconData? prefixIcon}) {
return InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.deepPurple),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.deepPurple, width: 2)),
hintText: hintText,
labelText: labelText,
labelStyle: TextStyle(color: Colors.grey),
prefixIcon: prefixIcon != null
? Icon(prefixIcon, color: Colors.deepPurple)
: null);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/services/notifications_service.dart | import 'package:flutter/material.dart';
class NotificationsService {
static GlobalKey<ScaffoldMessengerState> messengerKey =
new GlobalKey<ScaffoldMessengerState>();
static showSnackbar(String message) {
final snackBar = new SnackBar(
content:
Text(message, style: TextStyle(color: Colors.white, fontSize: 20)),
);
messengerKey.currentState!.showSnackBar(snackBar);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/services/services.dart | export 'package:productos_app/services/products_service.dart';
export 'package:productos_app/services/auth_service.dart';
export 'package:productos_app/services/notifications_service.dart';
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/services/products_service.dart | import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:productos_app/models/models.dart';
import 'package:http/http.dart' as http;
class ProductsService extends ChangeNotifier {
final String _baseUrl =
'flutter-varios-6a68f-default-rtdb.europe-west1.firebasedatabase.app';
final List<Product> products = [];
late Product selectedProduct;
final storage = new FlutterSecureStorage();
File? newPictureFile;
bool isLoading = true;
bool isSaving = false;
ProductsService() {
this.LoadProducts();
}
Future<List<Product>> LoadProducts() async {
this.isLoading = true;
notifyListeners();
final url = Uri.https(_baseUrl, 'products.json',
{'auth': await storage.read(key: 'token') ?? ''});
final resp = await http.get(
url,
);
final Map<String, dynamic> productsMap = json.decode(resp.body);
productsMap.forEach((key, value) {
final tempProduct = Product.fromMap(value);
tempProduct.id = key;
this.products.add(tempProduct);
});
this.isLoading = false;
notifyListeners();
return this.products;
}
Future saveOrCreateProduct(Product product) async {
isSaving = true;
notifyListeners();
if (product.id == null) {
//Es necesario crear
await this.createProduct(product);
} else {
//Actualizar
await this.updateProduct(product);
}
isSaving = false;
notifyListeners();
}
Future<String> updateProduct(Product product) async {
final url = Uri.https(_baseUrl, 'products/${product.id}.json',
{'auth': await storage.read(key: 'token') ?? ''});
final resp = await http.put(
url,
body: product.toJson(),
);
final decodeData = resp.body;
//TODO:Actualizar el listado de productos
final index =
this.products.indexWhere((element) => element.id == product.id);
this.products[index] = product;
return product.id!;
}
Future<String> createProduct(Product product) async {
final url = Uri.https(_baseUrl, 'products.json',
{'auth': await storage.read(key: 'token') ?? ''});
final resp = await http.post(url, body: product.toJson());
final decodeData = json.decode(resp.body);
product.id = decodeData['name'];
this.products.add(product);
return product.id!;
}
void updateSelectedProductImage(String path) {
this.selectedProduct.picture = path;
this.newPictureFile = File.fromUri(Uri(path: path));
notifyListeners();
}
Future<String?> uploadImage() async {
if (this.newPictureFile == null) return null;
this.isSaving = true;
notifyListeners();
final url = Uri.parse(
'https://api.cloudinary.com/v1_1/mcode/image/upload?upload_preset=vq6dxpmb');
final imageUploadRequest = http.MultipartRequest('POST', url);
final file =
await http.MultipartFile.fromPath('file', newPictureFile!.path);
imageUploadRequest.files.add(file);
final streamResponse = await imageUploadRequest.send();
final resp = await http.Response.fromStream(streamResponse);
if (resp.statusCode != 200 && resp.statusCode != 201) {
print('algo salio mal');
print(resp.body);
return null;
}
this.newPictureFile = null;
final decodeData = json.decode(resp.body);
return decodeData['secure_url'];
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/services/auth_service.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
class AuthService extends ChangeNotifier {
final String _baseUrl = 'identitytoolkit.googleapis.com';
final String _firebaseToken = 'AIzaSyB-T6vWj-PEkTLEvKOb7MdxQOH2ohxnBBQ';
final storage = new FlutterSecureStorage();
//Si retornamos algo,es un error,si no todo bien
Future<String?> createUser(String email, String password) async {
final Map<String, dynamic> authData = {
'email': email,
'password': password,
'returnSecureToken': true
};
final url =
Uri.https(_baseUrl, '/v1/accounts:signUp', {'key': _firebaseToken});
final resp = await http.post(url, body: json.encode(authData));
final Map<String, dynamic> decodedResp = json.decode(resp.body);
if (decodedResp.containsKey('idToken')) {
//Token hay que guardarlo en un lugar seguro
await storage.write(key: 'token', value: decodedResp['idToken']);
//decodedResp['idToken'];
return null;
} else {
return decodedResp['error']['message'];
}
}
Future<String?> login(String email, String password) async {
final Map<String, dynamic> authData = {
'email': email,
'password': password,
'returnSecureToken': true
};
final url = Uri.https(
_baseUrl, '/v1/accounts:signInWithPassword', {'key': _firebaseToken});
final resp = await http.post(url, body: json.encode(authData));
final Map<String, dynamic> decodedResp = json.decode(resp.body);
if (decodedResp.containsKey('idToken')) {
//Token hay que guardarlo en un lugar seguro
//decodedResp['idToken'];
await storage.write(key: 'token', value: decodedResp['idToken']);
return null;
} else {
return decodedResp['error']['message'];
}
}
Future logout() async {
await storage.delete(key: 'token');
return;
}
Future<String> readToken() async {
return await storage.read(key: 'token') ?? '';
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/screens/check_auth_screen.dart | import 'package:flutter/material.dart';
import 'package:productos_app/screens/screens.dart';
import 'package:productos_app/services/services.dart';
import 'package:provider/provider.dart';
class CheckAuthScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final authService = Provider.of<AuthService>(context, listen: false);
return Scaffold(
body: Center(
child: FutureBuilder(
future: authService.readToken(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (!snapshot.hasData) return Text('');
if (snapshot.data == '') {
Future.microtask(() {
Navigator.pushReplacement(
context,
PageRouteBuilder(
pageBuilder: (_, __, ___) => LoginScreen(),
transitionDuration: Duration(seconds: 0)));
});
} else {
Future.microtask(() {
Navigator.pushReplacement(
context,
PageRouteBuilder(
pageBuilder: (_, __, ___) => HomeScreen(),
transitionDuration: Duration(seconds: 0)));
});
}
return Container();
},
),
),
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/screens/screens.dart | export 'package:productos_app/screens/home_screen.dart';
export 'package:productos_app/screens/login_screen.dart';
export 'package:productos_app/screens/product_screen.dart';
export 'package:productos_app/screens/loading_screen.dart';
export 'package:productos_app/screens/register_screen.dart';
export 'package:productos_app/screens/check_auth_screen.dart';
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/screens/loading_screen.dart | import 'package:flutter/material.dart';
class LoadingScreem extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Products'),
),
body: Center(
child: CircularProgressIndicator(
color: Colors.indigo,
),
),
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/screens/home_screen.dart | import 'package:flutter/material.dart';
import 'package:productos_app/models/models.dart';
import 'package:productos_app/screens/screens.dart';
import 'package:productos_app/services/services.dart';
import 'package:productos_app/widgets/product_card.dart';
import 'package:provider/provider.dart';
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final productsService = Provider.of<ProductsService>(context);
final authService = Provider.of<AuthService>(context, listen: false);
if (productsService.isLoading) return LoadingScreem();
return Scaffold(
appBar: AppBar(
title: Text('Productos'),
leading: IconButton(
onPressed: () {
authService.logout();
Navigator.pushReplacementNamed(context, 'login');
},
icon: Icon(Icons.login_outlined)),
),
body: ListView.builder(
itemCount: productsService.products.length,
itemBuilder: (BuildContext context, int index) => GestureDetector(
onTap: () {
productsService.selectedProduct =
productsService.products[index].copy();
Navigator.pushNamed(context, 'product');
},
child: ProductCard(
product: productsService.products[index],
),
)),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
productsService.selectedProduct =
new Product(available: false, name: '', price: 0);
Navigator.pushNamed(context, 'product');
},
),
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/screens/register_screen.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:productos_app/providers/login_form_provider.dart';
import 'package:productos_app/services/services.dart';
import 'package:provider/provider.dart';
import 'package:productos_app/ui/input_decorations.dart';
import 'package:productos_app/widgets/auth_background.dart';
import 'package:productos_app/widgets/card_container.dart';
class RegisterScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: AuthBackground(
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 240),
CardContainer(
child: Column(
children: [
SizedBox(height: 10),
Text('Crear cuenta',
style: Theme.of(context).textTheme.headline4),
SizedBox(height: 30),
ChangeNotifierProvider(
create: (_) => LoginFormProvider(),
child: _LoginForm(),
),
//_LoginForm()
],
)),
SizedBox(height: 50),
TextButton(
onPressed: () => Navigator.pushReplacementNamed(context, 'login'),
style: ButtonStyle(
overlayColor:
MaterialStateProperty.all(Colors.indigo.withOpacity(0.1)),
shape: MaterialStateProperty.all(StadiumBorder())),
child: Text('¿Ya tienes una cuenta?',
style: TextStyle(fontSize: 18, color: Colors.black87)),
),
SizedBox(height: 50),
],
),
)));
}
}
class _LoginForm extends StatelessWidget {
@override
Widget build(BuildContext context) {
final loginForm = Provider.of<LoginFormProvider>(context);
return Container(
child: Form(
key: loginForm.formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
children: [
TextFormField(
autocorrect: false,
keyboardType: TextInputType.emailAddress,
decoration: InputDecorations.authInputDecoration(
hintText: '[email protected]',
labelText: 'Correo electronico',
prefixIcon: Icons.alternate_email_rounded),
onChanged: (value) => loginForm.email = value,
validator: (value) {
String pattern =
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regExp = new RegExp(pattern);
return regExp.hasMatch(value ?? '')
? null
: 'El correo no es correcto';
},
),
SizedBox(height: 30),
TextFormField(
autocorrect: false,
obscureText: true,
keyboardType: TextInputType.emailAddress,
decoration: InputDecorations.authInputDecoration(
hintText: '*****',
labelText: 'Contraeña',
prefixIcon: Icons.lock_outline),
onChanged: (value) => loginForm.password = value,
validator: (value) {
return (value != null && value.length >= 6)
? null
: 'La contraseña debe ser de 6 caracteres';
},
),
SizedBox(height: 30),
MaterialButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
disabledColor: Colors.grey,
elevation: 0,
color: Colors.deepPurple,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 80, vertical: 15),
child: Text(
loginForm.isLoading ? 'Espere' : 'Imgresar',
style: TextStyle(color: Colors.white),
)),
onPressed: loginForm.isLoading
? null
: () async {
FocusScope.of(context).unfocus();
final authService =
Provider.of<AuthService>(context, listen: false);
if (!loginForm.isValidForm()) return;
loginForm.isLoading = true;
// TODO: validar si el login es correcto
final String? errorMessage = await authService
.createUser(loginForm.email, loginForm.password);
if (errorMessage == null) {
Navigator.pushReplacementNamed(context, 'home');
} else {
//TODO:mostrar error en pantalla
print(errorMessage);
loginForm.isLoading = false;
}
})
],
),
),
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/screens/login_screen.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:productos_app/providers/login_form_provider.dart';
import 'package:productos_app/services/services.dart';
import 'package:provider/provider.dart';
import 'package:productos_app/ui/input_decorations.dart';
import 'package:productos_app/widgets/auth_background.dart';
import 'package:productos_app/widgets/card_container.dart';
class LoginScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: AuthBackground(
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 240),
CardContainer(
child: Column(
children: [
SizedBox(height: 10),
Text('Login', style: Theme.of(context).textTheme.headline4),
SizedBox(height: 30),
ChangeNotifierProvider(
create: (_) => LoginFormProvider(),
child: _LoginForm(),
),
//_LoginForm()
],
)),
SizedBox(height: 50),
TextButton(
onPressed: () =>
Navigator.pushReplacementNamed(context, 'register'),
style: ButtonStyle(
overlayColor:
MaterialStateProperty.all(Colors.indigo.withOpacity(0.1)),
shape: MaterialStateProperty.all(StadiumBorder())),
child: Text('Crear una nueva cuenta',
style: TextStyle(fontSize: 18, color: Colors.black87)),
),
SizedBox(height: 50),
],
),
)));
}
}
class _LoginForm extends StatelessWidget {
@override
Widget build(BuildContext context) {
final loginForm = Provider.of<LoginFormProvider>(context);
return Container(
child: Form(
key: loginForm.formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
children: [
TextFormField(
autocorrect: false,
keyboardType: TextInputType.emailAddress,
decoration: InputDecorations.authInputDecoration(
hintText: '[email protected]',
labelText: 'Correo electronico',
prefixIcon: Icons.alternate_email_rounded),
onChanged: (value) => loginForm.email = value,
validator: (value) {
String pattern =
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regExp = new RegExp(pattern);
return regExp.hasMatch(value ?? '')
? null
: 'El correo no es correcto';
},
),
SizedBox(height: 30),
TextFormField(
autocorrect: false,
obscureText: true,
keyboardType: TextInputType.emailAddress,
decoration: InputDecorations.authInputDecoration(
hintText: '*****',
labelText: 'Contraeña',
prefixIcon: Icons.lock_outline),
onChanged: (value) => loginForm.password = value,
validator: (value) {
return (value != null && value.length >= 6)
? null
: 'La contraseña debe ser de 6 caracteres';
},
),
SizedBox(height: 30),
MaterialButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
disabledColor: Colors.grey,
elevation: 0,
color: Colors.deepPurple,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 80, vertical: 15),
child: Text(
loginForm.isLoading ? 'Espere' : 'Imgresar',
style: TextStyle(color: Colors.white),
)),
onPressed: loginForm.isLoading
? null
: () async {
FocusScope.of(context).unfocus();
final authService =
Provider.of<AuthService>(context, listen: false);
if (!loginForm.isValidForm()) return;
loginForm.isLoading = true;
// TODO: validar si el login es correcto
final String? errorMessage = await authService.login(
loginForm.email, loginForm.password);
if (errorMessage == null) {
Navigator.pushReplacementNamed(context, 'home');
} else {
//TODO:mostrar error en pantalla
//print(errorMessage);
NotificationsService.showSnackbar(errorMessage);
loginForm.isLoading = false;
}
})
],
),
),
);
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/screens/product_screen.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:productos_app/providers/product_form_provider.dart';
import 'package:productos_app/services/services.dart';
import 'package:productos_app/ui/input_decorations.dart';
import 'package:productos_app/widgets/product_image.dart';
class ProductScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final productService = Provider.of<ProductsService>(context);
return ChangeNotifierProvider(
create: (_) => ProductFormProvider(productService.selectedProduct),
child: _ProductScreenBody(productService: productService),
);
}
}
class _ProductScreenBody extends StatelessWidget {
const _ProductScreenBody({
Key? key,
required this.productService,
}) : super(key: key);
final ProductsService productService;
@override
Widget build(BuildContext context) {
final productForm = Provider.of<ProductFormProvider>(context);
return Scaffold(
body: SingleChildScrollView(
//keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
child: Column(
children: [
Stack(
children: [
ProductImage(url: productService.selectedProduct.picture),
Positioned(
top: 60,
left: 20,
child: IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: Icon(Icons.arrow_back_ios_new,
size: 40, color: Colors.white))),
Positioned(
top: 60,
right: 20,
child: IconButton(
onPressed: () async {
final picker = new ImagePicker();
final PickedFile? pickedFile = await picker.getImage(
source: ImageSource.camera, imageQuality: 100);
if (pickedFile == null) {
print('No selecciono nada');
return;
}
productService
.updateSelectedProductImage(pickedFile.path);
},
icon: Icon(Icons.camera_alt_outlined,
size: 40, color: Colors.white)))
],
),
_ProductForm(),
SizedBox(height: 100),
],
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
floatingActionButton: FloatingActionButton(
child: productService.isSaving
? CircularProgressIndicator(color: Colors.white)
: Icon(Icons.save_outlined),
onPressed: productService.isSaving
? null
: () async {
if (!productForm.isValidForm()) return;
final String? imageUrl = await productService.uploadImage();
if (imageUrl != null) productForm.product.picture = imageUrl;
await productService.saveOrCreateProduct(productForm.product);
},
),
);
}
}
class _ProductForm extends StatelessWidget {
@override
Widget build(BuildContext context) {
final productForm = Provider.of<ProductFormProvider>(context);
final product = productForm.product;
return Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
width: double.infinity,
decoration: _buildBoxDecoration(),
child: Form(
key: productForm.formKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
child: Column(
children: [
SizedBox(height: 10),
TextFormField(
initialValue: product.name,
onChanged: (value) => product.name = value,
validator: (value) {
if (value == null || value.length < 1)
return 'El nombre es obligatorio';
},
decoration: InputDecorations.authInputDecoration(
hintText: 'Nombre del producto', labelText: 'Nombre:'),
),
SizedBox(height: 30),
TextFormField(
initialValue: '${product.price}',
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'^(\d+)?\.?\d{0,2}'))
],
onChanged: (value) {
if (double.tryParse(value) == null) {
product.price = 0;
} else {
product.price = double.parse(value);
}
},
keyboardType: TextInputType.number,
decoration: InputDecorations.authInputDecoration(
hintText: '\$150', labelText: 'Precio:'),
),
SizedBox(height: 30),
SwitchListTile.adaptive(
value: product.available,
title: Text('Disponible'),
activeColor: Colors.indigo,
onChanged: productForm.updateAvailability),
SizedBox(height: 30),
],
),
),
),
);
}
BoxDecoration _buildBoxDecoration() => BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(25),
bottomLeft: Radius.circular(25)),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
offset: Offset(0, 5),
blurRadius: 5)
]);
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/providers/product_form_provider.dart | import 'package:flutter/material.dart';
import 'package:productos_app/models/models.dart';
class ProductFormProvider extends ChangeNotifier {
GlobalKey<FormState> formKey = new GlobalKey<FormState>();
Product product;
ProductFormProvider(this.product);
updateAvailability(bool value) {
print(value);
this.product.available = value;
notifyListeners();
}
bool isValidForm() {
print(product.name);
print(product.price);
print(product.available);
return formKey.currentState?.validate() ?? false;
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter/lib | mirrored_repositories/Productos-App-Flutter/lib/providers/login_form_provider.dart | import 'package:flutter/material.dart';
class LoginFormProvider extends ChangeNotifier {
GlobalKey<FormState> formKey = new GlobalKey<FormState>();
String email = '';
String password = '';
bool _isLoading = false;
bool get isLoading => _isLoading;
set isLoading(bool value) {
_isLoading = value;
notifyListeners();
}
bool isValidForm() {
print(formKey.currentState?.validate());
print('$email - $password');
return formKey.currentState?.validate() ?? false;
}
}
| 0 |
mirrored_repositories/Productos-App-Flutter | mirrored_repositories/Productos-App-Flutter/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:productos_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/memes | mirrored_repositories/memes/lib/main.dart | import 'package:flutter/material.dart';
import 'package:memes/pages/homePage.dart';
import 'package:memes/pages/profilePage.dart';
import 'package:google_fonts/google_fonts.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return MaterialApp(
title: 'Top kek',
debugShowCheckedModeBanner: false,
theme: ThemeData(
brightness: Brightness.light,
backgroundColor: Colors.white,
primarySwatch: Colors.orange,
textTheme: GoogleFonts.latoTextTheme(textTheme),
),
darkTheme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.orange,
backgroundColor: Colors.black45,
textTheme: GoogleFonts.latoTextTheme(textTheme),
),
initialRoute: '/',
routes: {
'/': (context) => HomePage(),
'/profile': (context) => ProfilePage(),
},
);
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/constants/api.dart | const BASE_URL = 'forvovka.ru';
const MEMES = '/api/memes';
const FIRST_MEMES = '/api/get_memes';
const SET_REACTION = '/api/set_reaction';
const SIGN_IN = '/api/sign_up';
const SIGN_UP = '/api/sign_in'; | 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/constants/enum.dart | enum Reaction { like, dislike } | 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/widgets/scrollList.dart | import 'package:flutter/material.dart';
// import 'package:memes/components/scrollList/controls/onscreen_controls.dart';
import 'package:memes/components/scrollList/scroll_card.dart';
import 'package:memes/constants/enum.dart';
import 'package:memes/models/meme.dart';
import 'package:memes/api/memes_api.dart';
// import 'package:mixpanel_analytics/mixpanel_analytics.dart';
// import 'dart:async';
class ScrollList extends StatefulWidget {
@override
_ScrollListState createState() => _ScrollListState();
}
class _ScrollListState extends State<ScrollList> {
int cardsCounter = 0;
int currentMemIndex = 0;
bool loading = true;
List<Meme> memes = List();
List<ScrollCard> cards = List();
// MixpanelAnalytics _mixpanelAnalytics;
// final _user$ = StreamController<String>.broadcast();
@override
void initState() {
super.initState();
// _mixpanelAnalytics = MixpanelAnalytics(
// token: 'e28bf9b75c9895878a9eb63704b1fc92',
// userId$: _user$.stream,
// verbose: true,
// shouldAnonymize: true,
// shaFn: (value) => value,
// onError: (e) => print(e),
// );
// Init cards
getFirstMemes().then((res) {
for (cardsCounter = 0; cardsCounter < 3; cardsCounter++) {
cards.add(ScrollCard(res[cardsCounter]));
}
setState(() {
memes = res;
cards = cards;
loading = false;
});
});
}
// @override
// void dispose() {
// _user$.close();
// super.dispose();
// }
_onPageChange(int page) async {
var newMem = page + 3;
var reaction = Reaction.like;
if (memes.length < newMem) {
setState(() {
loading = true;
});
// await _mixpanelAnalytics.track(event: 'score_mem', properties: {
// 'feed': 'scroll',
// 'mem_id': memes[currentMemIndex].id,
// 'reaction': reaction
// });
scoreAndGetMem(memes[currentMemIndex].id, reaction, newMem).then((res) {
setState(() {
loading = false;
cards.add(ScrollCard(res[0]));
cardsCounter++;
memes = memes + res;
});
});
setState(() {
currentMemIndex = page;
});
}
// await _mixpanelAnalytics.track(
// event: 'change_mem',
// properties: {'feed': 'scroll', 'mem_id': memes[currentMemIndex].id});
}
@override
Widget build(BuildContext context) {
return PageView.builder(
onPageChanged: _onPageChange,
scrollDirection: Axis.vertical,
itemBuilder: (context, position) {
return Container(
child: Stack(
children: <Widget>[
memes.length < 2
? SizedBox.fromSize(child: CircularProgressIndicator())
: cards[position],
// onScreenControls(_mixpanelAnalytics, memes[currentMemIndex])
],
),
);
},
itemCount: cards.length);
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/widgets/swipeList.dart | import 'package:flutter/material.dart';
import 'package:memes/api/memes_api.dart';
import 'package:memes/models/meme.dart';
import 'package:flutter_share/flutter_share.dart';
import 'package:memes/components/swipeCard.dart';
import 'dart:math';
import 'package:memes/constants/enum.dart';
import 'package:mixpanel_analytics/mixpanel_analytics.dart';
import 'dart:async';
List<Alignment> cardsAlign = [
Alignment(0.0, 1.0),
Alignment(0.0, 0.8),
Alignment(0.0, 0.0)
];
List<Size> cardsSize = List(3);
class SwipeList extends StatefulWidget {
SwipeList(BuildContext context) {
cardsSize[0] = Size(MediaQuery.of(context).size.width * 0.9,
MediaQuery.of(context).size.height * 0.6);
cardsSize[1] = Size(MediaQuery.of(context).size.width * 0.85,
MediaQuery.of(context).size.height * 0.55);
cardsSize[2] = Size(MediaQuery.of(context).size.width * 0.8,
MediaQuery.of(context).size.height * 0.5);
}
@override
_SwipeListState createState() => _SwipeListState();
}
class _SwipeListState extends State<SwipeList>
with SingleTickerProviderStateMixin {
int cardsCounter = 0;
bool loading = true;
List<Meme> memes = List();
List<SwipeCard> cards = List();
AnimationController _controller;
MixpanelAnalytics _mixpanelAnalytics;
final _user$ = StreamController<String>.broadcast();
final Alignment defaultFrontCardAlign = Alignment(0.0, 0.0);
Alignment frontCardAlign;
double frontCardRot = 0.0;
Future<void> share() async {
await _mixpanelAnalytics.track(
event: 'share_mem', properties: {'mem_id': memes[cardsCounter - 3].id});
await FlutterShare.share(
title: 'Top Kek memes',
text: 'Top Kek memes',
linkUrl: memes[cardsCounter - 3].fileUrl,
chooserTitle: 'Memes app');
}
@override
void initState() {
super.initState();
// Init cards
getFirstMemes().then((res) {
for (cardsCounter = 0; cardsCounter < 3; cardsCounter++) {
cards.add(SwipeCard(res[cardsCounter]));
}
setState(() {
memes = res;
cards = cards;
loading = false;
});
});
_mixpanelAnalytics = MixpanelAnalytics(
token: 'e28bf9b75c9895878a9eb63704b1fc92',
userId$: _user$.stream,
verbose: true,
shouldAnonymize: true,
shaFn: (value) => value,
onError: (e) => print(e),
);
frontCardAlign = cardsAlign[2];
// Init the animation controller
_controller =
AnimationController(duration: Duration(milliseconds: 700), vsync: this);
_controller.addListener(() => setState(() {}));
_controller.addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) changeCardsOrder();
});
}
@override
void dispose() {
_user$.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
memesList(),
buttonsRow(),
],
);
}
Widget memesList() {
return Expanded(
child: Stack(
children: cards.length > 2
? <Widget>[
backCard(),
middleCard(),
frontCard(),
controller(),
loading
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(height: 50),
CircularProgressIndicator()
])
: Container(),
]
: <Widget>[loader()]));
}
Widget controller() {
return // Prevent swiping if the cards are animating
_controller.status != AnimationStatus.forward && !loading
? SizedBox.expand(
child: GestureDetector(
// While dragging the first card
onPanUpdate: (DragUpdateDetails details) {
// Add what the user swiped in the last frame to the alignment of the card
setState(() {
// 20 is the "speed" at which moves the card
frontCardAlign = Alignment(
frontCardAlign.x +
20 *
details.delta.dx /
MediaQuery.of(context).size.width,
frontCardAlign.y +
40 *
details.delta.dy /
MediaQuery.of(context).size.height);
frontCardRot = frontCardAlign.x; // * rotation speed;
});
},
// When releasing the first card
onPanEnd: (_) async {
// If the front card was swiped far enough to count as swiped
if (frontCardAlign.x > 3.0 || frontCardAlign.x < -3.0) {
scoreMem(frontCardAlign.x > 0
? Reaction.like
: Reaction.dislike);
animateCards();
await _mixpanelAnalytics.track(
event:
frontCardAlign.x > 0 ? 'like_mem' : 'dislike_mem',
properties: {
'mem_id': memes[cardsCounter - 3].id,
'feed': 'swipe',
'method': 'swipe',
});
} else {
// Return to the initial rotation and alignment
setState(() {
frontCardAlign = defaultFrontCardAlign;
frontCardRot = 0.0;
});
}
},
))
: Container();
}
Widget buttonsRow() {
return Container(
margin: EdgeInsets.symmetric(vertical: 48.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
FloatingActionButton(
heroTag: "report",
mini: true,
onPressed: loading
? null
: () async {
frontCardAlign = Alignment(-1.0, frontCardAlign.y);
scoreMem(Reaction.dislike);
animateCards();
await _mixpanelAnalytics
.track(event: 'report_mem', properties: {
'mem_id': memes[cardsCounter - 3].id,
'feed': 'swipe',
});
},
backgroundColor: Colors.white,
child: Icon(Icons.report, color: Colors.redAccent),
),
Padding(padding: EdgeInsets.only(right: 8.0)),
FloatingActionButton(
heroTag: "dislike",
onPressed: loading
? null
: () async {
frontCardAlign = Alignment(-1.0, frontCardAlign.y);
scoreMem(Reaction.dislike);
animateCards();
await _mixpanelAnalytics
.track(event: 'dislike_mem', properties: {
'mem_id': memes[cardsCounter - 3].id,
'feed': 'swipe',
'method': 'button',
});
},
backgroundColor: Colors.white,
child: Icon(Icons.close, color: Colors.red),
),
Padding(padding: EdgeInsets.only(right: 8.0)),
FloatingActionButton(
heroTag: "like",
onPressed: loading
? null
: () async {
frontCardAlign = Alignment(1.0, frontCardAlign.y);
scoreMem(Reaction.like);
animateCards();
await _mixpanelAnalytics
.track(event: 'like_mem', properties: {
'mem_id': memes[cardsCounter - 3].id,
'feed': 'swipe',
'method': 'button',
});
},
backgroundColor: Colors.white,
child: Icon(Icons.favorite, color: Colors.green),
),
Padding(padding: EdgeInsets.only(right: 8.0)),
FloatingActionButton(
heroTag: "share",
mini: true,
onPressed: memes.length == 0 ? null : share,
backgroundColor: Colors.white,
child: Icon(Icons.share, color: Colors.blue),
),
],
),
);
}
Widget backCard() {
return Align(
alignment: _controller.status == AnimationStatus.forward
? CardsAnimation.backCardAlignmentAnim(_controller).value
: cardsAlign[0],
child: SizedBox.fromSize(
size: _controller.status == AnimationStatus.forward
? CardsAnimation.backCardSizeAnim(_controller).value
: cardsSize[2],
child: cards[2]),
);
}
Widget middleCard() {
return Align(
alignment: _controller.status == AnimationStatus.forward
? CardsAnimation.middleCardAlignmentAnim(_controller).value
: cardsAlign[1],
child: SizedBox.fromSize(
size: _controller.status == AnimationStatus.forward
? CardsAnimation.middleCardSizeAnim(_controller).value
: cardsSize[1],
child: cards[1]),
);
}
Widget frontCard() {
return Align(
alignment: _controller.status == AnimationStatus.forward
? CardsAnimation.frontCardDisappearAlignmentAnim(
_controller, frontCardAlign)
.value
: frontCardAlign,
child: Transform.rotate(
angle: (pi / 180.0) * frontCardRot,
child: SizedBox.fromSize(
size: cardsSize[0],
child: Stack(
children: <Widget>[
cards[0],
Positioned(
left: frontCardAlign.x > 0 ? null : 30.0,
right: frontCardAlign.x > 0 ? 30.0 : null,
top: 20.0,
child: frontCardAlign.x == 0
? Container()
: Material(
borderRadius: BorderRadius.circular(12.0),
color: frontCardAlign.x > 0
? Color.fromRGBO(0, 255, 0, 0.05)
: Color.fromRGBO(255, 0, 0, 0.05),
child: frontCardAlign.x > 0
? Icon(
Icons.favorite,
color: Colors.green,
size: 60.0,
)
: Icon(Icons.close,
color: Colors.red, size: 60.0),
)),
],
)),
));
}
Widget loader() {
return Align(
alignment: Alignment(0, 0),
child: SizedBox.fromSize(child: CircularProgressIndicator()),
);
}
void changeCardsOrder() {
setState(() {
// Swap cards (back card becomes the middle card; middle card becomes the front card, front card becomes a bottom card)
var temp = cards[0];
cards[0] = cards[1];
cards[1] = cards[2];
cards[2] = temp;
frontCardAlign = defaultFrontCardAlign;
frontCardRot = 0.0;
});
}
void animateCards() {
_controller.stop();
_controller.value = 0.0;
_controller.forward();
}
void scoreMem(Reaction reaction) {
int memeId = memes[cardsCounter - 3].id;
setState(() {
loading = true;
});
scoreAndGetMem(memeId, reaction, cardsCounter + 1).then((newMem) {
setState(() {
loading = false;
cards[2] = SwipeCard(newMem[0]);
cardsCounter++;
memes = memes + newMem;
});
});
}
}
class CardsAnimation {
static Animation<Alignment> backCardAlignmentAnim(
AnimationController parent) {
return AlignmentTween(begin: cardsAlign[0], end: cardsAlign[1]).animate(
CurvedAnimation(
parent: parent, curve: Interval(0.4, 0.7, curve: Curves.easeIn)));
}
static Animation<Size> backCardSizeAnim(AnimationController parent) {
return SizeTween(begin: cardsSize[2], end: cardsSize[1]).animate(
CurvedAnimation(
parent: parent, curve: Interval(0.4, 0.7, curve: Curves.easeIn)));
}
static Animation<Alignment> middleCardAlignmentAnim(
AnimationController parent) {
return AlignmentTween(begin: cardsAlign[1], end: cardsAlign[2]).animate(
CurvedAnimation(
parent: parent, curve: Interval(0.2, 0.5, curve: Curves.easeIn)));
}
static Animation<Size> middleCardSizeAnim(AnimationController parent) {
return SizeTween(begin: cardsSize[1], end: cardsSize[0]).animate(
CurvedAnimation(
parent: parent, curve: Interval(0.2, 0.5, curve: Curves.easeIn)));
}
static Animation<Alignment> frontCardDisappearAlignmentAnim(
AnimationController parent, Alignment beginAlign) {
return AlignmentTween(
begin: beginAlign,
end: Alignment(
beginAlign.x > 0 ? beginAlign.x + 30.0 : beginAlign.x - 30.0,
0.0) // Has swiped to the left or right?
)
.animate(CurvedAnimation(
parent: parent, curve: Interval(0.0, 0.5, curve: Curves.easeIn)));
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/widgets/welcomePage.dart | import 'package:flutter/material.dart';
import 'package:memes/pages/loginPage.dart';
import 'package:memes/pages/signupPage.dart';
class WelcomePage extends StatefulWidget {
WelcomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_WelcomePageState createState() => _WelcomePageState();
}
class _WelcomePageState extends State<WelcomePage> {
Widget _submitButton() {
return InkWell(
onTap: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => LoginPage()));
},
child: Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 13),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Color(0xffdf8e33).withAlpha(100),
offset: Offset(2, 4),
blurRadius: 8,
spreadRadius: 2)
],
color: Colors.white),
child: Text(
'Login',
style: TextStyle(fontSize: 20, color: Color(0xfff7892b)),
),
),
);
}
Widget _signUpButton() {
return InkWell(
onTap: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => SignUpPage()));
},
child: Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 13),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
border: Border.all(color: Colors.white, width: 2),
),
child: Text(
'Register now',
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body:SingleChildScrollView(
child:Container(
padding: EdgeInsets.symmetric(horizontal: 20),
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey.shade200,
offset: Offset(2, 4),
blurRadius: 5,
spreadRadius: 2)
],
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xfffbb448), Color(0xffe46b10)])),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 80,
),
_submitButton(),
SizedBox(
height: 20,
),
_signUpButton(),
SizedBox(
height: 20,
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/widgets/settingsPage.dart | import 'package:flutter/material.dart';
import 'package:memes/database/database_hepler.dart';
class SettingsPage extends StatefulWidget {
SettingsPage({Key key, this.title}) : super(key: key);
final String title;
@override
_SettingsPageState createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
String login;
@override
void initState() {
super.initState();
var db = new DatabaseHelper();
db.getUser().then((user) => setState(() {
login = user.login;
}));
}
Widget _userLogin() {
return Container(
child: Text(
'Hello, $login!',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
backgroundColor: Colors.transparent,
),
));
}
Widget _logout() {
return InkWell(
onTap: () async {
var db = new DatabaseHelper();
await db.deleteUsers();
Navigator.pushNamed(context, '/');
},
child: Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 13),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Color(0xffdf8e33).withAlpha(100),
offset: Offset(2, 4),
blurRadius: 8,
spreadRadius: 2)
],
color: Colors.white),
child: Text(
'Logout',
style: TextStyle(fontSize: 20, color: Color(0xfff7892b)),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
height: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey.shade200,
offset: Offset(2, 4),
blurRadius: 5,
spreadRadius: 2)
],
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xfffbb448), Color(0xffe46b10)])),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 80,
),
_userLogin(),
SizedBox(
height: 20,
),
_logout(),
SizedBox(
height: 20,
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/database/database_hepler.dart | import 'dart:async';
import 'dart:io' as io;
import 'package:memes/database/model/settings.dart';
import 'package:memes/database/model/user.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseHelper {
static final DatabaseHelper _instance = new DatabaseHelper.internal();
factory DatabaseHelper() => _instance;
static Database _db;
Future<Database> get db async {
if (_db != null) return _db;
_db = await initDb();
return _db;
}
DatabaseHelper.internal();
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "main.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDb;
}
void _onCreate(Database db, int version) async {
// When creating the db, create the table
await db.execute("CREATE TABLE User(login TEXT PRIMARY KEY, token TEXT)");
}
Future<int> saveUser(User user) async {
var dbClient = await db;
int res = await dbClient.insert("User", user.toMap());
return res;
}
Future<int> saveSettings(Settings settings) async {
var dbClient = await db;
int res = await dbClient.insert("Settings", settings.toMap());
return res;
}
Future<User> getUser() async {
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM User');
if (list.length > 0) {
return new User.fromMap(list[0]);
} else {
return null;
}
}
Future<Settings> getSettings() async {
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM Settings');
if (list.length > 0) {
return new Settings.fromMap(list[0]);
} else {
return null;
}
}
Future<User> getUserByLogin(String login) async {
var dbClient = await db;
List<Map> list =
await dbClient.rawQuery('SELECT * FROM User WHERE login = ?', [login]);
if (list.length > 0) {
return new User.fromMap(list[0]);
} else {
return null;
}
}
Future<Settings> getSettingsValue(String key) async {
var dbClient = await db;
List<Map> list =
await dbClient.rawQuery('SELECT * FROM Settings WHERE key = ?', [key]);
if (list.length > 0) {
return new Settings.fromMap(list[0]);
} else {
return null;
}
}
Future<int> deleteUsers() async {
var dbClient = await db;
int res = await dbClient.delete('User');
return res;
}
Future<bool> updateUser(User user) async {
var dbClient = await db;
int res = await dbClient.update("User", user.toMap(),
where: "login = ?", whereArgs: <String>[user.login]);
return res > 0 ? true : false;
}
Future<bool> updateSettings(Settings settings) async {
var dbClient = await db;
int res = await dbClient.update("Settings", settings.toMap(),
where: "key = ?", whereArgs: <String>[settings.key]);
return res > 0 ? true : false;
}
}
Future<String> getToken() async {
var db = new DatabaseHelper();
var user = await db.getUser();
return user != null ? user.token : null;
}
| 0 |
mirrored_repositories/memes/lib/database | mirrored_repositories/memes/lib/database/model/settings.dart | class Settings {
final String key;
final String value;
Settings({this.key, this.value});
Map<String, dynamic> toMap() {
return {
'key': key,
'value': value,
};
}
factory Settings.fromMap(Map<String, dynamic> json) {
return Settings(
key: json['key'],
value: json['value'],
);
}
}
| 0 |
mirrored_repositories/memes/lib/database | mirrored_repositories/memes/lib/database/model/user.dart | class User {
final String login;
final String token;
User({this.login, this.token});
Map<String, dynamic> toMap() {
return {
'login': login,
'token': token,
};
}
factory User.fromMap(Map<String, dynamic> json) {
return User(
login: json['login'],
token: json['token'],
);
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/pages/profilePage.dart | import 'package:flutter/material.dart';
import 'package:memes/widgets/welcomePage.dart';
import 'package:memes/widgets/settingsPage.dart';
import 'package:memes/database/database_hepler.dart';
class ProfilePage extends StatefulWidget {
@override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
bool isSignIn = false;
@override
void initState() {
super.initState();
getToken().then((token) {
setState(() {
isSignIn = token != null;
});
});
}
Widget _backButton() {
return InkWell(
onTap: () {
Navigator.pop(context);
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Container(
padding: EdgeInsets.only(left: 0, top: 10, bottom: 10),
child: Icon(Icons.keyboard_arrow_left, color: Colors.black),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Material(
child: Text(
'Profile',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
backgroundColor: Colors.transparent,
),
)),
elevation: 0.0,
centerTitle: true,
backgroundColor: Colors.white,
leading: _backButton(),
),
backgroundColor: Colors.white,
body: isSignIn ? SettingsPage() : WelcomePage(),
);
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/pages/loginPage.dart | import 'package:flutter/material.dart';
import 'package:memes/api/users_api.dart';
import 'package:memes/pages/signupPage.dart';
import 'package:memes/components/bezierContainer.dart';
class LoginPage extends StatefulWidget {
LoginPage({Key key, this.title}) : super(key: key);
final String title;
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final loginController = TextEditingController();
final passwordController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is disposed.
loginController.dispose();
passwordController.dispose();
super.dispose();
}
Widget _backButton() {
return InkWell(
onTap: () {
Navigator.pop(context);
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Row(
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 0, top: 10, bottom: 10),
child: Icon(Icons.keyboard_arrow_left, color: Colors.black),
),
Text('Back',
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500))
],
),
),
);
}
Widget _entryField(String title, TextEditingController controller,
{bool isPassword = false}) {
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
title,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
SizedBox(
height: 10,
),
TextField(
controller: controller,
obscureText: isPassword,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xfff3f3f4),
filled: true))
],
),
);
}
Widget _submitButton() {
return InkWell(
onTap: () {
signIn(loginController.text.toString(), passwordController.text.toString()).then((success) {
if (success) {
Navigator.pushNamed(context, '/');
} else {
// todo: show error
}
});
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 15,),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey.shade200,
offset: Offset(2, 4),
blurRadius: 5,
spreadRadius: 2)
],
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Color(0xfffbb448), Color(0xfff7892b)])),
child: Text(
'Login',
style: TextStyle(fontSize: 20, color: Colors.white,),
),
));
}
Widget _createAccountLabel() {
return Container(
margin: EdgeInsets.symmetric(vertical: 20),
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Don\'t have an account ?',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
),
SizedBox(
width: 10,
),
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SignUpPage()));
},
child: Text(
'Register',
style: TextStyle(
color: Color(0xfff79c4f),
fontSize: 13,
fontWeight: FontWeight.w600),
),
)
],
),
);
}
Widget _emailPasswordWidget() {
return Column(
children: <Widget>[
_entryField("Email", loginController),
_entryField("Password", passwordController, isPassword: true),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
child: Stack(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
flex: 3,
child: SizedBox(),
),
SizedBox(
height: 50,
),
_emailPasswordWidget(),
SizedBox(
height: 20,
),
_submitButton(),
Expanded(
flex: 2,
child: SizedBox(),
),
],
),
),
Align(
alignment: Alignment.bottomCenter,
child: _createAccountLabel(),
),
Positioned(top: 40, left: 0, child: _backButton()),
Positioned(
top: -MediaQuery.of(context).size.height * .15,
right: -MediaQuery.of(context).size.width * .4,
child: BezierContainer())
],
),
)));
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/pages/homePage.dart | import 'package:flutter/material.dart';
// import 'package:memes/database/database_hepler.dart';
// import 'package:memes/database/model/settings.dart';
import 'package:memes/widgets/swipeList.dart';
import 'package:memes/widgets/scrollList.dart';
import 'package:url_launcher/url_launcher.dart';
// import 'package:memes/components/face_recognition/face_detection_camera.dart';
import 'package:mixpanel_analytics/mixpanel_analytics.dart';
import 'dart:async';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _user$ = StreamController<String>.broadcast();
MixpanelAnalytics _mixpanel;
bool scrollList = false;
@override
void initState() {
super.initState();
_mixpanel = MixpanelAnalytics(
token: 'e28bf9b75c9895878a9eb63704b1fc92',
userId$: _user$.stream,
verbose: true,
shouldAnonymize: true,
shaFn: (value) => value,
onError: (e) => print(e),
);
}
@override
void dispose() {
_user$.close();
super.dispose();
}
_sendFeedback() async {
const url = 'mailto:[email protected]?subject=Memes%20feedback';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
await _mixpanel.track(event: 'send_feedback', properties: null);
}
_changeFeedView(bool value) async {
setState(() => scrollList = value);
var feed = value ? 'scroll' : 'swipe';
await _mixpanel.track(
event: 'change_feed_view',
properties: {'feed': feed});
// var db = new DatabaseHelper();
// var feedValue = await db.getSettingsValue('feed');
// if (feedValue != null) {
// await db.updateSettings(new Settings.fromMap({'key': 'feed', 'value': feed}));
// } else {
// db.saveSettings(new Settings.fromMap({'key': 'feed', 'value': feed}));
// }
}
_navigateToProfile() async {
Navigator.pushNamed(context, '/profile');
await _mixpanel
.track(event: 'navigate_profile', properties: {'page': 'home'});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
centerTitle: true,
backgroundColor: Colors.white,
leading: IconButton(
onPressed: _navigateToProfile,
icon: Icon(Icons.person, color: Colors.grey)),
title: Switch(
onChanged: _changeFeedView,
value: scrollList,
activeColor: Colors.orange,
),
actions: <Widget>[
IconButton(
onPressed: _sendFeedback,
icon: Icon(Icons.question_answer, color: Colors.grey)),
],
),
backgroundColor: Colors.white,
body: scrollList ? ScrollList() : SwipeList(context),
);
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/pages/signupPage.dart | import 'package:flutter/material.dart';
import 'package:memes/api/users_api.dart';
import 'package:memes/components/bezierContainer.dart';
import 'package:memes/pages/loginPage.dart';
class SignUpPage extends StatefulWidget {
SignUpPage({Key key, this.title}) : super(key: key);
final String title;
@override
_SignUpPageState createState() => _SignUpPageState();
}
class _SignUpPageState extends State<SignUpPage> {
final loginController = TextEditingController();
final passwordController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is disposed.
loginController.dispose();
passwordController.dispose();
super.dispose();
}
Widget _backButton() {
return InkWell(
onTap: () {
Navigator.pop(context);
},
child: Container(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Row(
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 0, top: 10, bottom: 10),
child: Icon(Icons.keyboard_arrow_left, color: Colors.black),
),
Text('Back',
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500))
],
),
),
);
}
Widget _entryField(String title, TextEditingController controller,
{bool isPassword = false}) {
return Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
title,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
SizedBox(
height: 10,
),
TextField(
controller: controller,
obscureText: isPassword,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Color(0xfff3f3f4),
filled: true))
],
),
);
}
Widget _submitButton() {
return InkWell(
onTap: () {
signUp(loginController.text.toString(), passwordController.text.toString()).then((success) {
if (success) {
Navigator.pushNamed(context, '/');
} else {
// todo: show error
}
});
},
child: Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 15),
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey.shade200,
offset: Offset(2, 4),
blurRadius: 5,
spreadRadius: 2)
],
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [Color(0xfffbb448), Color(0xfff7892b)])),
child: Text(
'Register Now',
style: TextStyle(fontSize: 20, color: Colors.white),
),
));
}
Widget _loginAccountLabel() {
return Container(
margin: EdgeInsets.symmetric(vertical: 20),
alignment: Alignment.bottomCenter,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Already have an account ?',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
),
SizedBox(
width: 10,
),
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => LoginPage()));
},
child: Text(
'Login',
style: TextStyle(
color: Color(0xfff79c4f),
fontSize: 13,
fontWeight: FontWeight.w600),
),
)
],
),
);
}
Widget _emailPasswordWidget() {
return Column(
children: <Widget>[
_entryField("Email", loginController),
_entryField("Password", passwordController, isPassword: true),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
child: Stack(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
flex: 3,
child: SizedBox(),
),
SizedBox(
height: 50,
),
_emailPasswordWidget(),
SizedBox(
height: 20,
),
_submitButton(),
Expanded(
flex: 2,
child: SizedBox(),
)
],
),
),
Align(
alignment: Alignment.bottomCenter,
child: _loginAccountLabel(),
),
Positioned(top: 40, left: 0, child: _backButton()),
Positioned(
top: -MediaQuery.of(context).size.height * .15,
right: -MediaQuery.of(context).size.width * .4,
child: BezierContainer())
],
),
)));
}
}
| 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/components/customTextField.dart | import 'package:flutter/material.dart';
class CustomTextField extends StatelessWidget {
CustomTextField(
{this.icon,
this.hint,
this.obsecure = false,
this.validator,
this.onSaved});
final FormFieldSetter<String> onSaved;
final Icon icon;
final String hint;
final bool obsecure;
final FormFieldValidator<String> validator;
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(left: 20, right: 20),
child: TextFormField(
onSaved: onSaved,
validator: validator,
autofocus: true,
obscureText: obsecure,
style: TextStyle(
fontSize: 20,
),
decoration: InputDecoration(
hintStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
hintText: hint,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: BorderSide(
color: Theme.of(context).primaryColor,
width: 2,
),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: BorderSide(
color: Theme.of(context).primaryColor,
width: 3,
),
),
prefixIcon: Padding(
child: IconTheme(
data: IconThemeData(color: Theme.of(context).primaryColor),
child: icon,
),
padding: EdgeInsets.only(left: 30, right: 10),
)),
),
);
}
} | 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/components/customClipper.dart |
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
class ClipPainter extends CustomClipper<Path>{
@override
Path getClip(Size size) {
var height = size.height;
var width = size.width;
var path = new Path();
path.lineTo(0, size.height );
path.lineTo(size.width , height);
path.lineTo(size.width , 0);
/// [Top Left corner]
var secondControlPoint = Offset(0 ,0);
var secondEndPoint = Offset(width * .2 , height *.3);
path.quadraticBezierTo(secondControlPoint.dx, secondControlPoint.dy, secondEndPoint.dx, secondEndPoint.dy);
/// [Left Middle]
var fifthControlPoint = Offset(width * .3 ,height * .5);
var fiftEndPoint = Offset( width * .23, height *.6);
path.quadraticBezierTo(fifthControlPoint.dx, fifthControlPoint.dy, fiftEndPoint.dx, fiftEndPoint.dy);
/// [Bottom Left corner]
var thirdControlPoint = Offset(0 ,height);
var thirdEndPoint = Offset(width , height );
path.quadraticBezierTo(thirdControlPoint.dx, thirdControlPoint.dy, thirdEndPoint.dx, thirdEndPoint.dy);
path.lineTo(0, size.height );
path.close();
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) {
return true;
}
} | 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/components/swipeCard.dart | import 'package:flutter/material.dart';
import 'package:memes/models/meme.dart';
class SwipeCard extends StatelessWidget {
final Meme meme;
SwipeCard(this.meme);
@override
Widget build(BuildContext context) {
return Card(
child: Stack(
children: <Widget>[
SizedBox.expand(
child: Material(
borderRadius: BorderRadius.circular(12.0),
child: Image.network(meme.fileUrl, fit: BoxFit.contain),
),
),
// SizedBox.expand(
// child: Container(
// decoration: BoxDecoration(
// gradient: LinearGradient(
// colors: [Colors.transparent, Colors.black54],
// begin: Alignment.center,
// end: Alignment.bottomCenter)),
// ),
// ),
// Align(
// alignment: Alignment.bottomLeft,
// child: Container(
// padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 16.0),
// child: Column(
// mainAxisAlignment: MainAxisAlignment.end,
// crossAxisAlignment: CrossAxisAlignment.start,
// children: <Widget>[
// Text('Meme number ${meme.id}',
// style: TextStyle(
// color: Colors.white,
// fontSize: 20.0,
// fontWeight: FontWeight.w700)),
// Padding(padding: EdgeInsets.only(bottom: 8.0)),
// Text(meme.name,
// textAlign: TextAlign.start,
// style: TextStyle(color: Colors.white)),
// ],
// )),
// )
],
),
);
}
} | 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/components/bezierContainer.dart | import 'dart:math';
import 'package:flutter/material.dart';
import 'customClipper.dart';
class BezierContainer extends StatelessWidget {
const BezierContainer({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Transform.rotate(
angle: -pi / 3.5,
child: ClipPath(
clipper: ClipPainter(),
child: Container(
height: MediaQuery.of(context).size.height *.5,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0xfffbb448),Color(0xffe46b10)]
)
),
),
),
)
);
}
} | 0 |
mirrored_repositories/memes/lib | mirrored_repositories/memes/lib/components/clipper.dart | import 'package:flutter/material.dart';
class BottomWaveClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
var path = Path();
path.moveTo(size.width, 0.0);
path.lineTo(size.width, size.height);
path.lineTo(0.0, size.height);
path.lineTo(0.0, size.height + 5);
var secondControlPoint = Offset(size.width - (size.width / 6), size.height);
var secondEndPoint = Offset(size.width, 0.0);
path.quadraticBezierTo(secondControlPoint.dx, secondControlPoint.dy,
secondEndPoint.dx, secondEndPoint.dy);
return path;
}
@override
bool shouldReclip(CustomClipper<Path> oldClipper) => false;
} | 0 |
mirrored_repositories/memes/lib/components | mirrored_repositories/memes/lib/components/scrollList/audio_spinner_icon.dart | import 'package:flutter/material.dart';
Widget audioSpinner() {
return Container();
}
LinearGradient get audioDiscGradient => LinearGradient(colors: [
Colors.grey[800],
Colors.grey[900],
Colors.grey[900],
Colors.grey[800]
], stops: [
0.0,
0.4,
0.6,
1.0
], begin: Alignment.bottomLeft, end: Alignment.topRight);
| 0 |
mirrored_repositories/memes/lib/components | mirrored_repositories/memes/lib/components/scrollList/scroll_card.dart | import 'package:flutter/material.dart';
import 'package:memes/models/meme.dart';
class ScrollCard extends StatelessWidget {
final Meme meme;
ScrollCard(this.meme);
@override
Widget build(BuildContext context) {
return Center(
child: Image.network(this.meme.fileUrl),
);
}
}
| 0 |
Subsets and Splits