updated project style guidelines

This commit is contained in:
Elias Müller 2024-04-03 19:18:17 +02:00
parent 27618f4404
commit 4c7f53e309
185 changed files with 505 additions and 873 deletions

View File

@ -28,6 +28,13 @@ linter:
prefer_relative_imports: true
unnecessary_lambdas: true
prefer_single_quotes: true
prefer_if_elements_to_conditional_expressions: true
prefer_expression_function_bodies: true
omit_local_variable_types: true
eol_at_end_of_file: true
cast_nullable_to_non_nullable: true
avoid_void_async: true
avoid_multiple_declarations_per_line: true
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

View File

@ -4,7 +4,5 @@ class ApiError {
ApiError(this.message);
@override
String toString() {
return 'ApiError: $message';
}
String toString() => 'ApiError: $message';
}

View File

@ -6,7 +6,7 @@ import 'getHolidaysResponse.dart';
class GetHolidays {
Future<GetHolidaysResponse> query() async {
String response = (await http.get(Uri.parse('https://ferien-api.de/api/v1/holidays/HE'))).body;
var response = (await http.get(Uri.parse('https://ferien-api.de/api/v1/holidays/HE'))).body;
return GetHolidaysResponse(
List<GetHolidaysResponseObject>.from(
jsonDecode(response).map<GetHolidaysResponseObject>(

View File

@ -23,7 +23,5 @@ class GetHolidaysCache extends RequestCache<GetHolidaysResponse> {
}
@override
Future<GetHolidaysResponse> onLoad() {
return GetHolidays().query();
}
Future<GetHolidaysResponse> onLoad() => GetHolidays().query();
}

View File

@ -2,7 +2,6 @@ import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import '../../../model/accountData.dart';
import '../../../model/endpointData.dart';
@ -10,7 +9,7 @@ import 'autocompleteResponse.dart';
class AutocompleteApi {
Future<AutocompleteResponse> find(String query) async {
Map<String, dynamic> getParameters = {
var getParameters = <String, dynamic>{
'search': query,
'itemType': ' ',
'itemId': ' ',
@ -18,15 +17,15 @@ class AutocompleteApi {
'limit': '10',
};
Map<String, String> headers = {};
var headers = <String, String>{};
headers.putIfAbsent('Accept', () => 'application/json');
headers.putIfAbsent('OCS-APIRequest', () => 'true');
Uri endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/core/autocomplete/get', getParameters);
var endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/core/autocomplete/get', getParameters);
Response response = await http.get(endpoint, headers: headers);
var response = await http.get(endpoint, headers: headers);
if(response.statusCode != HttpStatus.ok) throw Exception('Api call failed with ${response.statusCode}: ${response.body}');
String result = response.body;
var result = response.body;
return AutocompleteResponse.fromJson(jsonDecode(result)['ocs']);
}

View File

@ -1,7 +1,6 @@
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import '../../../model/accountData.dart';
import '../../../model/endpointData.dart';
@ -9,12 +8,12 @@ import 'fileSharingApiParams.dart';
class FileSharingApi {
Future<void> share(FileSharingApiParams query) async {
Map<String, String> headers = {};
var headers = <String, String>{};
headers.putIfAbsent('Accept', () => 'application/json');
headers.putIfAbsent('OCS-APIRequest', () => 'true');
Uri endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/files_sharing/api/v1/shares', query.toJson().map((key, value) => MapEntry(key, value.toString())));
Response response = await http.post(endpoint, headers: headers);
var endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/files_sharing/api/v1/shares', query.toJson().map((key, value) => MapEntry(key, value.toString())));
var response = await http.post(endpoint, headers: headers);
if(response.statusCode != HttpStatus.ok) {
throw Exception('Api call failed with ${response.statusCode}: ${response.body}');

View File

@ -14,13 +14,9 @@ class GetChat extends TalkApi<GetChatResponse> {
GetChat(this.chatToken, this.params) : super('v1/chat/$chatToken', null, getParameters: params.toJson());
@override
assemble(String raw) {
return GetChatResponse.fromJson(jsonDecode(raw)['ocs']);
}
assemble(String raw) => GetChatResponse.fromJson(jsonDecode(raw)['ocs']);
@override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) {
return http.get(uri, headers: headers);
}
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.get(uri, headers: headers);
}

View File

@ -13,8 +13,7 @@ class GetChatCache extends RequestCache<GetChatResponse> {
}
@override
Future<GetChatResponse> onLoad() {
return GetChat(
Future<GetChatResponse> onLoad() => GetChat(
chatToken,
GetChatParams(
lookIntoFuture: GetChatParamsSwitch.off,
@ -22,11 +21,8 @@ class GetChatCache extends RequestCache<GetChatResponse> {
limit: 200,
)
).run();
}
@override
GetChatResponse onLocalData(String json) {
return GetChatResponse.fromJson(jsonDecode(json));
}
GetChatResponse onLocalData(String json) => GetChatResponse.fromJson(jsonDecode(json));
}

View File

@ -16,7 +16,7 @@ class GetChatResponse extends ApiResponse {
Map<String, dynamic> toJson() => _$GetChatResponseToJson(this);
List<GetChatResponseObject> sortByTimestamp() {
List<GetChatResponseObject> sorted = data.toList();
var sorted = data.toList();
sorted.sort((a, b) => a.timestamp.compareTo(b.timestamp));
return sorted;
}
@ -60,12 +60,11 @@ class GetChatResponseObject {
Map<String, dynamic> toJson() => _$GetChatResponseObjectToJson(this);
static GetChatResponseObject getDateDummy(int timestamp) {
DateTime elementDate = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
var elementDate = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
return getTextDummy(Jiffy.parseFromDateTime(elementDate).format(pattern: 'dd.MM.yyyy'));
}
static GetChatResponseObject getTextDummy(String text) {
return GetChatResponseObject(
static GetChatResponseObject getTextDummy(String text) => GetChatResponseObject(
0,
'',
GetRoomResponseObjectMessageActorType.user,
@ -81,13 +80,12 @@ class GetChatResponseObject {
null,
null
);
}
}
Map<String, RichObjectString>? _fromJson(json) {
if(json is Map<String, dynamic>) {
Map<String, RichObjectString> data = {};
var data = <String, RichObjectString>{};
for (var element in json.keys) {
data.putIfAbsent(element, () => RichObjectString.fromJson(json[element]));
}

View File

@ -10,9 +10,7 @@ class CreateRoom extends TalkApi {
CreateRoom(this.params) : super('v4/room', params);
@override
assemble(String raw) {
return null;
}
assemble(String raw) => null;
@override
Future<Response>? request(Uri uri, Object? body, Map<String, String>? headers) {

View File

@ -10,13 +10,9 @@ class DeleteMessage extends TalkApi {
DeleteMessage(this.chatToken, this.messageId) : super('v1/chat/$chatToken/$messageId', null);
@override
assemble(String raw) {
return null;
}
assemble(String raw) => null;
@override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {
return http.delete(uri, headers: headers);
}
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) => http.delete(uri, headers: headers);
}

View File

@ -11,9 +11,7 @@ class DeleteReactMessage extends TalkApi {
DeleteReactMessage({required this.chatToken, required this.messageId, required DeleteReactMessageParams params}) : super('v1/reaction/$chatToken/$messageId', params);
@override
assemble(String raw) {
return null;
}
assemble(String raw) => null;
@override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {

View File

@ -10,13 +10,9 @@ class GetParticipants extends TalkApi<GetParticipantsResponse> {
GetParticipants(this.token) : super('v4/room/$token/participants', null);
@override
GetParticipantsResponse assemble(String raw) {
return GetParticipantsResponse.fromJson(jsonDecode(raw)['ocs']);
}
GetParticipantsResponse assemble(String raw) => GetParticipantsResponse.fromJson(jsonDecode(raw)['ocs']);
@override
Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) {
return http.get(uri, headers: headers);
}
Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.get(uri, headers: headers);
}

View File

@ -12,15 +12,11 @@ class GetParticipantsCache extends RequestCache<GetParticipantsResponse> {
}
@override
Future<GetParticipantsResponse> onLoad() {
return GetParticipants(
Future<GetParticipantsResponse> onLoad() => GetParticipants(
chatToken,
).run();
}
@override
GetParticipantsResponse onLocalData(String json) {
return GetParticipantsResponse.fromJson(jsonDecode(json));
}
GetParticipantsResponse onLocalData(String json) => GetParticipantsResponse.fromJson(jsonDecode(json));
}

View File

@ -13,13 +13,9 @@ class GetReactions extends TalkApi<GetReactionsResponse> {
GetReactions({required this.chatToken, required this.messageId}) : super('v1/reaction/$chatToken/$messageId', null);
@override
assemble(String raw) {
return GetReactionsResponse.fromJson(jsonDecode(raw)['ocs']);
}
assemble(String raw) => GetReactionsResponse.fromJson(jsonDecode(raw)['ocs']);
@override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {
return http.get(uri, headers: headers);
}
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) => http.get(uri, headers: headers);
}

View File

@ -9,12 +9,8 @@ class LeaveRoom extends TalkApi {
LeaveRoom(this.chatToken) : super('v4/room/$chatToken/participants/self', null);
@override
assemble(String raw) {
return null;
}
assemble(String raw) => null;
@override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) {
return http.delete(uri, headers: headers);
}
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.delete(uri, headers: headers);
}

View File

@ -11,9 +11,7 @@ class ReactMessage extends TalkApi {
ReactMessage({required this.chatToken, required this.messageId, required ReactMessageParams params}) : super('v1/reaction/$chatToken/$messageId', params);
@override
assemble(String raw) {
return null;
}
assemble(String raw) => null;
@override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {

View File

@ -14,13 +14,9 @@ class GetRoom extends TalkApi<GetRoomResponse> {
@override
GetRoomResponse assemble(String raw) {
return GetRoomResponse.fromJson(jsonDecode(raw)['ocs']);
}
GetRoomResponse assemble(String raw) => GetRoomResponse.fromJson(jsonDecode(raw)['ocs']);
@override
Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) {
return http.get(uri, headers: headers);
}
Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.get(uri, headers: headers);
}

View File

@ -12,16 +12,12 @@ class GetRoomCache extends RequestCache<GetRoomResponse> {
}
@override
GetRoomResponse onLocalData(String json) {
return GetRoomResponse.fromJson(jsonDecode(json));
}
GetRoomResponse onLocalData(String json) => GetRoomResponse.fromJson(jsonDecode(json));
@override
Future<GetRoomResponse> onLoad() {
return GetRoom(
Future<GetRoomResponse> onLoad() => GetRoom(
GetRoomParams(
includeStatus: true,
)
).run();
}
}

View File

@ -10,9 +10,7 @@ class SendMessage extends TalkApi {
SendMessage(this.chatToken, SendMessageParams params) : super('v1/chat/$chatToken', params);
@override
assemble(String raw) {
return null;
}
assemble(String raw) => null;
@override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {

View File

@ -11,9 +11,7 @@ class SetFavorite extends TalkApi {
SetFavorite(this.chatToken, this.favoriteState) : super('v4/room/$chatToken/favorite', null);
@override
assemble(String raw) {
return null;
}
assemble(String raw) => null;
@override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) {

View File

@ -15,9 +15,7 @@ class SetReadMarker extends TalkApi {
}
@override
assemble(String raw) {
return null;
}
assemble(String raw) => null;
@override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) {

View File

@ -34,7 +34,7 @@ abstract class TalkApi<T extends ApiResponse?> extends ApiRequest {
getParameters?.update(key, (value) => value.toString());
});
Uri endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/spreed/api/$path', getParameters);
var endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/spreed/api/$path', getParameters);
headers ??= {};
headers?.putIfAbsent('Accept', () => 'application/json');

View File

@ -6,7 +6,5 @@ class TalkError {
TalkError(this.status, this.code, this.message);
@override
String toString() {
return 'Talk - $status - ($code): $message';
}
String toString() => 'Talk - $status - ($code): $message';
}

View File

@ -13,8 +13,8 @@ class ListFiles extends WebdavApi<ListFilesParams> {
@override
Future<ListFilesResponse> run() async {
List<WebDavFile> davFiles = (await (await WebdavApi.webdav).propfind(PathUri.parse(params.path))).toWebDavFiles();
Set<CacheableFile> files = davFiles.map(CacheableFile.fromDavFile).toSet();
var davFiles = (await (await WebdavApi.webdav).propfind(PathUri.parse(params.path))).toWebDavFiles();
var files = davFiles.map(CacheableFile.fromDavFile).toSet();
// webdav handles subdirectories wrong, this is a fix
// currently this fix is not needed anymore

View File

@ -11,19 +11,17 @@ class ListFilesCache extends RequestCache<ListFilesResponse> {
ListFilesCache({required onUpdate, required this.path}) : super(RequestCache.cacheNothing, onUpdate) {
var bytes = utf8.encode('MarianumMobile-$path');
String cacheName = md5.convert(bytes).toString();
var cacheName = md5.convert(bytes).toString();
start('MarianumMobile', 'wd-folder-$cacheName');
}
@override
Future<ListFilesResponse> onLoad() async {
ListFilesResponse data = await ListFiles(ListFilesParams(path)).run();
var data = await ListFiles(ListFilesParams(path)).run();
return data;
}
@override
ListFilesResponse onLocalData(String json) {
return ListFilesResponse.fromJson(jsonDecode(json));
}
ListFilesResponse onLocalData(String json) => ListFilesResponse.fromJson(jsonDecode(json));
}

View File

@ -17,11 +17,7 @@ abstract class WebdavApi<T> extends ApiRequest {
static Future<WebDavClient> webdav = establishWebdavConnection();
static Future<String> webdavConnectString = buildWebdavConnectString();
static Future<WebDavClient> establishWebdavConnection() async {
return NextcloudClient(Uri.parse('https://${EndpointData().nextcloud().full()}'), password: AccountData().getPassword(), loginName: AccountData().getUsername()).webdav;
}
static Future<WebDavClient> establishWebdavConnection() async => NextcloudClient(Uri.parse('https://${EndpointData().nextcloud().full()}'), password: AccountData().getPassword(), loginName: AccountData().getUsername()).webdav;
static Future<String> buildWebdavConnectString() async {
return 'https://${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().full()}/remote.php/dav/files/${AccountData().getUsername()}/';
}
static Future<String> buildWebdavConnectString() async => 'https://${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().full()}/remote.php/dav/files/${AccountData().getUsername()}/';
}

View File

@ -9,13 +9,9 @@ class GetBreakers extends MhslApi<GetBreakersResponse> {
GetBreakers() : super('breaker/');
@override
GetBreakersResponse assemble(String raw) {
return GetBreakersResponse.fromJson(jsonDecode(raw));
}
GetBreakersResponse assemble(String raw) => GetBreakersResponse.fromJson(jsonDecode(raw));
@override
Future<Response>? request(Uri uri) {
return http.get(uri);
}
Future<Response>? request(Uri uri) => http.get(uri);
}

View File

@ -10,12 +10,8 @@ class GetBreakersCache extends RequestCache<GetBreakersResponse> {
}
@override
GetBreakersResponse onLocalData(String json) {
return GetBreakersResponse.fromJson(jsonDecode(json));
}
GetBreakersResponse onLocalData(String json) => GetBreakersResponse.fromJson(jsonDecode(json));
@override
Future<GetBreakersResponse> onLoad() {
return GetBreakers().run();
}
Future<GetBreakersResponse> onLoad() => GetBreakers().run();
}

View File

@ -16,7 +16,7 @@ class AddCustomTimetableEvent extends MhslApi<void> {
@override
Future<Response>? request(Uri uri) {
String body = jsonEncode(params.toJson());
var body = jsonEncode(params.toJson());
return http.post(uri, body: body);
}
}

View File

@ -12,12 +12,8 @@ class GetCustomTimetableEvent extends MhslApi<GetCustomTimetableEventResponse> {
GetCustomTimetableEvent(this.params) : super('server/timetable/customEvents?user=${params.user}');
@override
GetCustomTimetableEventResponse assemble(String raw) {
return GetCustomTimetableEventResponse.fromJson({'events': jsonDecode(raw)});
}
GetCustomTimetableEventResponse assemble(String raw) => GetCustomTimetableEventResponse.fromJson({'events': jsonDecode(raw)});
@override
Future<Response>? request(Uri uri) {
return http.get(uri);
}
Future<Response>? request(Uri uri) => http.get(uri);
}

View File

@ -13,12 +13,8 @@ class GetCustomTimetableEventCache extends RequestCache<GetCustomTimetableEventR
}
@override
Future<GetCustomTimetableEventResponse> onLoad() {
return GetCustomTimetableEvent(params).run();
}
Future<GetCustomTimetableEventResponse> onLoad() => GetCustomTimetableEvent(params).run();
@override
GetCustomTimetableEventResponse onLocalData(String json) {
return GetCustomTimetableEventResponse.fromJson(jsonDecode(json));
}
GetCustomTimetableEventResponse onLocalData(String json) => GetCustomTimetableEventResponse.fromJson(jsonDecode(json));
}

View File

@ -15,7 +15,5 @@ class RemoveCustomTimetableEvent extends MhslApi<void> {
void assemble(String raw) {}
@override
Future<Response>? request(Uri uri) {
return http.delete(uri, body: jsonEncode(params.toJson()));
}
Future<Response>? request(Uri uri) => http.delete(uri, body: jsonEncode(params.toJson()));
}

View File

@ -15,7 +15,5 @@ class UpdateCustomTimetableEvent extends MhslApi<void> {
void assemble(String raw) {}
@override
Future<Response>? request(Uri uri) {
return http.patch(uri, body: jsonEncode(params.toJson()));
}
Future<Response>? request(Uri uri) => http.patch(uri, body: jsonEncode(params.toJson()));
}

View File

@ -10,12 +10,8 @@ class GetMessages extends MhslApi<GetMessagesResponse> {
@override
GetMessagesResponse assemble(String raw) {
return GetMessagesResponse.fromJson(jsonDecode(raw));
}
GetMessagesResponse assemble(String raw) => GetMessagesResponse.fromJson(jsonDecode(raw));
@override
Future<http.Response> request(Uri uri) {
return http.get(uri);
}
Future<http.Response> request(Uri uri) => http.get(uri);
}

View File

@ -10,12 +10,8 @@ class GetMessagesCache extends RequestCache<GetMessagesResponse> {
}
@override
GetMessagesResponse onLocalData(String json) {
return GetMessagesResponse.fromJson(jsonDecode(json));
}
GetMessagesResponse onLocalData(String json) => GetMessagesResponse.fromJson(jsonDecode(json));
@override
Future<GetMessagesResponse> onLoad() {
return GetMessages().run();
}
Future<GetMessagesResponse> onLoad() => GetMessages().run();
}

View File

@ -15,9 +15,9 @@ abstract class MhslApi<T> extends ApiRequest {
T assemble(String raw);
Future<T> run() async {
Uri endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath');
var endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath');
http.Response? data = await request(endpoint);
var data = await request(endpoint);
if(data == null) {
throw ApiError('Request could not be dispatched!');
}
@ -31,5 +31,4 @@ abstract class MhslApi<T> extends ApiRequest {
static String dateTimeToJson(DateTime time) => Jiffy.parseFromDateTime(time).format(pattern: 'yyyy-MM-dd HH:mm:ss');
static DateTime dateTimeFromJson(String time) => DateTime.parse(time);
}

View File

@ -19,7 +19,7 @@ class NotifyRegister extends MhslApi<void> {
@override
Future<http.Response> request(Uri uri) {
String requestString = jsonEncode(params.toJson());
var requestString = jsonEncode(params.toJson());
log(requestString);
return http.post(uri, body: requestString);
}

View File

@ -15,7 +15,5 @@ class AddFeedback extends MhslApi<void> {
void assemble(String raw) {}
@override
Future<Response>? request(Uri uri) {
return http.post(uri, body: jsonEncode(params.toJson()));
}
Future<Response>? request(Uri uri) => http.post(uri, body: jsonEncode(params.toJson()));
}

View File

@ -19,12 +19,12 @@ class UpdateUserIndex extends MhslApi<void> {
@override
Future<http.Response> request(Uri uri) {
String data = jsonEncode(params.toJson());
var data = jsonEncode(params.toJson());
log('Updating userindex:\n $data');
return http.post(uri, body: data);
}
static void index() async {
static Future<void> index() async {
UpdateUserIndex(
UpdateUserIndexParams(
username: AccountData().getUsername(),

View File

@ -20,8 +20,8 @@ abstract class RequestCache<T extends ApiResponse?> {
static void ignore(Exception e) {}
void start(String file, String document) async {
Map<String, dynamic>? tableData = await Localstore.instance.collection(file).doc(document).get();
Future<void> start(String file, String document) async {
var tableData = await Localstore.instance.collection(file).doc(document).get();
if(tableData != null) {
onUpdate(onLocalData(tableData['json']));
}
@ -31,7 +31,7 @@ abstract class RequestCache<T extends ApiResponse?> {
}
try {
T newValue = await onLoad();
var newValue = await onLoad();
onUpdate(newValue);
Localstore.instance.collection(file).doc(document).set({

View File

@ -14,7 +14,7 @@ class Authenticate extends WebuntisApi {
@override
Future<AuthenticateResponse> run() async {
awaitingResponse = true;
String rawAnswer = await query(this);
var rawAnswer = await query(this);
AuthenticateResponse response = finalize(AuthenticateResponse.fromJson(jsonDecode(rawAnswer)['result']));
_lastResponse = response;
if(!awaitedResponse.isCompleted) awaitedResponse.complete();

View File

@ -8,7 +8,7 @@ class GetHolidays extends WebuntisApi {
@override
Future<GetHolidaysResponse> run() async {
String rawAnswer = await query(this);
var rawAnswer = await query(this);
return finalize(GetHolidaysResponse.fromJson(jsonDecode(rawAnswer)));
}
@ -17,8 +17,8 @@ class GetHolidays extends WebuntisApi {
time = DateTime(time.year, time.month, time.day, 0, 0, 0, 0, 0);
for (var element in holidaysResponse.result) {
DateTime start = DateTime.parse(element.startDate.toString());
DateTime end = DateTime.parse(element.endDate.toString());
var start = DateTime.parse(element.startDate.toString());
var end = DateTime.parse(element.endDate.toString());
if(!start.isAfter(time) && !end.isBefore(time)) return element;
}

View File

@ -10,12 +10,8 @@ class GetHolidaysCache extends RequestCache<GetHolidaysResponse> {
}
@override
Future<GetHolidaysResponse> onLoad() {
return GetHolidays().run();
}
Future<GetHolidaysResponse> onLoad() => GetHolidays().run();
@override
GetHolidaysResponse onLocalData(String json) {
return GetHolidaysResponse.fromJson(jsonDecode(json));
}
GetHolidaysResponse onLocalData(String json) => GetHolidaysResponse.fromJson(jsonDecode(json));
}

View File

@ -9,7 +9,7 @@ class GetRooms extends WebuntisApi {
@override
Future<GetRoomsResponse> run() async {
String rawAnswer = await query(this);
var rawAnswer = await query(this);
try {
return finalize(GetRoomsResponse.fromJson(jsonDecode(rawAnswer)));
} catch(e, trace) {

View File

@ -10,13 +10,9 @@ class GetRoomsCache extends RequestCache<GetRoomsResponse> {
}
@override
Future<GetRoomsResponse> onLoad() {
return GetRooms().run();
}
Future<GetRoomsResponse> onLoad() => GetRooms().run();
@override
GetRoomsResponse onLocalData(String json) {
return GetRoomsResponse.fromJson(jsonDecode(json));
}
GetRoomsResponse onLocalData(String json) => GetRoomsResponse.fromJson(jsonDecode(json));
}

View File

@ -8,7 +8,7 @@ class GetSubjects extends WebuntisApi {
@override
Future<GetSubjectsResponse> run() async {
String rawAnswer = await query(this);
var rawAnswer = await query(this);
return finalize(GetSubjectsResponse.fromJson(jsonDecode(rawAnswer)));
}
}

View File

@ -10,13 +10,9 @@ class GetSubjectsCache extends RequestCache<GetSubjectsResponse> {
}
@override
Future<GetSubjectsResponse> onLoad() {
return GetSubjects().run();
}
Future<GetSubjectsResponse> onLoad() => GetSubjects().run();
@override
onLocalData(String json) {
return GetSubjectsResponse.fromJson(jsonDecode(json));
}
onLocalData(String json) => GetSubjectsResponse.fromJson(jsonDecode(json));
}

View File

@ -11,7 +11,7 @@ class GetTimetable extends WebuntisApi {
@override
Future<GetTimetableResponse> run() async {
String rawAnswer = await query(this);
var rawAnswer = await query(this);
return finalize(GetTimetableResponse.fromJson(jsonDecode(rawAnswer)));
}

View File

@ -15,13 +15,10 @@ class GetTimetableCache extends RequestCache<GetTimetableResponse> {
}
@override
GetTimetableResponse onLocalData(String json) {
return GetTimetableResponse.fromJson(jsonDecode(json));
}
GetTimetableResponse onLocalData(String json) => GetTimetableResponse.fromJson(jsonDecode(json));
@override
Future<GetTimetableResponse> onLoad() async {
return GetTimetable(
Future<GetTimetableResponse> onLoad() async => GetTimetable(
GetTimetableParams(
options: GetTimetableParamsOptions(
element: GetTimetableParamsOptionsElement(
@ -38,5 +35,4 @@ class GetTimetableCache extends RequestCache<GetTimetableResponse> {
)
)
).run();
}
}

View File

@ -20,13 +20,13 @@ abstract class WebuntisApi extends ApiRequest {
Future<String> query(WebuntisApi untis) async {
String query = '{"id":"ID","method":"$method","params":${untis._body()},"jsonrpc":"2.0"}';
var query = '{"id":"ID","method":"$method","params":${untis._body()},"jsonrpc":"2.0"}';
String sessionId = '0';
var sessionId = '0';
if(authenticatedResponse) {
sessionId = (await Authenticate.getSession()).sessionId;
}
http.Response data = await post(query, {'Cookie': 'JSESSIONID=$sessionId'});
var data = await post(query, {'Cookie': 'JSESSIONID=$sessionId'});
response = data;
dynamic jsonData = jsonDecode(data.body);
@ -48,16 +48,12 @@ abstract class WebuntisApi extends ApiRequest {
Future<ApiResponse> run();
String _body() {
return genericParam == null ? '{}' : jsonEncode(genericParam);
}
String _body() => genericParam == null ? '{}' : jsonEncode(genericParam);
Future<http.Response> post(String data, Map<String, String>? headers) async {
return await http
Future<http.Response> post(String data, Map<String, String>? headers) async => await http
.post(endpoint, body: data, headers: headers)
.timeout(
const Duration(seconds: 10),
onTimeout: () => throw WebuntisError('Timeout', 1)
);
}
}

View File

@ -5,7 +5,5 @@ class WebuntisError implements Exception {
WebuntisError(this.message, this.code);
@override
String toString() {
return 'WebUntis ($code): $message';
}
String toString() => 'WebUntis ($code): $message';
}

View File

@ -94,8 +94,7 @@ class _AppState extends State<App> with WidgetsBindingObserver {
}
@override
Widget build(BuildContext context) {
return PersistentTabView(
Widget build(BuildContext context) => PersistentTabView(
controller: App.bottomNavigator,
navBarOverlap: const NavBarOverlap.none(),
backgroundColor: Theme.of(context).colorScheme.primary,
@ -119,7 +118,7 @@ class _AppState extends State<App> with WidgetsBindingObserver {
icon: Consumer<ChatListProps>(
builder: (context, value, child) {
if(value.primaryLoading()) return const Icon(Icons.chat);
int messages = value.getRoomsResponse.data.map((e) => e.unreadMessages).reduce((a, b) => a+b);
var messages = value.getRoomsResponse.data.map((e) => e.unreadMessages).reduce((a, b) => a+b);
return badges.Badge(
showBadge: messages > 0,
position: badges.BadgePosition.topEnd(top: -3, end: -3),
@ -164,7 +163,6 @@ class _AppState extends State<App> with WidgetsBindingObserver {
),
),
);
}
@override
void dispose() {

View File

@ -1,30 +1,20 @@
import 'package:flutter/material.dart';
extension IsSameDay on DateTime {
bool isSameDay(DateTime other) {
return year == other.year && month == other.month && day == other.day;
}
bool isSameDay(DateTime other) => year == other.year && month == other.month && day == other.day;
DateTime nextWeekday(int day) {
return add(Duration(days: (day - weekday) % DateTime.daysPerWeek));
}
DateTime nextWeekday(int day) => add(Duration(days: (day - weekday) % DateTime.daysPerWeek));
DateTime withTime(TimeOfDay time) {
return copyWith(hour: time.hour, minute: time.minute);
}
DateTime withTime(TimeOfDay time) => copyWith(hour: time.hour, minute: time.minute);
TimeOfDay toTimeOfDay() {
return TimeOfDay(hour: hour, minute: minute);
}
TimeOfDay toTimeOfDay() => TimeOfDay(hour: hour, minute: minute);
bool isSameDateTime(DateTime other) {
bool isSameDay = this.isSameDay(other);
bool isSameTimeOfDay = (toTimeOfDay() == other.toTimeOfDay());
var isSameDay = this.isSameDay(other);
var isSameTimeOfDay = (toTimeOfDay() == other.toTimeOfDay());
return isSameDay && isSameTimeOfDay;
}
bool isSameOrAfter(DateTime other) {
return isSameDateTime(other) || isAfter(other);
}
bool isSameOrAfter(DateTime other) => isSameDateTime(other) || isAfter(other);
}

View File

@ -1,5 +1,3 @@
extension RenderNotNullExt<T> on T? {
R? wrapNullable<R>(R Function(T data) defaultValueCallback) {
return this != null ? defaultValueCallback(this as T) : null;
}
R? wrapNullable<R>(R Function(T data) defaultValueCallback) => this != null ? defaultValueCallback(this as T) : null;
}

View File

@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
extension TextExt on Text {
Size get size {
final TextPainter textPainter = TextPainter(
final textPainter = TextPainter(
text: TextSpan(text: data, style: style),
maxLines: 1,
textDirection: TextDirection.ltr

View File

@ -1,15 +1,9 @@
import 'package:flutter/material.dart';
extension TimeOfDayExt on TimeOfDay {
bool isBefore(TimeOfDay other) {
return hour < other.hour && minute < other.minute;
}
bool isBefore(TimeOfDay other) => hour < other.hour && minute < other.minute;
bool isAfter(TimeOfDay other) {
return hour > other.hour && minute > other.minute;
}
bool isAfter(TimeOfDay other) => hour > other.hour && minute > other.minute;
TimeOfDay add({int hours = 0, int minutes = 0}) {
return replacing(hour: hour + hours, minute: minute + minutes);
}
TimeOfDay add({int hours = 0, int minutes = 0}) => replacing(hour: hour + hours, minute: minute + minutes);
}

View File

@ -41,16 +41,14 @@ Future<void> main() async {
log('Error initializing Firebase app!');
}
ByteData data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
var data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List());
if(kReleaseMode) {
ErrorWidget.builder = (error) {
return PlaceholderView(
ErrorWidget.builder = (error) => PlaceholderView(
icon: Icons.phonelink_erase_rounded,
text: error.toStringShort(),
);
};
}
runApp(
@ -101,8 +99,7 @@ class _MainState extends State<Main> {
}
@override
Widget build(BuildContext context) {
return Directionality(
Widget build(BuildContext context) => Directionality(
textDirection: TextDirection.ltr,
child: Consumer<SettingsProvider>(
builder: (context, settings, child) {
@ -146,7 +143,6 @@ class _MainState extends State<Main> {
},
),
);
}
@override
void dispose() {

View File

@ -17,9 +17,7 @@ class AccountData {
final Future<SharedPreferences> _storage = SharedPreferences.getInstance();
Completer<void> _populated = Completer();
factory AccountData() {
return _instance;
}
factory AccountData() => _instance;
AccountData._construct() {
_updateFromStorage();
@ -38,16 +36,12 @@ class AccountData {
return _password!;
}
String getUserSecret() {
return sha512.convert(utf8.encode('${AccountData().getUsername()}:${AccountData().getPassword()}')).toString();
}
String getUserSecret() => sha512.convert(utf8.encode('${AccountData().getUsername()}:${AccountData().getPassword()}')).toString();
Future<String> getDeviceId() async {
return sha512.convert(utf8.encode('${getUserSecret()}@${await FirebaseMessaging.instance.getToken()}')).toString();
}
Future<String> getDeviceId() async => sha512.convert(utf8.encode('${getUserSecret()}@${await FirebaseMessaging.instance.getToken()}')).toString();
Future<void> setData(String username, String password) async {
SharedPreferences storage = await _storage;
var storage = await _storage;
storage.setString(_usernameField, username);
storage.setString(_passwordField, password);
@ -59,13 +53,13 @@ class AccountData {
if(context != null) Provider.of<AccountModel>(context, listen: false).setState(AccountModelState.loggedOut);
SharedPreferences storage = await _storage;
var storage = await _storage;
await storage.remove(_usernameField);
await storage.remove(_passwordField);
}
Future<void> _updateFromStorage() async {
SharedPreferences storage = await _storage;
var storage = await _storage;
//await storage.reload(); // This line was the cause of the first rejected google play upload :(
if(storage.containsKey(_usernameField) && storage.containsKey(_passwordField)) {
_username = storage.getString(_usernameField);
@ -79,9 +73,7 @@ class AccountData {
return isPopulated();
}
bool isPopulated() {
return _username != null && _password != null;
}
bool isPopulated() => _username != null && _password != null;
String buildHttpAuthString() {
if(!isPopulated()) throw Exception('AccountData (e.g. username or password) is not initialized!');

View File

@ -19,10 +19,9 @@ class Breaker extends StatefulWidget {
class _BreakerState extends State<Breaker> {
@override
Widget build(BuildContext context) {
return Consumer<BreakerProps>(
Widget build(BuildContext context) => Consumer<BreakerProps>(
builder: (context, value, child) {
String? blocked = value.isBlocked(widget.breaker);
var blocked = value.isBlocked(widget.breaker);
if(blocked != null) {
return PlaceholderView(icon: Icons.security_outlined, text: "Die App/ Dieser Bereich wurde als Schutzmaßnahme deaktiviert!\n\n${blocked.isEmpty ? "Es wurde vom Server kein Grund übermittelt." : blocked}");
}
@ -30,5 +29,4 @@ class _BreakerState extends State<Breaker> {
return widget.child;
},
);
}
}

View File

@ -18,13 +18,13 @@ class BreakerProps extends DataHolder {
}
if(primaryLoading()) return null;
GetBreakersResponse breakers = _getBreakersResponse!;
var breakers = _getBreakersResponse!;
if(breakers.global.areas.contains(type)) return breakers.global.message;
int selfVersion = int.parse(packageInfo!.buildNumber);
var selfVersion = int.parse(packageInfo!.buildNumber);
for(var key in breakers.regional.keys) {
GetBreakersReponseObject value = breakers.regional[key]!;
var value = breakers.regional[key]!;
if(int.parse(key.split('b')[1]) >= selfVersion) {
if(value.areas.contains(type)) return value.message;
@ -35,9 +35,7 @@ class BreakerProps extends DataHolder {
}
@override
List<ApiResponse?> properties() {
return [_getBreakersResponse];
}
List<ApiResponse?> properties() => [_getBreakersResponse];
@override
void run() {

View File

@ -11,9 +11,7 @@ class ChatListProps extends DataHolder {
GetRoomResponse get getRoomsResponse => _getRoomResponse!;
@override
List<ApiResponse?> properties() {
return [_getRoomResponse];
}
List<ApiResponse?> properties() => [_getRoomResponse];
@override
void run({renew}) {

View File

@ -11,15 +11,13 @@ class ChatProps extends DataHolder {
GetChatResponse get getChatResponse => _getChatResponse!;
@override
List<ApiResponse?> properties() {
return [_getChatResponse];
}
List<ApiResponse?> properties() => [_getChatResponse];
@override
void run() {
notifyListeners();
if(_queryToken.isEmpty) return;
DateTime requestStart = DateTime.now();
var requestStart = DateTime.now();
GetChatCache(
chatToken: _queryToken,
@ -39,7 +37,5 @@ class ChatProps extends DataHolder {
run();
}
String currentToken() {
return _queryToken;
}
String currentToken() => _queryToken;
}

View File

@ -3,10 +3,10 @@ import 'package:localstore/localstore.dart';
import '../widget/debug/cacheView.dart';
class DataCleaner {
static void cleanOldCache() async {
static Future<void> cleanOldCache() async {
var cacheData = await Localstore.instance.collection(CacheView.collection).get();
cacheData?.forEach((key, value) async {
DateTime lastUpdate = DateTime.fromMillisecondsSinceEpoch(value['lastupdate']);
var lastUpdate = DateTime.fromMillisecondsSinceEpoch(value['lastupdate']);
if(DateTime.now().subtract(const Duration(days: 200)).isAfter(lastUpdate)) {
await Localstore.instance.collection(CacheView.collection).doc(key.split('/').last).delete();
}

View File

@ -6,16 +6,14 @@ import '../api/apiResponse.dart';
abstract class DataHolder extends ChangeNotifier {
CollectionRef storage(String path) {
return Localstore.instance.collection(path);
}
CollectionRef storage(String path) => Localstore.instance.collection(path);
void run();
List<ApiResponse?> properties();
bool primaryLoading() {
// log("${toString()} ${properties().map((e) => e != null ? "1" : "0").join(", ")}");
for(ApiResponse? element in properties()) {
for(var element in properties()) {
if(element == null) return true;
}
return false;

View File

@ -23,17 +23,13 @@ class Endpoint {
Endpoint({required this.domain, this.path = ''});
String full() {
return domain + path;
}
String full() => domain + path;
}
class EndpointData {
static final EndpointData _instance = EndpointData._construct();
factory EndpointData() {
return _instance;
}
factory EndpointData() => _instance;
EndpointData._construct();
@ -43,8 +39,7 @@ class EndpointData {
return existingName.startsWith('google') ? EndpointMode.stage : EndpointMode.live;
}
Endpoint webuntis() {
return EndpointOptions(
Endpoint webuntis() => EndpointOptions(
live: Endpoint(
domain: 'peleus.webuntis.com',
),
@ -53,10 +48,8 @@ class EndpointData {
path: '/marianum/marianummobile/webuntis/public/index.php/api'
),
).get(getEndpointMode());
}
Endpoint nextcloud() {
return EndpointOptions(
Endpoint nextcloud() => EndpointOptions(
live: Endpoint(
domain: 'cloud.marianum-fulda.de',
),
@ -65,6 +58,5 @@ class EndpointData {
path: '/marianum/marianummobile/cloud',
)
).get(getEndpointMode());
}
}

View File

@ -23,9 +23,7 @@ class FilesProps extends DataHolder {
}
@override
List<ApiResponse?> properties() {
return [_listFilesResponse];
}
List<ApiResponse?> properties() => [_listFilesResponse];
@override
void run() {

View File

@ -10,9 +10,7 @@ class HolidaysProps extends DataHolder {
GetHolidaysResponse get getHolidaysResponse => _getHolidaysResponse!;
@override
List<ApiResponse?> properties() {
return [_getHolidaysResponse];
}
List<ApiResponse?> properties() => [_getHolidaysResponse];
@override
void run() {

View File

@ -9,9 +9,7 @@ class MessageProps extends DataHolder {
GetMessagesResponse get getMessagesResponse => _getMessagesResponse!;
@override
List<ApiResponse?> properties() {
return [_getMessagesResponse];
}
List<ApiResponse?> properties() => [_getMessagesResponse];
@override
void run({renew}) {

View File

@ -42,9 +42,7 @@ class TimetableProps extends DataHolder {
bool get hasError => error != null;
@override
List<ApiResponse?> properties() {
return [_getTimetableResponse, _getRoomsResponse, _getSubjectsResponse, _getHolidaysResponse, _getCustomTimetableEventResponse];
}
List<ApiResponse?> properties() => [_getTimetableResponse, _getRoomsResponse, _getSubjectsResponse, _getHolidaysResponse, _getCustomTimetableEventResponse];
@override
void run({renew}) {
@ -101,9 +99,7 @@ class TimetableProps extends DataHolder {
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
bool isWeekend(DateTime queryDate) {
return queryDate.weekday == DateTime.saturday || queryDate.weekday == DateTime.sunday;
}
bool isWeekend(DateTime queryDate) => queryDate.weekday == DateTime.saturday || queryDate.weekday == DateTime.sunday;
void updateWeek(DateTime start, DateTime end) {
properties().forEach((element) => element = null);
@ -123,7 +119,7 @@ class TimetableProps extends DataHolder {
error = null;
notifyListeners();
DateTime queryWeek = DateTime.now().add(const Duration(days: 2));
var queryWeek = DateTime.now().add(const Duration(days: 2));
startDate = getDate(queryWeek.subtract(Duration(days: queryWeek.weekday - 1)));
endDate = getDate(queryWeek.add(Duration(days: DateTime.daysPerWeek - queryWeek.weekday)));

View File

@ -3,27 +3,25 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationService {
static final NotificationService _instance = NotificationService._internal();
factory NotificationService() {
return _instance;
}
factory NotificationService() => _instance;
NotificationService._internal();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
Future<void> initializeNotifications() async {
const AndroidInitializationSettings androidSettings = AndroidInitializationSettings(
const androidSettings = AndroidInitializationSettings(
'@mipmap/ic_launcher'
);
final DarwinInitializationSettings iosSettings = DarwinInitializationSettings(
final iosSettings = DarwinInitializationSettings(
onDidReceiveLocalNotification: (id, title, body, payload) {
// TODO Navigate to Talk section (This runs when an Notification is tapped)
},
);
final InitializationSettings initializationSettings = InitializationSettings(
final initializationSettings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
@ -34,7 +32,7 @@ class NotificationService {
}
Future<void> showNotification({required String title, required String body, required int badgeCount}) async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
const androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'marmobile',
'Marianum Fulda',
@ -43,9 +41,9 @@ class NotificationService {
ticker: 'Marianum Fulda',
);
const DarwinNotificationDetails iosPlatformChannelSpecifics = DarwinNotificationDetails();
const iosPlatformChannelSpecifics = DarwinNotificationDetails();
const NotificationDetails platformChannelSpecifics = NotificationDetails(
const platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iosPlatformChannelSpecifics
);

View File

@ -8,8 +8,7 @@ import '../storage/base/settingsProvider.dart';
import '../widget/confirmDialog.dart';
class NotifyUpdater {
static ConfirmDialog enableAfterDisclaimer(SettingsProvider settings) {
return ConfirmDialog(
static ConfirmDialog enableAfterDisclaimer(SettingsProvider settings) => ConfirmDialog(
title: 'Warnung',
icon: Icons.warning_amber,
content: ''
@ -25,9 +24,8 @@ class NotifyUpdater {
NotifyUpdater.registerToServer();
},
);
}
static void registerToServer() async {
String? fcmToken = await FirebaseMessaging.instance.getToken();
static Future<void> registerToServer() async {
var fcmToken = await FirebaseMessaging.instance.getToken();
if(fcmToken == null) throw Exception('Failed to register push notification because there is no FBC token!');

View File

@ -29,7 +29,7 @@ class SettingsProvider extends ChangeNotifier {
_readFromStorage();
}
void reset() async {
Future<void> reset() async {
_storage = await SharedPreferences.getInstance();
_storage.remove(_fieldName);
_settings = DefaultSettings.get();
@ -38,7 +38,7 @@ class SettingsProvider extends ChangeNotifier {
notifyListeners();
}
void _readFromStorage() async {
Future<void> _readFromStorage() async {
_storage = await SharedPreferences.getInstance();
try {
@ -63,7 +63,7 @@ class SettingsProvider extends ChangeNotifier {
}
Map<String, dynamic> _mergeSettings(Map<String, dynamic> oldMap, Map<String, dynamic> newMap) {
Map<String, dynamic> mergedMap = Map.from(newMap);
var mergedMap = Map<String, dynamic>.from(newMap);
oldMap.forEach((key, value) {
if (mergedMap.containsKey(key)) {

View File

@ -15,9 +15,7 @@ class AppTheme {
}
}
static bool isDarkMode(BuildContext context) {
return Theme.of(context).brightness == Brightness.dark;
}
static bool isDarkMode(BuildContext context) => Theme.of(context).brightness == Brightness.dark;
}
class ThemeModeDisplay {

View File

@ -20,9 +20,7 @@ class Login extends StatefulWidget {
class _LoginState extends State<Login> {
bool displayDisclaimerText = true;
String? _checkInput(value){
return (value ?? '').length == 0 ? 'Eingabe erforderlich' : null;
}
String? _checkInput(value)=> (value ?? '').length == 0 ? 'Eingabe erforderlich' : null;
Future<String?> _login(LoginData data) async {
await AccountData().removeData();
@ -49,15 +47,10 @@ class _LoginState extends State<Login> {
return null;
}
Future<String> _resetPassword(String name) {
return Future.delayed(Duration.zero).then((_) {
return 'Diese Funktion steht nicht zur Verfügung!';
});
}
Future<String> _resetPassword(String name) => Future.delayed(Duration.zero).then((_) => 'Diese Funktion steht nicht zur Verfügung!');
@override
Widget build(BuildContext context) {
return FlutterLogin(
Widget build(BuildContext context) => FlutterLogin(
logo: Image.asset('assets/logo/icon.png').image,
userValidator: _checkInput,
@ -109,5 +102,4 @@ class _LoginState extends State<Login> {
userType: LoginUserType.name,
);
}
}

View File

@ -26,14 +26,14 @@ class FileElement extends StatefulWidget {
const FileElement(this.file, this.path, this.refetch, {super.key});
static Future<DownloaderCore> download(BuildContext context, String remotePath, String name, Function(double) onProgress, Function(OpenResult) onDone) async {
Directory paths = await getTemporaryDirectory();
var paths = await getTemporaryDirectory();
var encodedPath = Uri.encodeComponent(remotePath);
encodedPath = encodedPath.replaceAll('%2F', '/');
String local = paths.path + Platform.pathSeparator + name;
var local = paths.path + Platform.pathSeparator + name;
DownloaderUtils options = DownloaderUtils(
var options = DownloaderUtils(
progressCallback: (current, total) {
final progress = (current / total) * 100;
onProgress(progress);
@ -52,7 +52,7 @@ class FileElement extends StatefulWidget {
);
return await Flowder.download(
"${await WebdavApi.webdavConnectString}$encodedPath",
'${await WebdavApi.webdavConnectString}$encodedPath',
options,
);
}
@ -89,8 +89,7 @@ class _FileElementState extends State<FileElement> {
}
@override
Widget build(BuildContext context) {
return ListTile(
Widget build(BuildContext context) => ListTile(
leading: CenteredLeading(
Icon(widget.file.isDirectory ? Icons.folder : Icons.description_outlined)
),
@ -100,9 +99,7 @@ class _FileElementState extends State<FileElement> {
onTap: () {
if(widget.file.isDirectory) {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) {
return Files(widget.path.toList()..add(widget.file.name));
},
builder: (context) => Files(widget.path.toList()..add(widget.file.name)),
));
} else {
if(EndpointData().getEndpointMode() == EndpointMode.stage) {
@ -141,12 +138,10 @@ class _FileElementState extends State<FileElement> {
setState(() => percent = progress);
}, (result) {
if(result.type != ResultType.done) {
showDialog(context: context, builder: (context) {
return AlertDialog(
showDialog(context: context, builder: (context) => AlertDialog(
title: const Text('Download'),
content: Text(result.message),
);
});
));
}
setState(() {
@ -158,8 +153,7 @@ class _FileElementState extends State<FileElement> {
}
},
onLongPress: () {
showDialog(context: context, builder: (context) {
return SimpleDialog(
showDialog(context: context, builder: (context) => SimpleDialog(
children: [
ListTile(
leading: const Icon(Icons.delete_outline),
@ -189,9 +183,7 @@ class _FileElementState extends State<FileElement> {
),
),
],
);
});
));
},
);
}
}

View File

@ -32,18 +32,18 @@ class _FileUploadDialogState extends State<FileUploadDialog> {
TextEditingController fileNameController = TextEditingController();
void upload({bool override = false}) async {
Future<void> upload({bool override = false}) async {
setState(() {
state = FileUploadState.upload;
});
WebDavClient webdavClient = await WebdavApi.webdav;
var webdavClient = await WebdavApi.webdav;
if(!override) {
setState(() {
state = FileUploadState.checkConflict;
});
List<WebDavResponse> result = (await webdavClient.propfind(PathUri.parse(widget.remotePath.join('/')))).responses;
var result = (await webdavClient.propfind(PathUri.parse(widget.remotePath.join('/')))).responses;
if(result.any((element) => element.href!.endsWith('/$targetFileName'))) {
setState(() {
state = FileUploadState.conflict;
@ -56,7 +56,7 @@ class _FileUploadDialogState extends State<FileUploadDialog> {
}
}
Future<HttpClientResponse> uploadTask = webdavClient.putFile(File(widget.localPath), FileStat.statSync(widget.localPath), PathUri.parse(fullRemotePath)); // TODO use onProgress from putFile
var uploadTask = webdavClient.putFile(File(widget.localPath), FileStat.statSync(widget.localPath), PathUri.parse(fullRemotePath)); // TODO use onProgress from putFile
uploadTask.then(Future<HttpClientResponse?>.value).catchError((e) {
setState(() {
state = FileUploadState.error;

View File

@ -64,9 +64,7 @@ class SortOptions {
)
};
static BetterSortOption getOption(SortOption option) {
return options[option]!;
}
static BetterSortOption getOption(SortOption option) => options[option]!;
}
class _FilesState extends State<Files> {
@ -101,7 +99,7 @@ class _FilesState extends State<Files> {
@override
Widget build(BuildContext context) {
List<CacheableFile> files = data?.sortBy(
var files = data?.sortBy(
sortOption: currentSort,
foldersToTop: Provider.of<SettingsProvider>(context).val().fileSettings.sortFoldersToTop,
reversed: currentSortDirection
@ -119,8 +117,7 @@ class _FilesState extends State<Files> {
// ),
PopupMenuButton<bool>(
icon: Icon(currentSortDirection ? Icons.text_rotate_up : Icons.text_rotation_down),
itemBuilder: (context) {
return [true, false].map((e) => PopupMenuItem<bool>(
itemBuilder: (context) => [true, false].map((e) => PopupMenuItem<bool>(
value: e,
enabled: e != currentSortDirection,
child: Row(
@ -130,8 +127,7 @@ class _FilesState extends State<Files> {
Text(e ? 'Aufsteigend' : 'Absteigend')
],
)
)).toList();
},
)).toList(),
onSelected: (e) {
setState(() {
currentSortDirection = e;
@ -141,8 +137,7 @@ class _FilesState extends State<Files> {
),
PopupMenuButton<SortOption>(
icon: const Icon(Icons.sort),
itemBuilder: (context) {
return SortOptions.options.keys.map((key) => PopupMenuItem<SortOption>(
itemBuilder: (context) => SortOptions.options.keys.map((key) => PopupMenuItem<SortOption>(
value: key,
enabled: key != currentSort,
child: Row(
@ -152,8 +147,7 @@ class _FilesState extends State<Files> {
Text(SortOptions.getOption(key).displayName)
],
)
)).toList();
},
)).toList(),
onSelected: (e) {
setState(() {
currentSort = e;
@ -167,8 +161,7 @@ class _FilesState extends State<Files> {
heroTag: 'uploadFile',
backgroundColor: Theme.of(context).primaryColor,
onPressed: () {
showDialog(context: context, builder: (context) {
return SimpleDialog(
showDialog(context: context, builder: (context) => SimpleDialog(
children: [
ListTile(
leading: const Icon(Icons.create_new_folder_outlined),
@ -224,8 +217,7 @@ class _FilesState extends State<Files> {
),
),
],
);
});
));
},
child: const Icon(Icons.add),
),
@ -239,7 +231,7 @@ class _FilesState extends State<Files> {
padding: EdgeInsets.zero,
itemCount: files.length,
itemBuilder: (context, index) {
CacheableFile file = files.toList()[index];
var file = files.toList()[index];
return FileElement(file, widget.path, _query);
},
),
@ -248,7 +240,7 @@ class _FilesState extends State<Files> {
);
}
void mediaUpload(String? path) async {
Future<void> mediaUpload(String? path) async {
context.loaderOverlay.hide();
if(path == null) {

View File

@ -44,8 +44,7 @@ class _FeedbackDialogState extends State<FeedbackDialog> {
}
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Feedback'),
),
@ -125,7 +124,7 @@ class _FeedbackDialogState extends State<FeedbackDialog> {
onPressed: () async {
context.loaderOverlay.show();
var imageData = await (await FilePick.galleryPick())?.readAsBytes();
context.loaderOverlay.hide();
if(context.mounted) context.loaderOverlay.hide();
setState(() {
_image = imageData;
});
@ -170,6 +169,4 @@ class _FeedbackDialogState extends State<FeedbackDialog> {
],
),
);
}
}

View File

@ -4,7 +4,6 @@ import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:provider/provider.dart';
import '../../../../api/holidays/getHolidaysResponse.dart';
import '../../../../model/holidays/holidaysProps.dart';
import '../../../../storage/base/settingsProvider.dart';
import '../../../../widget/centeredLeading.dart';
@ -22,9 +21,7 @@ class Holidays extends StatefulWidget {
}
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${substring(1).toLowerCase()}";
}
String capitalize() => '${this[0].toUpperCase()}${substring(1).toLowerCase()}';
}
class _HolidaysState extends State<Holidays> {
@ -41,13 +38,10 @@ class _HolidaysState extends State<Holidays> {
super.initState();
}
String parseString(String enDate) {
return Jiffy.parse(enDate).format(pattern: 'dd.MM.yyyy');
}
String parseString(String enDate) => Jiffy.parse(enDate).format(pattern: 'dd.MM.yyyy');
void showDisclaimer() {
showDialog(context: context, builder: (context) {
return AlertDialog(
showDialog(context: context, builder: (context) => AlertDialog(
title: const Text('Richtigkeit und Bereitstellung der Daten'),
content: Column(
mainAxisSize: MainAxisSize.min,
@ -70,13 +64,11 @@ class _HolidaysState extends State<Holidays> {
TextButton(child: const Text('ferien-api.de besuchen'), onPressed: () => ConfirmDialog.openBrowser(context, 'https://ferien-api.de/')),
TextButton(child: const Text('Okay'), onPressed: () => Navigator.of(context).pop()),
],
);
});
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Schulferien in Hessen'),
actions: [
@ -87,8 +79,7 @@ class _HolidaysState extends State<Holidays> {
PopupMenuButton<bool>(
initialValue: settings.val().holidaysSettings.showPastEvents,
icon: const Icon(Icons.manage_history_outlined),
itemBuilder: (context) {
return [true, false].map((e) => PopupMenuItem<bool>(
itemBuilder: (context) => [true, false].map((e) => PopupMenuItem<bool>(
value: e,
enabled: e != showPastEvents,
child: Row(
@ -98,8 +89,7 @@ class _HolidaysState extends State<Holidays> {
Text(e ? 'Alle anzeigen' : 'Nur zukünftige anzeigen')
],
)
)).toList();
},
)).toList(),
onSelected: (e) {
setState(() {
showPastEvents = e;
@ -112,7 +102,7 @@ class _HolidaysState extends State<Holidays> {
body: Consumer<HolidaysProps>(builder: (context, value, child) {
if(value.primaryLoading()) return const LoadingSpinner();
List<GetHolidaysResponseObject> holidays = value.getHolidaysResponse.data;
var holidays = value.getHolidaysResponse.data;
if(!showPastEvents) holidays = holidays.where((element) => DateTime.parse(element.end).isAfter(DateTime.now())).toList();
if(holidays.isEmpty) return const PlaceholderView(icon: Icons.search_off, text: 'Es wurden keine Ferieneinträge gefunden!');
@ -120,8 +110,8 @@ class _HolidaysState extends State<Holidays> {
return ListView.builder(
itemCount: holidays.length,
itemBuilder: (context, index) {
GetHolidaysResponseObject holiday = holidays[index];
String holidayType = holiday.name.split(' ').first.capitalize();
var holiday = holidays[index];
var holidayType = holiday.name.split(' ').first.capitalize();
return ListTile(
leading: const CenteredLeading(Icon(Icons.calendar_month)),
title: Text('$holidayType ab ${parseString(holiday.start)}'),
@ -164,5 +154,4 @@ class _HolidaysState extends State<Holidays> {
},
)
);
}
}

View File

@ -1,7 +1,6 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../../api/mhsl/message/getMessages/getMessagesResponse.dart';
import '../../../../model/message/messageProps.dart';
import '../../../../widget/loadingSpinner.dart';
import 'messageView.dart';
@ -24,8 +23,7 @@ class _MessageState extends State<Message> {
}
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Marianum Message'),
),
@ -36,7 +34,7 @@ class _MessageState extends State<Message> {
child: ListView.builder(
itemCount: value.getMessagesResponse.messages.length,
itemBuilder: (context, index) {
GetMessagesResponseObject message = value.getMessagesResponse.messages.toList()[index];
var message = value.getMessagesResponse.messages.toList()[index];
return ListTile(
leading: const Column(
mainAxisAlignment: MainAxisAlignment.center,
@ -58,5 +56,4 @@ class _MessageState extends State<Message> {
);
}),
);
}
}

View File

@ -17,8 +17,7 @@ class MessageView extends StatefulWidget {
class _MessageViewState extends State<MessageView> {
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text(widget.message.name),
),
@ -27,8 +26,7 @@ class _MessageViewState extends State<MessageView> {
enableHyperlinkNavigation: true,
onDocumentLoadFailed: (PdfDocumentLoadFailedDetails e) {
Navigator.of(context).pop();
showDialog(context: context, builder: (context) {
return AlertDialog(
showDialog(context: context, builder: (context) => AlertDialog(
title: const Text('Fehler beim öffnen'),
content: Text("Dokument '${widget.message.name}' konnte nicht geladen werden:\n${e.description}"),
actions: [
@ -36,8 +34,7 @@ class _MessageViewState extends State<MessageView> {
Navigator.of(context).pop();
}, child: const Text('Ok'))
],
);
});
));
},
onHyperlinkClicked: (PdfHyperlinkClickedDetails e) {
showDialog(
@ -52,5 +49,4 @@ class _MessageViewState extends State<MessageView> {
},
),
);
}
}

View File

@ -5,8 +5,7 @@ class Roomplan extends StatelessWidget {
const Roomplan({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Raumplan'),
),
@ -17,5 +16,4 @@ class Roomplan extends StatelessWidget {
backgroundDecoration: BoxDecoration(color: Theme.of(context).colorScheme.background),
),
);
}
}

View File

@ -8,7 +8,7 @@ class AppSharePlatformView extends StatelessWidget {
@override
Widget build(BuildContext context) {
Color foregroundColor = Theme.of(context).colorScheme.onBackground;
var foregroundColor = Theme.of(context).colorScheme.onBackground;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,

View File

@ -11,8 +11,7 @@ class QrShareView extends StatefulWidget {
class _QrShareViewState extends State<QrShareView> {
@override
Widget build(BuildContext context) {
return DefaultTabController(
Widget build(BuildContext context) => DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
@ -32,5 +31,4 @@ class _QrShareViewState extends State<QrShareView> {
),
),
);
}
}

View File

@ -8,8 +8,7 @@ class SelectShareTypeDialog extends StatelessWidget {
const SelectShareTypeDialog({super.key});
@override
Widget build(BuildContext context) {
return SimpleDialog(
Widget build(BuildContext context) => SimpleDialog(
children: [
ListTile(
leading: const Icon(Icons.qr_code_2_outlined),
@ -36,5 +35,4 @@ class SelectShareTypeDialog extends StatelessWidget {
)
],
);
}
}

View File

@ -21,9 +21,7 @@ class Overhang extends StatelessWidget {
const Overhang({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Mehr'),
actions: [
@ -79,5 +77,4 @@ class Overhang extends StatelessWidget {
],
),
);
}
}

View File

@ -35,7 +35,7 @@ class _ChatInfoState extends State<ChatInfo> {
@override
Widget build(BuildContext context) {
bool isGroup = widget.room.type != GetRoomResponseObjectConversationType.oneToOne;
var isGroup = widget.room.type != GetRoomResponseObjectConversationType.oneToOne;
return Scaffold(
appBar: AppBar(
title: Text(widget.room.displayName),

View File

@ -13,20 +13,16 @@ class ParticipantsListView extends StatefulWidget {
class _ParticipantsListViewState extends State<ParticipantsListView> {
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Teilnehmende'),
),
body: ListView(
children: widget.participantsResponse.data.map((participant) {
return ListTile(
children: widget.participantsResponse.data.map((participant) => ListTile(
leading: UserAvatar(id: participant.actorId),
title: Text(participant.displayName),
subtitle: participant.statusMessage != null ? Text(participant.statusMessage!) : null,
);
}).toList(),
)).toList(),
),
);
}
}

View File

@ -119,14 +119,14 @@ class _ChatListState extends State<ChatList> {
if(data.primaryLoading()) return const LoadingSpinner();
latestData = data;
List<ChatTile> chats = [];
var chats = <ChatTile>[];
for (var chatRoom in data.getRoomsResponse.sortBy(
lastActivity: true,
favoritesToTop: Provider.of<SettingsProvider>(context).val().talkSettings.sortFavoritesToTop,
unreadToTop: Provider.of<SettingsProvider>(context).val().talkSettings.sortUnreadToTop,
)
) {
bool hasDraft = settings.val().talkSettings.drafts.containsKey(chatRoom.token);
var hasDraft = settings.val().talkSettings.drafts.containsKey(chatRoom.token);
chats.add(ChatTile(data: chatRoom, query: _query, hasDraft: hasDraft));
}

View File

@ -40,19 +40,18 @@ class _ChatViewState extends State<ChatView> {
}
@override
Widget build(BuildContext context) {
return Consumer<ChatProps>(
Widget build(BuildContext context) => Consumer<ChatProps>(
builder: (context, data, child) {
List<Widget> messages = List<Widget>.empty(growable: true);
var messages = List<Widget>.empty(growable: true);
if(!data.primaryLoading()) {
DateTime lastDate = DateTime.now();
var lastDate = DateTime.now();
data.getChatResponse.sortByTimestamp().forEach((element) {
DateTime elementDate = DateTime.fromMillisecondsSinceEpoch(element.timestamp * 1000);
var elementDate = DateTime.fromMillisecondsSinceEpoch(element.timestamp * 1000);
if(element.systemMessage.contains('reaction')) return;
int commonRead = int.parse(data.getChatResponse.headers?['x-chat-last-common-read'] ?? '0');
var commonRead = int.parse(data.getChatResponse.headers?['x-chat-last-common-read'] ?? '0');
if(!elementDate.isSameDay(lastDate)) {
lastDate = elementDate;
@ -140,5 +139,4 @@ class _ChatViewState extends State<ChatView> {
);
},
);
}
}

View File

@ -51,15 +51,13 @@ class ChatBubble extends StatefulWidget {
class _ChatBubbleState extends State<ChatBubble> {
BubbleStyle getSystemStyle() {
return BubbleStyle(
BubbleStyle getSystemStyle() => BubbleStyle(
color: AppTheme.isDarkMode(context) ? const Color(0xff182229) : Colors.white,
borderWidth: 1,
elevation: 2,
margin: const BubbleEdges.only(bottom: 20, top: 10),
alignment: Alignment.center,
);
}
BubbleStyle getRemoteStyle(bool seamless) {
var color = AppTheme.isDarkMode(context) ? const Color(0xff202c33) : Colors.white;
@ -105,17 +103,17 @@ class _ChatBubbleState extends State<ChatBubble> {
@override
Widget build(BuildContext context) {
message = ChatMessage(originalMessage: widget.bubbleData.message, originalData: widget.bubbleData.messageParameters);
bool showActorDisplayName = widget.bubbleData.messageType == GetRoomResponseObjectMessageType.comment && widget.chatData.type != GetRoomResponseObjectConversationType.oneToOne;
bool showBubbleTime = widget.bubbleData.messageType != GetRoomResponseObjectMessageType.system;
var showActorDisplayName = widget.bubbleData.messageType == GetRoomResponseObjectMessageType.comment && widget.chatData.type != GetRoomResponseObjectConversationType.oneToOne;
var showBubbleTime = widget.bubbleData.messageType != GetRoomResponseObjectMessageType.system;
Text actorText = Text(
var actorText = Text(
widget.bubbleData.actorDisplayName,
textAlign: TextAlign.start,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold),
);
Text timeText = Text(
var timeText = Text(
Jiffy.parseFromMillisecondsSinceEpoch(widget.bubbleData.timestamp * 1000).format(pattern: 'HH:mm'),
textAlign: TextAlign.end,
style: TextStyle(color: widget.timeIconColor, fontSize: widget.timeIconSize),
@ -186,8 +184,8 @@ class _ChatBubbleState extends State<ChatBubble> {
),
onLongPress: () {
showDialog(context: context, builder: (context) {
List<String> commonReactions = ['👍', '👎', '😆', '❤️', '👀'];
bool canReact = widget.bubbleData.messageType == GetRoomResponseObjectMessageType.comment;
var commonReactions = <String>['👍', '👎', '😆', '❤️', '👀'];
var canReact = widget.bubbleData.messageType == GetRoomResponseObjectMessageType.comment;
return SimpleDialog(
children: [
Visibility(
@ -217,8 +215,7 @@ class _ChatBubbleState extends State<ChatBubble> {
),
IconButton(
onPressed: () {
showDialog(context: context, builder: (context) {
return AlertDialog(
showDialog(context: context, builder: (context) => AlertDialog(
contentPadding: const EdgeInsets.all(15),
titlePadding: const EdgeInsets.only(left: 6, top: 15),
title: Row(
@ -278,8 +275,7 @@ class _ChatBubbleState extends State<ChatBubble> {
],
),
),
);
});
));
},
style: IconButton.styleFrom(
padding: EdgeInsets.zero,
@ -350,8 +346,7 @@ class _ChatBubbleState extends State<ChatBubble> {
if(message.file == null) return;
if(downloadProgress > 0) {
showDialog(context: context, builder: (context) {
return AlertDialog(
showDialog(context: context, builder: (context) => AlertDialog(
title: const Text('Download abbrechen?'),
content: const Text('Möchtest du den Download abbrechen?'),
actions: [
@ -369,8 +364,7 @@ class _ChatBubbleState extends State<ChatBubble> {
});
}, child: const Text('Ja, Abbrechen'))
],
);
});
));
return;
}
@ -388,11 +382,9 @@ class _ChatBubbleState extends State<ChatBubble> {
});
if(result.type != ResultType.done) {
showDialog(context: context, builder: (context) {
return AlertDialog(
showDialog(context: context, builder: (context) => AlertDialog(
content: Text(result.message),
);
});
));
}
});
},
@ -408,7 +400,7 @@ class _ChatBubbleState extends State<ChatBubble> {
alignment: widget.isSender ? WrapAlignment.end : WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.start,
children: widget.bubbleData.reactions?.entries.map<Widget>((e) {
bool hasSelfReacted = widget.bubbleData.reactionsSelf?.contains(e.key) ?? false;
var hasSelfReacted = widget.bubbleData.reactionsSelf?.contains(e.key) ?? false;
return Container(
margin: const EdgeInsets.only(right: 2.5, left: 2.5),
child: ActionChip(

View File

@ -37,8 +37,7 @@ class ChatMessage {
}
return CachedNetworkImage(
errorWidget: (context, url, error) {
return Padding(padding: const EdgeInsets.only(top: 10), child: Row(
errorWidget: (context, url, error) => Padding(padding: const EdgeInsets.only(top: 10), child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
@ -47,12 +46,9 @@ class ChatMessage {
Flexible(child: Text(file!.name, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.bold))),
const SizedBox(width: 10),
],
));
},
)),
alignment: Alignment.center,
placeholder: (context, url) {
return const Padding(padding: EdgeInsets.all(10), child: CircularProgressIndicator());
},
placeholder: (context, url) => const Padding(padding: EdgeInsets.all(10), child: CircularProgressIndicator()),
fadeInDuration: Duration.zero,
fadeOutDuration: Duration.zero,
errorListener: (value) {},
@ -60,7 +56,7 @@ class ChatMessage {
);
}
void onOpen(LinkableElement link) async {
Future<void> onOpen(LinkableElement link) async {
if(await canLaunchUrlString(link.url)) {
await launchUrlString(link.url);
}

View File

@ -34,15 +34,15 @@ class _ChatTextfieldState extends State<ChatTextfield> {
Provider.of<ChatProps>(context, listen: false).run();
}
void mediaUpload(String? path) async {
Future<void> mediaUpload(String? path) async {
context.loaderOverlay.hide();
if(path == null) {
return;
}
String filename = "${path.split("/").last.split(".").first}-${const Uuid().v4()}.${path.split(".").last}";
String shareFolder = 'MarianumMobile';
var filename = "${path.split("/").last.split(".").first}-${const Uuid().v4()}.${path.split(".").last}";
var shareFolder = 'MarianumMobile';
WebdavApi.webdav.then((webdav) {
webdav.mkcol(PathUri.parse('/$shareFolder'));
});
@ -91,8 +91,7 @@ class _ChatTextfieldState extends State<ChatTextfield> {
children: <Widget>[
GestureDetector(
onTap: (){
showDialog(context: context, builder: (context) {
return SimpleDialog(
showDialog(context: context, builder: (context) => SimpleDialog(
children: [
ListTile(
leading: const Icon(Icons.file_open),
@ -118,8 +117,7 @@ class _ChatTextfieldState extends State<ChatTextfield> {
),
),
],
);
});
));
},
child: Material(
elevation: 5,

View File

@ -40,7 +40,7 @@ class _ChatTileState extends State<ChatTile> {
username = value.getString('username')!
});
bool isGroup = widget.data.type != GetRoomResponseObjectConversationType.oneToOne;
var isGroup = widget.data.type != GetRoomResponseObjectConversationType.oneToOne;
circleAvatar = UserAvatar(id: isGroup ? widget.data.token : widget.data.name, isGroup: isGroup);
}
@ -56,10 +56,7 @@ class _ChatTileState extends State<ChatTile> {
@override
Widget build(BuildContext context) {
return Consumer<ChatProps>(builder: (context, chatData, child) {
return ListTile(
Widget build(BuildContext context) => Consumer<ChatProps>(builder: (context, chatData, child) => ListTile(
style: ListTileStyle.list,
tileColor: chatData.currentToken() == widget.data.token && TalkNavigator.isSecondaryVisible(context)
? Theme.of(context).primaryColor.withAlpha(100)
@ -120,7 +117,7 @@ class _ChatTileState extends State<ChatTile> {
),
onTap: () async {
setCurrentAsRead();
ChatView view = ChatView(room: widget.data, selfId: username, avatar: circleAvatar);
var view = ChatView(room: widget.data, selfId: username, avatar: circleAvatar);
TalkNavigator.pushSplitView(context, view, overrideToSingleSubScreen: true);
Provider.of<ChatProps>(context, listen: false).setQueryToken(widget.data.token);
},
@ -185,7 +182,5 @@ class _ChatTileState extends State<ChatTile> {
],
));
},
);
});
}
));
}

View File

@ -6,8 +6,7 @@ class SplitViewPlaceholder extends StatelessWidget {
const SplitViewPlaceholder({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
@ -25,5 +24,4 @@ class SplitViewPlaceholder extends StatelessWidget {
),
)
);
}
}

View File

@ -11,8 +11,7 @@ class JoinChat extends SearchDelegate<String> {
CancelableOperation<AutocompleteResponse>? future;
@override
List<Widget>? buildActions(BuildContext context) {
return [
List<Widget>? buildActions(BuildContext context) => [
if(future != null && query.isNotEmpty) FutureBuilder(
future: future!.value,
builder: (context, snapshot) {
@ -35,12 +34,9 @@ class JoinChat extends SearchDelegate<String> {
),
if(query.isNotEmpty) IconButton(onPressed: () => query = '', icon: const Icon(Icons.delete)),
];
}
@override
Widget? buildLeading(BuildContext context) {
return null;
}
Widget? buildLeading(BuildContext context) => null;
@override
Widget buildResults(BuildContext context) {
@ -61,8 +57,8 @@ class JoinChat extends SearchDelegate<String> {
return ListView.builder(
itemCount: snapshot.data!.data.length,
itemBuilder: (context, index) {
AutocompleteResponseObject object = snapshot.data!.data[index];
CircleAvatar circleAvatar = CircleAvatar(
var object = snapshot.data!.data[index];
var circleAvatar = CircleAvatar(
foregroundImage: Image.network('https://${EndpointData().nextcloud().full()}/avatar/${object.id}/128').image,
backgroundColor: Theme.of(context).primaryColor,
foregroundColor: Colors.white,
@ -89,8 +85,6 @@ class JoinChat extends SearchDelegate<String> {
}
@override
Widget buildSuggestions(BuildContext context) {
return buildResults(context);
}
Widget buildSuggestions(BuildContext context) => buildResults(context);
}

View File

@ -30,8 +30,7 @@ class _MessageReactionsState extends State<MessageReactions> {
}
@override
Widget build(BuildContext context) {
return Scaffold(
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Reaktionen'),
),
@ -42,8 +41,7 @@ class _MessageReactionsState extends State<MessageReactions> {
if(snapshot.data == null) return const PlaceholderView(icon: Icons.search_off_outlined, text: 'Keine Reaktionen gefunden!');
return ListView(
children: [
...snapshot.data!.data.entries.map<Widget>((entry) {
return ExpansionTile(
...snapshot.data!.data.entries.map<Widget>((entry) => ExpansionTile(
textColor: Theme.of(context).colorScheme.onSurface,
collapsedTextColor: Theme.of(context).colorScheme.onSurface,
iconColor: Theme.of(context).colorScheme.onSurface,
@ -53,7 +51,7 @@ class _MessageReactionsState extends State<MessageReactions> {
leading: CenteredLeading(Text(entry.key)),
title: Text('${entry.value.length} mal reagiert'),
children: entry.value.map((e) {
bool isSelf = AccountData().getUsername() == e.actorId;
var isSelf = AccountData().getUsername() == e.actorId;
return ListTile(
leading: UserAvatar(id: e.actorId, isGroup: false),
title: Text(e.actorDisplayName),
@ -71,12 +69,10 @@ class _MessageReactionsState extends State<MessageReactions> {
),
);
}).toList(),
);
})
))
],
);
},
),
);
}
}

View File

@ -9,16 +9,12 @@ class SearchChat extends SearchDelegate {
SearchChat(this.chats);
@override
List<Widget>? buildActions(BuildContext context) {
return [
List<Widget>? buildActions(BuildContext context) => [
if(query.isNotEmpty) IconButton(onPressed: () => query = '', icon: const Icon(Icons.delete)),
];
}
@override
Widget? buildLeading(BuildContext context) {
return null;
}
Widget? buildLeading(BuildContext context) => null;
@override
Widget buildResults(BuildContext context) {
@ -35,7 +31,5 @@ class SearchChat extends SearchDelegate {
}
@override
Widget buildSuggestions(BuildContext context) {
return buildResults(context);
}
Widget buildSuggestions(BuildContext context) => buildResults(context);
}

View File

@ -9,7 +9,7 @@ class TalkNavigator {
static void pushSplitView(BuildContext context, Widget view, {bool overrideToSingleSubScreen = false}) {
if(isSecondaryVisible(context)) {
SplitViewState splitView = SplitView.of(context);
var splitView = SplitView.of(context);
overrideToSingleSubScreen ? splitView.setSecondary(view) : splitView.push(view);
} else {
pushScreen(context, screen: view, withNavBar: false);

Some files were not shown because too many files have changed in this diff Show More