rename to one trip

This commit is contained in:
Alexander Laevens
2022-11-26 00:25:22 -07:00
parent 839147e0b0
commit 25e1a42392
207 changed files with 8015 additions and 245 deletions

View File

@@ -0,0 +1,86 @@
import 'dart:convert';
import 'consts.dart';
import 'package:http/http.dart' as http;
class TokenSingleton {
static final TokenSingleton _instance = TokenSingleton._internal();
String token = "";
factory TokenSingleton() {
return _instance;
}
void setToken(String tok) {
token = tok;
}
String getToken() {
return token;
}
TokenSingleton._internal();
}
Future<String> getToken(String username, String password) async {
const String requestURL = "$baseURL/auth/token";
final http.Response response = await http.post(Uri.parse(requestURL),
body: {"username": username, "password": password});
if (response.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(response.body);
final TokenSingleton s = TokenSingleton();
s.setToken(json["token"]);
return json["token"];
} else {
return "";
}
}
Future<bool> testToken(String token) async {
const String requestURL = "$baseURL/auth/users/me";
final http.Response response = await http.get(
Uri.parse(requestURL),
headers: {
"Authorization": "Token $token",
},
);
return response.statusCode == 200;
}
Future<String> signup(
String firstName,
String lastName,
String username,
String password,
) async {
const String requestURL = "$baseURL/auth/users/";
final http.Response response = await http.post(
Uri.parse(requestURL),
body: {
"first_name": firstName,
"last_name": lastName,
"username": username,
"password": password,
},
);
if (response.statusCode == 201) {
return "";
}
Map<String, dynamic> errorBody = jsonDecode(response.body);
List<String> errors = [];
errorBody.forEach((key, value) {
errors.add("$key: ${value[0]}");
});
return errors.join(", ");
}

View File

@@ -0,0 +1,3 @@
const String baseURL = "http://192.168.0.16:8000";
const int resultsPerPage = 4;

View File

@@ -0,0 +1,72 @@
import 'dart:convert';
import 'package:one_trip/api/auth.dart';
import 'package:one_trip/api/consts.dart';
import 'package:http/http.dart' as http;
class Homegroup {
int id;
String name;
List<int> recipes;
List<int> users;
List<int> inviteIDs;
Homegroup({
required this.id,
required this.name,
required this.recipes,
required this.users,
required this.inviteIDs,
});
factory Homegroup.fromJson(Map<String, dynamic> json) {
List<int> recipes =
(json["recipes"] as List<dynamic>).map(((e) => e as int)).toList();
List<int> users =
(json["users"] as List<dynamic>).map(((e) => e as int)).toList();
List<int> inviteIDs =
(json["invites"] as List<dynamic>).map(((e) => e as int)).toList();
return Homegroup(
id: json["id"] as int,
name: json["name"] as String,
recipes: recipes,
users: users,
inviteIDs: inviteIDs,
);
}
static Future<Homegroup?> get(int id) async {
String requestURL = "$baseURL/api/homegroups/$id/";
String token = TokenSingleton().getToken();
final http.Response response = await http.get(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
);
if (response.statusCode == 200) {
Homegroup hg = Homegroup.fromJson(jsonDecode(response.body));
return hg;
} else {
return null;
}
}
static Future<Homegroup?> create(String title) async {
String requestURL = "$baseURL/api/homegroups/";
String token = TokenSingleton().getToken();
final http.Response response = await http.post(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
body: {"name": title},
);
if (response.statusCode == 201) {
Homegroup hg = Homegroup.fromJson(jsonDecode(response.body));
return hg;
}
return null;
}
}

View File

@@ -0,0 +1,70 @@
import 'dart:convert';
import 'package:one_trip/api/auth.dart';
import 'package:one_trip/api/consts.dart';
import 'package:http/http.dart' as http;
class HomegroupInvite {
int id;
int homegroupID;
int userID;
HomegroupInvite({
required this.id,
required this.homegroupID,
required this.userID,
});
factory HomegroupInvite.fromJson(Map<String, dynamic> json) {
return HomegroupInvite(
id: json["id"] as int,
homegroupID: json["homegroup"] as int,
userID: json["user"] as int,
);
}
static Future<HomegroupInvite?> get(int id) async {
String requestURL = "$baseURL/api/groupinvites/$id/";
String token = TokenSingleton().getToken();
final http.Response response = await http.get(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
);
if (response.statusCode == 200) {
return HomegroupInvite.fromJson(jsonDecode(response.body));
}
return null;
}
static Future<HomegroupInvite?> create(int homegroupID, int userID) async {
String requestURL = "$baseURL/api/groupinvites/";
String token = TokenSingleton().getToken();
final http.Response response = await http.post(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
body: {"homegroup": "$homegroupID", "user": "$userID"},
);
if (response.statusCode == 201) {
return HomegroupInvite.fromJson(jsonDecode(response.body));
}
return null;
}
Future<bool> delete() async {
String requestURL = "$baseURL/api/groupinvites/$id/";
String token = TokenSingleton().getToken();
final http.Response response = await http.delete(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
);
if (response.statusCode == 204) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,28 @@
import 'package:one_trip/api/auth.dart';
import 'package:one_trip/api/consts.dart';
import 'package:http/http.dart' as http;
class Ingredient {
int id;
String name;
bool inStock;
int contentType;
int objectID;
Ingredient({
required this.id,
required this.name,
required this.inStock,
required this.contentType,
required this.objectID,
});
factory Ingredient.fromJson(Map<String, dynamic> json) {
return Ingredient(
id: json["id"] as int,
name: json["name"] as String,
inStock: json["in_stock"] as bool,
contentType: json["content_type"] as int,
objectID: json["object_id"] as int);
}
}

View File

@@ -0,0 +1,81 @@
import 'dart:convert';
import 'package:one_trip/api/auth.dart';
import 'package:one_trip/api/consts.dart';
import 'package:one_trip/api/models/homegroup.dart';
import 'package:one_trip/api/models/ingredient.dart';
import 'package:http/http.dart' as http;
class Recipe {
int id;
int homegroup;
String name;
List<Ingredient> ingredients;
Recipe(
{required this.id,
required this.name,
required this.ingredients,
required this.homegroup});
factory Recipe.fromJson(Map<String, dynamic> json) {
List<Ingredient> ingredients = [];
for (dynamic ingredient in json["ingredients"]) {
ingredients.add(Ingredient.fromJson(ingredient));
}
return Recipe(
id: json["id"] as int,
homegroup: json["homegroup"] as int,
name: json["name"] as String,
ingredients: ingredients);
}
static Future<Recipe?> get(int id) async {
String requestURL = "$baseURL/api/recipes/$id/";
String token = TokenSingleton().getToken();
final http.Response response = await http.get(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
);
if (response.statusCode == 200) {
return Recipe.fromJson(jsonDecode(response.body));
}
return null;
}
static Future<List<Recipe>> getList(int groupID) async {
Homegroup? group = await Homegroup.get(groupID);
if (group == null) {
return [];
}
List<Recipe> recipes = [];
for (int recipeID in group.recipes) {
Recipe? recipe = await Recipe.get(recipeID);
if (recipe != null) {
recipes.add(recipe);
}
}
return recipes;
}
static Future<Recipe?> create(String name, int group) async {
String requestURL = "$baseURL/api/recipes/";
String token = TokenSingleton().getToken();
final http.Response response = await http.post(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
body: {"homegroup": "$group", "name": name},
);
if (response.statusCode == 201) {
return Recipe.fromJson(jsonDecode(response.body));
}
return null;
}
}

View File

@@ -0,0 +1,89 @@
import 'dart:convert';
import 'package:one_trip/api/auth.dart';
import 'package:one_trip/api/consts.dart';
import 'package:http/http.dart' as http;
class SearchResult {
List<SimpleUser> users;
String? next;
SearchResult({required this.users, required this.next});
}
class SimpleUser {
int id;
String username;
String firstName;
String lastName;
String? imageUrl;
int? invite;
SimpleUser({
required this.id,
required this.username,
required this.firstName,
required this.lastName,
this.imageUrl,
});
factory SimpleUser.fromJson(Map<String, dynamic> json) {
return SimpleUser(
id: json["id"] as int,
username: json["username"] as String,
firstName: json["first_name"] as String,
lastName: json["last_name"] as String,
imageUrl: json["image"] as String?,
);
}
static Future<SimpleUser?> get({int? id}) async {
String requestURL = "$baseURL/auth/users/${id ?? 'me'}";
String token = TokenSingleton().getToken();
final http.Response response = await http.get(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
);
if (response.statusCode == 200) {
SimpleUser u = SimpleUser.fromJson(jsonDecode(response.body));
return u;
} else {
return null;
}
}
static Future<SearchResult> search(String query, int page) async {
// String requestURL = "";
// if (url != null) {
// requestURL = url;
// } else if (query != null) {
// requestURL = "$baseURL/auth/users/?search=$query";
// } else {
// return SearchResult(users: [], next: null);
// }
String requestURL = "$baseURL/auth/users/?page=$page&search=$query";
requestURL = requestURL.replaceAll(RegExp(r"\s+"), "+");
String token = TokenSingleton().getToken();
final http.Response response = await http.get(
Uri.parse(requestURL),
headers: {"Authorization": "Token $token"},
);
if (response.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(response.body);
List<SimpleUser> users = [];
for (var userObject in json["results"]) {
SimpleUser u = SimpleUser.fromJson(userObject);
users.add(u);
}
return SearchResult(users: users, next: json["next"] as String?);
}
return SearchResult(users: [], next: null);
}
}

View File

@@ -0,0 +1,115 @@
import 'dart:convert';
import 'package:one_trip/api/auth.dart';
import 'package:one_trip/api/consts.dart';
import 'package:http/http.dart' as http;
import 'dart:io' show File;
class User {
int id;
String username;
String firstName;
String lastName;
List<int> homegroupInvites;
int? homegroup;
String? imageUrl;
User({
required this.id,
required this.username,
required this.firstName,
required this.lastName,
required this.homegroupInvites,
this.homegroup,
this.imageUrl,
});
factory User.fromJson(Map<String, dynamic> json) {
List<dynamic> invitesDynamic = json["homegroup_invites"];
List<int> invites = invitesDynamic.map((e) => e as int).toList();
return User(
id: json["id"] as int,
username: json["username"] as String,
firstName: json["first_name"] as String,
lastName: json["last_name"] as String,
homegroup: json["homegroup"] as int?,
imageUrl: json["image"] as String?,
homegroupInvites: invites,
);
}
static Future<User?> getMe() async {
String requestURL = "$baseURL/auth/users/me";
String token = TokenSingleton().getToken();
final http.Response response =
await http.get(Uri.parse(requestURL), headers: {
"Authorization": "Token $token",
});
if (response.statusCode == 200) {
User u = User.fromJson(jsonDecode(response.body));
return u;
} else {
return null;
}
}
Future<User?> patchMe({
String? firstName,
String? lastName,
int? homegroup,
}) async {
String requestURL = "$baseURL/auth/users/me";
Map<String, String> body = {};
if (firstName != null) {
body["first_name"] = firstName;
}
if (lastName != null) {
body["last_name"] = lastName;
}
if (homegroup != null) {
body["homegroup"] = "$homegroup";
}
String token = TokenSingleton().getToken();
final http.Response response = await http.patch(
Uri.parse(requestURL),
headers: {
"Authorization": "Token $token",
},
body: body,
);
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
}
return null;
}
Future<User?> uploadImage(File file) async {
String requestURL = "$baseURL/auth/users/me";
String token = TokenSingleton().getToken();
http.MultipartRequest request =
http.MultipartRequest("PATCH", Uri.parse(requestURL));
request.headers.addAll({"Authorization": "Token $token"});
request.files.add(http.MultipartFile.fromBytes(
"image", file.readAsBytesSync(),
filename: file.path));
var multiresponse = await request.send();
http.Response response = await http.Response.fromStream(multiresponse);
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
}
return null;
}
}

30
one_trip/lib/main.dart Normal file
View File

@@ -0,0 +1,30 @@
import 'package:flutter/material.dart';
import 'package:one_trip/screens/home_screen.dart';
import 'package:one_trip/screens/login_screen.dart';
import 'package:one_trip/theme.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Grocery Helper',
theme: lightTheme,
darkTheme: darkTheme,
themeMode: ThemeMode.system,
debugShowCheckedModeBanner: false,
initialRoute: "/login",
routes: {
"/login": (context) => const LoginScreen(),
"/home": (context) => ScrollConfiguration(
behavior: MyBehavior(), child: const HomeScreen())
},
);
}
}

View File

@@ -0,0 +1,164 @@
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:one_trip/api/models/homegroup.dart';
import 'package:one_trip/widgets/text_entry_dialog.dart';
import 'package:one_trip/pages/profile_page/widgets/homegroup_card_widget.dart';
import 'package:one_trip/pages/profile_page/widgets/profile_card_widget.dart';
import 'package:one_trip/api/models/user.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io' show Platform, File;
class ProfilePage extends StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
late User _userInfo;
late Future<bool> _isLoaded;
Future<bool> _loadProfile() async {
User? userInfo = await User.getMe();
if (userInfo != null) {
_userInfo = userInfo;
return true;
}
return false;
}
void showError(String text) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Theme.of(context).colorScheme.error,
content: Text(text),
action: SnackBarAction(
textColor: Theme.of(context).colorScheme.onError,
label: "Dismiss",
onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(),
),
),
);
}
@override
void initState() {
super.initState();
_isLoaded = _loadProfile();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _isLoaded,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return Scrollbar(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ProfileCard(
userInfo: _userInfo,
onTapPhoto: () async {
if (Platform.isAndroid) {
final ImagePicker picker = ImagePicker();
final XFile? photo = await picker.pickImage(
source: ImageSource.camera,
imageQuality: 70,
maxWidth: 400,
maxHeight: 400);
if (photo == null) {
return;
}
File file = File(photo.path);
User? response = await _userInfo.uploadImage(file);
if (response != null) {
setState(() {
_userInfo = response;
});
}
} else {
showError(
"This feature is only available on Android");
}
},
onLogout: () async {
const storage = FlutterSecureStorage();
await storage.delete(key: "token");
if (mounted) {
Navigator.pushReplacementNamed(context, "/login");
}
},
),
const SizedBox(height: 12),
_userInfo.homegroup == null
? CreateJoinHomegroup(
invites: _userInfo.homegroupInvites,
onJoin: (id) async {
User? response =
await _userInfo.patchMe(homegroup: id);
if (response != null) {
setState(() {
_userInfo = response;
});
}
},
onCreate: () async {
String? name = await textEntryDialog(
context,
"Create Homegroup",
"Homegroup Name",
defaultValue: "${_userInfo.username}'s Kitchen",
);
if (name == null) {
return;
}
if (name == "") {
showError("Homegroup name must not be empty");
return;
}
Homegroup? hg = await Homegroup.create(name);
if (hg == null) {
return;
}
User? response =
await _userInfo.patchMe(homegroup: hg.id);
if (response != null) {
setState(() {
_userInfo = response;
});
}
},
)
: EditHomegroup(
homegroupID: _userInfo.homegroup!,
)
],
),
),
),
);
} else {
return const CircularProgressIndicator();
}
},
);
}
}

View File

@@ -0,0 +1,360 @@
import 'package:flutter/material.dart';
import 'package:one_trip/api/models/homegroup.dart';
import 'package:one_trip/api/models/homegroupinvite.dart';
import 'package:one_trip/api/models/simpleuser.dart';
import 'package:one_trip/pages/profile_page/widgets/invite_homegroup_dialog.dart';
import 'package:one_trip/pages/profile_page/widgets/user_chip.dart';
import 'package:one_trip/theme.dart';
class CreateJoinHomegroup extends StatefulWidget {
final List<int> invites;
final Function(int id) onJoin;
final Function() onCreate;
const CreateJoinHomegroup({
super.key,
required this.invites,
required this.onJoin,
required this.onCreate,
});
@override
State<CreateJoinHomegroup> createState() => _CreateJoinHomegroupState();
}
class _CreateJoinHomegroupState extends State<CreateJoinHomegroup> {
late Future<bool> _isLoaded;
final List<Homegroup> _invitedGroups = [];
Future<bool> _loadInvites() async {
for (int id in widget.invites) {
Homegroup? hg = await Homegroup.get(id);
if (hg != null) {
_invitedGroups.add(hg);
}
}
return true;
}
@override
void initState() {
super.initState();
_isLoaded = _loadInvites();
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
elevation: 10,
margin: EdgeInsets.zero,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(10), bottom: Radius.zero),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Create or Join a Homegroup",
style: Theme.of(context).textTheme.titleMedium,
),
const Divider(),
widget.invites.isEmpty
? const Text(
"You have not been invited to join any homegroups")
: Center(
child: FutureBuilder(
future: _isLoaded,
builder: ((context, snapshot) {
if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else if (snapshot.hasData &&
snapshot.connectionState ==
ConnectionState.done) {
return ListView.separated(
shrinkWrap: true,
itemBuilder: (context, index) {
return JoinRow(
hg: _invitedGroups[index],
onJoin: (id) => widget.onJoin(id),
);
},
separatorBuilder: (context, index) =>
const Divider(),
itemCount: _invitedGroups.length);
} else {
return const CircularProgressIndicator();
}
}),
),
),
],
),
),
),
ElevatedButton(
style: bottomButtonStyle,
onPressed: () => widget.onCreate(),
child: const Text("Create Homegroup"),
)
],
);
}
}
class JoinRow extends StatelessWidget {
final Homegroup hg;
final Function(int id) onJoin;
const JoinRow({super.key, required this.hg, required this.onJoin});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(hg.name),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(
Theme.of(context).colorScheme.secondary),
foregroundColor: MaterialStatePropertyAll(
Theme.of(context).colorScheme.onSecondary)),
onPressed: () => onJoin(hg.id),
child: Row(
children: const [
Text("Join"),
SizedBox(width: 4),
Icon(Icons.check)
],
),
)
],
);
}
}
class EditHomegroup extends StatefulWidget {
final int homegroupID;
const EditHomegroup({super.key, required this.homegroupID});
@override
State<EditHomegroup> createState() => _EditHomegroupState();
}
class _EditHomegroupState extends State<EditHomegroup> {
late Future<bool> _isLoaded;
Homegroup? _homegroup;
List<SimpleUser> _groupUsers = [];
List<HomegroupInvite> _groupInvites = [];
Map<HomegroupInvite, SimpleUser> _groupInviteUsers = {};
Future<bool> _loadHomegroup() async {
Homegroup? hg = await Homegroup.get(widget.homegroupID);
if (hg == null) {
return false;
}
_homegroup = hg;
_groupUsers = [];
_groupInvites = [];
_groupInviteUsers = {};
for (int id in hg.users) {
SimpleUser? u = await SimpleUser.get(id: id);
if (u != null) {
_groupUsers.add(u);
}
}
for (int id in hg.inviteIDs) {
HomegroupInvite? invite = await HomegroupInvite.get(id);
if (invite == null || hg.users.contains(invite.userID)) {
continue;
}
SimpleUser? u = await SimpleUser.get(id: invite.userID);
if (u != null) {
_groupInvites.add(invite);
_groupInviteUsers[invite] = u;
}
}
return true;
}
@override
void initState() {
super.initState();
_isLoaded = _loadHomegroup();
}
@override
Widget build(BuildContext context) {
final TextStyle textstylebase = Theme.of(context).textTheme.titleSmall!;
final TextStyle textstyle = TextStyle(
fontSize: textstylebase.fontSize,
fontWeight: textstylebase.fontWeight,
color: textstylebase.color,
decorationColor: textstylebase.color,
decorationStyle: TextDecorationStyle.solid,
decoration: TextDecoration.underline);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
elevation: 10,
margin: EdgeInsets.zero,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(10), bottom: Radius.zero),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: FutureBuilder(
future: _isLoaded,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text(snapshot.error.toString()));
} else if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_homegroup!.name,
style: Theme.of(context).textTheme.titleLarge,
),
const Divider(),
Text(
"Users",
style: textstyle,
),
const SizedBox(height: 8),
ListView.separated(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: _groupUsers.length,
separatorBuilder: (context, index) => const Divider(),
itemBuilder: (context, index) {
return UserRow(
user: _groupUsers[index],
onButton: (id) {},
buttonText: "Kick",
);
},
),
const Divider(),
Text(
"Pending Invites",
style: textstyle,
),
const SizedBox(height: 8),
_groupInvites.isEmpty
? const Text("None")
: ListView.separated(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, index) {
return UserRow(
user:
_groupInviteUsers[_groupInvites[index]]!,
onButton: (id) async {
bool success =
await _groupInvites[index].delete();
if (success) {
setState(() {
_isLoaded = _loadHomegroup();
});
}
},
buttonText: "Cancel",
);
},
separatorBuilder: (context, index) =>
const Divider(),
itemCount: _groupInvites.length)
],
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
),
),
),
ElevatedButton(
style: bottomButtonStyle,
onPressed: () async {
List<int>? selectedIDs = await inviteHomegroupDialog(context);
if (selectedIDs == null) {
return;
}
for (int id in selectedIDs) {
await HomegroupInvite.create(_homegroup!.id, id);
}
setState(() {
_isLoaded = _loadHomegroup();
});
},
child: const Text("Invite"),
)
],
);
}
}
class UserRow extends StatelessWidget {
final SimpleUser user;
final Function(int id) onButton;
final String buttonText;
const UserRow(
{super.key,
required this.user,
required this.onButton,
required this.buttonText});
@override
Widget build(BuildContext context) {
final ButtonStyle buttonStyle = ButtonStyle(
padding: const MaterialStatePropertyAll(
EdgeInsets.symmetric(vertical: 8, horizontal: 4)),
backgroundColor:
MaterialStatePropertyAll(Theme.of(context).colorScheme.secondary),
foregroundColor: MaterialStatePropertyAll(
Theme.of(context).colorScheme.onSecondary));
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SmallUserChip(user: user),
ElevatedButton(
style: buttonStyle,
onPressed: () => onButton(user.id),
child: Row(
children: [
Text(buttonText),
const SizedBox(width: 4),
const Icon(Icons.close)
],
),
)
],
);
}
}

View File

@@ -0,0 +1,163 @@
import 'package:flutter/material.dart';
import 'package:one_trip/api/models/simpleuser.dart';
import 'package:one_trip/pages/profile_page/widgets/user_chip.dart';
import 'package:one_trip/theme.dart';
import 'package:one_trip/widgets/pagination_listview.dart';
class InviteHomegroupDialog extends StatefulWidget {
const InviteHomegroupDialog({super.key});
@override
State<InviteHomegroupDialog> createState() => _InviteHomegroupDialogState();
}
class _InviteHomegroupDialogState extends State<InviteHomegroupDialog> {
final TextEditingController _searchController = TextEditingController();
ListViewState _listState = ListViewState.inactive;
List<int> selectedIDs = [];
@override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.zero,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Invite to Homegroup",
style: Theme.of(context).textTheme.titleMedium,
),
const Divider(),
TextFormField(
controller: _searchController,
textInputAction: TextInputAction.search,
onFieldSubmitted: (value) {
setState(() {
_listState = ListViewState.changed;
});
},
onChanged: (value) {
setState(() {
_listState = ListViewState.inactive;
});
},
decoration: InputDecoration(
label: const Text("Search"),
isDense: true,
suffix: IconButton(
onPressed: () {
setState(() {
_listState = ListViewState.changed;
});
// https://flutterigniter.com/dismiss-keyboard-form-lose-focus/
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
icon: const Icon(Icons.search),
),
),
),
const SizedBox(height: 8),
LayoutBuilder(
builder: (builder, constraints) {
return ConstrainedBox(
constraints: BoxConstraints.expand(
width: constraints.maxWidth - 8,
height: 160,
),
child: PaginationListView(
state: _listState,
shrinkWrap: true,
itemBuilder: (context, data) {
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
setState(() {
// _ready = false;
_listState = ListViewState.inUse;
if (selectedIDs.contains(data.id)) {
selectedIDs.remove(data.id);
} else {
selectedIDs.add(data.id);
}
});
},
child: Container(
padding: const EdgeInsets.all(4),
color: selectedIDs.contains(data.id)
? Theme.of(context).colorScheme.secondary
: null,
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
SmallUserChip(
user: data,
radius: 20,
textColor: selectedIDs.contains(data.id)
? Theme.of(context).colorScheme.onSecondary
: null,
),
],
),
),
);
},
seperatorBuilder: (context, data) {
return const Divider();
},
dataProvider: (int page) async {
SearchResult result =
await SimpleUser.search(_searchController.text, page);
List<dynamic> users = List<dynamic>.from(result.users);
if (result.next == null) {
users.add(null);
}
return users;
},
),
);
},
),
Padding(
padding: const EdgeInsets.only(top: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () => Navigator.pop(context),
child: const Text("Cancel"),
),
ElevatedButton(
onPressed: () => Navigator.pop(context, selectedIDs),
child: const Text("Done")),
],
),
)
],
),
),
);
}
}
Future<List<int>?> inviteHomegroupDialog(BuildContext context) async {
List<int>? selectedIDs = await showDialog(
context: context,
builder: (context) {
return Dialog(
child: ScrollConfiguration(
behavior: MyBehavior(), child: const InviteHomegroupDialog()),
);
},
);
return selectedIDs;
}

View File

@@ -0,0 +1,86 @@
import 'package:flutter/material.dart';
import 'package:one_trip/api/models/user.dart';
import 'package:flutter_svg_provider/flutter_svg_provider.dart';
import 'package:one_trip/theme.dart';
class ProfileCard extends StatelessWidget {
final User userInfo;
final Function() onTapPhoto;
final Function() onLogout;
const ProfileCard(
{super.key,
required this.userInfo,
required this.onTapPhoto,
required this.onLogout});
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
elevation: 10,
margin: EdgeInsets.zero,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(10), bottom: Radius.zero),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisSize: MainAxisSize.max,
children: [
CircleAvatar(
backgroundColor: Theme.of(context).colorScheme.primary,
radius: 42,
child: CircleAvatar(
radius: 40,
backgroundImage: userInfo.imageUrl != null
? NetworkImage(userInfo.imageUrl!)
: Image(
image: Svg('assets/images/person.svg',
color: Theme.of(context)
.colorScheme
.onPrimaryContainer),
).image,
backgroundColor:
Theme.of(context).colorScheme.primaryContainer,
// https://github.com/flutter/flutter/issues/42901#issuecomment-708050484
child: Material(
shape: const CircleBorder(),
clipBehavior: Clip.hardEdge,
color: Colors.transparent,
child: InkWell(
onTap: () => onTapPhoto(),
),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${userInfo.firstName} ${userInfo.lastName}",
style: Theme.of(context).textTheme.titleMedium,
),
Text("@${userInfo.username}",
style: Theme.of(context).textTheme.titleLarge),
],
),
)
],
),
),
),
ElevatedButton(
style: bottomButtonStyle,
onPressed: () => onLogout(),
child: const Text("Log out"),
)
],
);
}
}

View File

@@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg_provider/flutter_svg_provider.dart';
import 'package:one_trip/api/models/simpleuser.dart';
class SmallUserChip extends StatelessWidget {
final SimpleUser user;
final double? radius;
final Color? textColor;
const SmallUserChip(
{super.key, required this.user, this.radius, this.textColor});
@override
Widget build(BuildContext context) {
double baseRadius = radius ?? 30;
return Row(
children: [
CircleAvatar(
radius: baseRadius,
backgroundColor: Theme.of(context).colorScheme.primary,
child: CircleAvatar(
radius: baseRadius - 2,
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
backgroundImage: user.imageUrl != null
? NetworkImage(user.imageUrl!)
: Image(
image: Svg('assets/images/person.svg',
color:
Theme.of(context).colorScheme.onPrimaryContainer),
).image,
),
),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"${user.firstName} ${user.lastName}",
style: TextStyle(
color: textColor ?? Theme.of(context).colorScheme.onSurface),
),
Text(
"@${user.username}",
style: TextStyle(
color: textColor ?? Theme.of(context).colorScheme.onSurface),
),
],
)
],
);
}
}

View File

@@ -0,0 +1,132 @@
import 'package:flutter/material.dart';
import 'package:one_trip/api/models/homegroup.dart';
import 'package:one_trip/api/models/recipe.dart';
import 'package:one_trip/api/models/user.dart';
import 'package:one_trip/pages/recipes_page/widgets/recipe_card_widget.dart';
import 'package:one_trip/widgets/text_entry_dialog.dart';
class RecipesPage extends StatefulWidget {
const RecipesPage({super.key});
@override
State<RecipesPage> createState() => _RecipesPageState();
}
class _RecipesPageState extends State<RecipesPage> {
late Future<List<Recipe>> _recipes;
late User _userInfo;
Future<List<Recipe>> _fetchList() async {
User? userInfo = await User.getMe();
if (userInfo == null || userInfo.homegroup == null) {
return [];
}
_userInfo = userInfo;
List<Recipe> recipes = await Recipe.getList(_userInfo.homegroup!);
return recipes;
}
@override
void initState() {
super.initState();
_recipes = _fetchList();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _recipes,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return RecipeList(
recipes: snapshot.data!, homegroup: _userInfo.homegroup!);
} else {
return const Center(child: CircularProgressIndicator());
}
},
);
}
}
class RecipeList extends StatefulWidget {
final List<Recipe> recipes;
final int homegroup;
const RecipeList({super.key, required this.recipes, required this.homegroup});
@override
State<RecipeList> createState() => _RecipeListState();
}
class _RecipeListState extends State<RecipeList> {
int? _expandedCard;
void showError(String text) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Theme.of(context).colorScheme.error,
content: Text(text),
action: SnackBarAction(
textColor: Theme.of(context).colorScheme.onError,
label: "Dismiss",
onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(),
),
),
);
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
ListView.separated(
padding: const EdgeInsets.all(8),
itemCount: widget.recipes.length,
separatorBuilder: (context, index) => const SizedBox(height: 12),
itemBuilder: (context, index) => RecipeCard(
recipe: widget.recipes[index],
isExpanded: _expandedCard == index,
onTap: () {
setState(() {
if (_expandedCard == index) {
_expandedCard = null;
} else {
_expandedCard = index;
}
});
},
),
),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: FloatingActionButton.extended(
onPressed: () async {
String? name =
await textEntryDialog(context, "Recipe Name", "Recipe");
if (name == null) {
return;
}
if (name == "") {
showError("Recipe name cannot be empty");
return;
}
Recipe? created = await Recipe.create(name, widget.homegroup);
},
label: Row(
children: const [Icon(Icons.note_add), Text("New Recipe")],
),
),
),
)
],
);
}
}

View File

@@ -0,0 +1,133 @@
import 'package:flutter/material.dart';
import 'package:one_trip/api/models/ingredient.dart';
import 'package:one_trip/api/models/recipe.dart';
import 'package:one_trip/theme.dart';
import 'package:one_trip/widgets/text_entry_dialog.dart';
class RecipeCard extends StatelessWidget {
final Recipe recipe;
final bool isExpanded;
final Function() onTap;
const RecipeCard({
super.key,
required this.recipe,
required this.isExpanded,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: const Radius.circular(10),
bottom: isExpanded ? Radius.zero : const Radius.circular(10)),
),
margin: EdgeInsets.zero,
child: GestureDetector(
onTap: onTap,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.all(8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
recipe.name,
style: Theme.of(context).textTheme.headlineSmall,
),
),
AnimatedRotation(
duration: const Duration(milliseconds: 200),
turns: isExpanded ? 0.5 : 0,
child: const Icon(Icons.expand_more, size: 30),
),
],
),
),
AnimatedSize(
duration: const Duration(milliseconds: 200),
child: isExpanded
? IngredientSection(ingredients: recipe.ingredients)
: const SizedBox(),
),
],
),
),
),
AnimatedSize(
duration: const Duration(milliseconds: 200),
child: isExpanded
? ElevatedButton(
style: bottomButtonStyle,
onPressed: () async {
String? name = await textEntryDialog(
context, "Ingredient Name", "Ingredient");
},
child: const Text("Add Ingredient"),
)
: const SizedBox(),
)
],
);
}
}
class IngredientSection extends StatelessWidget {
final List<Ingredient> ingredients;
const IngredientSection({super.key, required this.ingredients});
@override
Widget build(BuildContext context) {
final TextStyle ingredientStyle = Theme.of(context)
.textTheme
.bodyLarge!
.copyWith(color: Theme.of(context).colorScheme.onSurface);
return Container(
color: Theme.of(context).colorScheme.surface,
child: ListView.separated(
padding: const EdgeInsets.all(8),
itemCount: (ingredients.length / 2).ceil(),
shrinkWrap: true,
separatorBuilder: (context, index) => Divider(
color: index % 2 == 0
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.error,
),
itemBuilder: (context, index) {
if (ingredients.length % 2 == 0 ||
index * 2 <= ingredients.length - 2) {
return Row(
children: [
Expanded(
child: Text(
ingredients[index * 2].name,
style: ingredientStyle,
),
),
Expanded(
child: Text(ingredients[index * 2 + 1].name,
style: ingredientStyle),
)
],
);
} else {
return Row(
children: [
Text(ingredients[index * 2].name, style: ingredientStyle),
],
);
}
},
),
);
}
}

View File

@@ -0,0 +1,125 @@
import 'package:flutter/material.dart';
class ColorPage extends StatelessWidget {
const ColorPage({super.key});
@override
Widget build(BuildContext context) {
return GridView.count(
crossAxisCount: 3,
children: [
// FIRST ROW
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.primary,
child: Center(
child: Text(
"Primary",
style: TextStyle(color: Theme.of(context).colorScheme.onPrimary),
)),
),
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.secondary,
child: Center(
child: Text(
"Secondary",
style: TextStyle(color: Theme.of(context).colorScheme.onSecondary),
)),
),
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.tertiary,
child: Center(
child: Text(
"Tertiary",
style: TextStyle(color: Theme.of(context).colorScheme.onTertiary),
)),
),
// SECOND ROW
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.primaryContainer,
child: Center(
child: Text(
"Primary Container",
style: TextStyle(
color: Theme.of(context).colorScheme.onPrimaryContainer),
)),
),
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.secondaryContainer,
child: Center(
child: Text(
"Secondary Container",
style: TextStyle(
color: Theme.of(context).colorScheme.onSecondaryContainer),
)),
),
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.tertiaryContainer,
child: Center(
child: Text(
"Tertiary Container",
style: TextStyle(
color: Theme.of(context).colorScheme.onTertiaryContainer),
)),
),
// THIRD ROW
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.error,
child: Center(
child: Text(
"Error",
style: TextStyle(color: Theme.of(context).colorScheme.onError),
)),
),
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.background,
child: Center(
child: Text(
"Background",
style: TextStyle(color: Theme.of(context).colorScheme.onBackground),
)),
),
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.surface,
child: Center(
child: Text(
"Surface",
style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
)),
),
// FOURTH ROW
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.errorContainer,
child: Center(
child: Text(
"Error Container",
style: TextStyle(
color: Theme.of(context).colorScheme.onErrorContainer),
)),
),
Container(
padding: const EdgeInsets.all(8),
color: Theme.of(context).colorScheme.surfaceVariant,
child: Center(
child: Text(
"Surface Variant",
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant),
)),
),
],
);
}
}

View File

@@ -0,0 +1,75 @@
import 'package:flutter/material.dart';
import 'package:one_trip/pages/profile_page/profile_page.dart';
import 'package:one_trip/pages/recipes_page/recipes_page.dart';
import 'package:one_trip/pages/themetest.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _selectedPage = 0;
late List<Widget> _pages;
final List<String> _pageNames = [
"Shopping List",
"Saved Recipes",
"Your Profile",
"Color Debug"
];
@override
void initState() {
_pages = <Widget>[
Container(),
const RecipesPage(),
const ProfilePage(),
const ColorPage()
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(child: _pages[_selectedPage]),
appBar: AppBar(title: Text(_pageNames[_selectedPage])),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.shifting,
selectedItemColor: Theme.of(context).colorScheme.primary,
unselectedItemColor: Theme.of(context).colorScheme.secondary,
landscapeLayout: BottomNavigationBarLandscapeLayout.centered,
items: [
BottomNavigationBarItem(
icon: const Icon(Icons.list_alt),
label: "List",
backgroundColor: Theme.of(context).colorScheme.secondaryContainer,
),
BottomNavigationBarItem(
icon: const Icon(Icons.menu_book),
label: "Recipes",
backgroundColor: Theme.of(context).colorScheme.secondaryContainer,
),
BottomNavigationBarItem(
icon: const Icon(Icons.person),
label: "Profile",
backgroundColor: Theme.of(context).colorScheme.secondaryContainer,
),
BottomNavigationBarItem(
icon: const Icon(Icons.grid_3x3),
label: "Colors",
backgroundColor: Theme.of(context).colorScheme.secondaryContainer,
)
],
currentIndex: _selectedPage,
onTap: (value) {
setState(() {
_selectedPage = value;
});
},
),
);
}
}

View File

@@ -0,0 +1,348 @@
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:one_trip/api/auth.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final List<bool> _isSelected = [true, false];
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportContraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints:
BoxConstraints(minHeight: viewportContraints.maxHeight),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.min,
children: [
SizedBox.square(
dimension: 150,
child: SvgPicture.asset(
"assets/images/desktop.svg",
fit: BoxFit.contain,
),
),
FractionallySizedBox(
widthFactor: 0.9,
child: Card(
elevation: 10,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
children: [
LayoutBuilder(builder: (builder, constraints) {
return ToggleButtons(
isSelected: _isSelected,
constraints: BoxConstraints.expand(
width: constraints.maxWidth / 2 - 8,
height: 30),
selectedBorderColor:
Theme.of(context).colorScheme.primary,
onPressed: (index) {
setState(() {
for (int i = 0;
i < _isSelected.length;
i++) {
_isSelected[i] = (i == index);
}
});
},
children: const [
Text("Log In"),
Text("Sign Up")
],
);
}),
_isSelected[0]
? const LoginForm()
: const SignupForm()
],
),
),
),
),
],
),
),
);
},
),
);
}
}
class LoginForm extends StatefulWidget {
const LoginForm({super.key});
@override
State<LoginForm> createState() => _LoginFormState();
}
class _LoginFormState extends State<LoginForm> {
bool _stayLoggedIn = false;
bool _tryingLogin = false;
final _usernameController = TextEditingController(text: "");
final _passwordController = TextEditingController(text: "");
void tryLogIn(bool save) async {
setState(() {
_tryingLogin = true;
});
String tok =
await getToken(_usernameController.text, _passwordController.text);
if (tok == "") {
showError("That Username / Password combination does not exist.");
setState(() {
_tryingLogin = false;
});
return;
}
if (save) {
const storage = FlutterSecureStorage();
storage.write(key: "token", value: tok);
}
if (mounted) {
await Navigator.pushReplacementNamed(context, "/home");
}
}
void trySavedToken() async {
setState(() {
_tryingLogin = true;
});
// get token from storage
const storage = FlutterSecureStorage();
final String? token = await storage.read(key: "token");
if (token == null) {
setState(() {
_tryingLogin = false;
});
return;
}
// check the stored token still works
final bool stillValid = await testToken(token);
if (!stillValid) {
storage.delete(key: "token");
setState(() {
_tryingLogin = false;
});
return;
}
// store the token in a singleton to avoid repeated storage accesses
final TokenSingleton s = TokenSingleton();
s.setToken(token);
if (mounted) {
await Navigator.pushReplacementNamed(context, "/home");
}
}
void showError(String text) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Theme.of(context).colorScheme.error,
content: Text(text),
action: SnackBarAction(
textColor: Theme.of(context).colorScheme.onError,
label: "Dismiss",
onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(),
),
),
);
}
@override
void initState() {
super.initState();
trySavedToken();
}
@override
Widget build(BuildContext context) {
return Form(
child: Column(
children: [
TextFormField(
controller: _usernameController,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(hintText: "Username"),
),
TextFormField(
controller: _passwordController,
textInputAction: TextInputAction.done,
obscureText: true,
decoration: const InputDecoration(hintText: "Password"),
onFieldSubmitted: (value) => tryLogIn(_stayLoggedIn),
),
Row(
children: [
const Text("Stay Logged In:"),
Checkbox(
value: _stayLoggedIn,
onChanged: (value) {
setState(() {
_stayLoggedIn = value!;
});
},
)
],
),
ElevatedButton(
onPressed: !_tryingLogin ? () => tryLogIn(_stayLoggedIn) : null,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: _tryingLogin
? [
const Text("Log In"),
const Padding(
padding: EdgeInsets.only(left: 12),
child: Center(
child: SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(),
),
),
)
]
: const [
Text("Log In"),
],
),
)
],
),
);
}
}
class SignupForm extends StatefulWidget {
const SignupForm({super.key});
@override
State<SignupForm> createState() => _SignupFormState();
}
class _SignupFormState extends State<SignupForm> {
final _usernameController = TextEditingController(text: "");
final _passwordController = TextEditingController(text: "");
final _firstnameController = TextEditingController(text: "");
final _lastnameController = TextEditingController(text: "");
void showError(String text) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Theme.of(context).colorScheme.error,
content: Text(text),
action: SnackBarAction(
textColor: Theme.of(context).colorScheme.onError,
label: "Dismiss",
onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(),
),
),
);
}
void trySignUpLogin() async {
String firstName = _firstnameController.text;
String lastName = _lastnameController.text;
String userName = _usernameController.text;
String password = _passwordController.text;
if (firstName == "" || lastName == "" || userName == "" || password == "") {
showError("All fields must be populated");
return;
}
String errors = await signup(firstName, lastName, userName, password);
if (errors != "") {
showError(errors);
return;
}
String tok = await getToken(userName, password);
if (tok == "") {
showError("That Username / Password combination does not exist.");
return;
}
if (mounted) {
await Navigator.pushReplacementNamed(context, "/home");
}
}
@override
Widget build(BuildContext context) {
return Form(
child: Column(
children: [
Row(
children: [
Flexible(
child: TextFormField(
controller: _firstnameController,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(hintText: "First Name"),
),
),
const SizedBox(width: 8),
Flexible(
child: TextFormField(
controller: _lastnameController,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(hintText: "Last Name"),
),
)
],
),
TextFormField(
controller: _usernameController,
textInputAction: TextInputAction.next,
decoration: const InputDecoration(hintText: "Username"),
),
TextFormField(
controller: _passwordController,
textInputAction: TextInputAction.done,
obscureText: true,
decoration: const InputDecoration(hintText: "Password"),
onFieldSubmitted: (value) async => trySignUpLogin(),
),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () async {
trySignUpLogin();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: const [Text("Sign up & Log in")],
),
)
],
),
);
}
}

43
one_trip/lib/theme.dart Normal file
View File

@@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
// const Color _seed = Color.fromARGB(255, 8, 150, 255);
const Color _seed = Color.fromARGB(255, 50, 110, 160);
final _darkScheme =
ColorScheme.fromSeed(seedColor: _seed, brightness: Brightness.dark);
final _lightScheme =
ColorScheme.fromSeed(seedColor: _seed, brightness: Brightness.light);
final darkTheme = ThemeData(
colorScheme: _darkScheme,
toggleableActiveColor: _darkScheme.primary,
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: _darkScheme.primary,
splashColor: _darkScheme.secondary,
),
cardColor: _darkScheme.secondaryContainer);
final lightTheme = ThemeData(
colorScheme: _lightScheme,
toggleableActiveColor: _lightScheme.primary,
cardColor: _lightScheme.secondaryContainer);
final bottomButtonStyle = ButtonStyle(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
shape: MaterialStateProperty.all(
const RoundedRectangleBorder(
borderRadius:
BorderRadius.vertical(top: Radius.zero, bottom: Radius.circular(10)),
),
),
);
// https://stackoverflow.com/a/51119796/13538080
class MyBehavior extends ScrollBehavior {
@override
Widget buildOverscrollIndicator(
BuildContext context, Widget child, ScrollableDetails details) {
return child;
}
}

View File

@@ -0,0 +1,112 @@
import "package:flutter/material.dart";
enum ListViewState { inUse, changed, inactive }
class PaginationListView extends StatefulWidget {
final Widget Function(BuildContext context, dynamic data) itemBuilder;
final Widget Function(BuildContext context, dynamic data) seperatorBuilder;
final bool? shrinkWrap;
final ListViewState state;
final Future<List<dynamic>> Function(int page) dataProvider;
const PaginationListView(
{super.key,
required this.itemBuilder,
required this.dataProvider,
required this.state,
required this.seperatorBuilder,
this.shrinkWrap});
@override
State<PaginationListView> createState() => _PaginationListViewState();
}
class _PaginationListViewState extends State<PaginationListView> {
int _pagesLoaded = 0;
List<dynamic> _data = [];
bool _dataLeft = true;
bool _isLoading = false;
ListViewState _state = ListViewState.inactive;
late ScrollController _scrollController;
void consumeData() async {
if (_state != ListViewState.inUse || _isLoading || !_dataLeft) {
return;
}
setState(() {
_isLoading = true;
});
List<dynamic> newData = await widget.dataProvider(_pagesLoaded + 1);
if (newData[newData.length - 1] == null) {
newData.removeAt(newData.length - 1);
_dataLeft = false;
}
_pagesLoaded++;
setState(() {
_data.addAll(newData);
});
setState(() {
_isLoading = false;
});
}
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_state = widget.state;
}
@override
void didUpdateWidget(covariant PaginationListView oldWidget) {
super.didUpdateWidget(oldWidget);
_state = widget.state;
if (_state == ListViewState.changed) {
_state = ListViewState.inUse;
_data = [];
_dataLeft = true;
_isLoading = false;
_pagesLoaded = 0;
consumeData();
}
}
@override
Widget build(BuildContext context) {
List<Widget> stackChildren = [
NotificationListener<ScrollNotification>(
onNotification: (notification) {
if (_scrollController.position.maxScrollExtent ==
_scrollController.position.pixels) {
consumeData();
}
return true;
},
// child: Scrollbar(
child: ListView.separated(
controller: _scrollController,
itemCount: _data.length,
shrinkWrap: widget.shrinkWrap ?? false,
itemBuilder: (context, index) =>
widget.itemBuilder(context, _data[index]),
separatorBuilder: (context, index) =>
widget.seperatorBuilder(context, _data[index]),
),
),
// )
];
if (_isLoading) {
stackChildren.add(const Center(child: CircularProgressIndicator()));
}
return Stack(
children: stackChildren,
);
}
}

View File

@@ -0,0 +1,82 @@
import 'package:flutter/material.dart';
class TextEntryForm extends StatefulWidget {
final String title;
final String label;
final String? defaultValue;
const TextEntryForm(
{super.key, required this.title, required this.label, this.defaultValue});
@override
State<TextEntryForm> createState() => _TextEntryFormState();
}
class _TextEntryFormState extends State<TextEntryForm> {
late TextEditingController _textController;
@override
void initState() {
super.initState();
_textController = TextEditingController(text: widget.defaultValue);
}
@override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.zero,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.title,
style: Theme.of(context).textTheme.titleMedium,
),
const Divider(),
TextFormField(
controller: _textController,
decoration: InputDecoration(hintText: widget.label),
),
Padding(
padding: const EdgeInsets.only(top: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () => Navigator.pop(context),
child: const Text("Cancel"),
),
ElevatedButton(
onPressed: () =>
Navigator.pop(context, _textController.text),
child: const Text("Done")),
],
),
),
],
),
),
);
}
}
Future<String?> textEntryDialog(
BuildContext context, String title, String label,
{String? defaultValue}) async {
String? name = await showDialog(
context: context,
builder: (context) {
return Dialog(
child: TextEntryForm(
title: title,
label: label,
defaultValue: defaultValue,
),
);
},
);
return name;
}