diff --git a/.devcontainer.json b/.devcontainer.json new file mode 100644 index 000000000..a948d7911 --- /dev/null +++ b/.devcontainer.json @@ -0,0 +1,4 @@ +{ + "image": "cirrusci/flutter:beta", + "forwardPorts": [ 5000 ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json index 5539c9613..4394eabe7 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -8,13 +8,13 @@ "name": "dev-okuna-app", "request": "launch", "type": "dart", - "args": ["--flavor", "development"] + "args": ["--flavor", "development", "--no-sound-null-safety"] }, { "name": "prod-okuna-app", "request": "launch", "type": "dart", - "args": ["--flavor", "production"] + "args": ["--flavor", "production", "--no-sound-null-safety"] } ] } diff --git a/android/app/build.gradle b/android/app/build.gradle index 269aa3ad2..86724d3ce 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -106,5 +106,4 @@ dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0' - implementation 'com.onesignal:OneSignal:[3.11.2, 3.99.99]' -} \ No newline at end of file +} diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar old mode 100644 new mode 100755 diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index 86eb11d88..2210ceb17 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip \ No newline at end of file +distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-all.zip diff --git a/bin/split_locales.dart b/bin/split_locales.dart index dde8b85c6..8778620f0 100644 --- a/bin/split_locales.dart +++ b/bin/split_locales.dart @@ -18,7 +18,7 @@ void main() { translationStrings[mainKey] = {}; } - translationStrings[mainKey][translationKey] = json[key]; + translationStrings[mainKey]![translationKey] = json[key]; if (!mainKey.startsWith('@') && !mainKeys.contains(mainKey)) { mainKeys.add(mainKey); @@ -30,9 +30,9 @@ void main() { var output = {}; var current = translationStrings[mainKey]; - current.keys.forEach((key) { + current?.keys.forEach((key) { output[key] = current[key]; - output['@$key'] = translationStrings['@$mainKey'][key]; + output['@$key'] = translationStrings['@$mainKey']![key]; }); var str = jsonEncoder.convert(output); diff --git a/ios/Podfile b/ios/Podfile index 8c80f35d9..f255b7759 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -41,8 +41,7 @@ end install! 'cocoapods', :deterministic_uuids => false target 'OneSignalNotificationServiceExtension' do - pod 'OneSignal', '>= 2.9.5', '< 3.0' - use_frameworks! + pod 'OneSignalXCFramework', '>= 3.4.3', '< 4.0' end post_install do |installer| @@ -72,4 +71,3 @@ config.name == "Debug-development" end end end - diff --git a/lib/delegates/es_es_localizations_delegate.dart b/lib/delegates/es_es_localizations_delegate.dart index a70b17b6e..7c5b07b0c 100644 --- a/lib/delegates/es_es_localizations_delegate.dart +++ b/lib/delegates/es_es_localizations_delegate.dart @@ -9,18 +9,24 @@ class MaterialLocalizationEsES extends MaterialLocalizationEs { const MaterialLocalizationEsES({ String localeName = 'es-ES', - @required intl.DateFormat fullYearFormat, - @required intl.DateFormat mediumDateFormat, - @required intl.DateFormat longDateFormat, - @required intl.DateFormat yearMonthFormat, - @required intl.NumberFormat decimalFormat, - @required intl.NumberFormat twoDigitZeroPaddedFormat, + required intl.DateFormat fullYearFormat, + required intl.DateFormat shortDateFormat, + required intl.DateFormat mediumDateFormat, + required intl.DateFormat longDateFormat, + required intl.DateFormat compactDateFormat, + required intl.DateFormat yearMonthFormat, + required intl.DateFormat shortMonthDayFormat, + required intl.NumberFormat decimalFormat, + required intl.NumberFormat twoDigitZeroPaddedFormat, }) : super( localeName: localeName, fullYearFormat: fullYearFormat, + shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, + compactDateFormat: compactDateFormat, yearMonthFormat: yearMonthFormat, + shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat, ); @@ -37,23 +43,32 @@ class MaterialLocalizationEsESDelegate extends LocalizationsDelegate load(Locale locale) { intl.DateFormat fullYearFormat; + intl.DateFormat shortDateFormat; intl.DateFormat mediumDateFormat; intl.DateFormat longDateFormat; + intl.DateFormat compactDateFormat; intl.DateFormat yearMonthFormat; + intl.DateFormat shortMonthDayFormat; intl.NumberFormat decimalFormat; intl.NumberFormat twoDigitZeroPaddedFormat; decimalFormat = intl.NumberFormat.decimalPattern(locale.languageCode); twoDigitZeroPaddedFormat = intl.NumberFormat('00', locale.languageCode); fullYearFormat = intl.DateFormat.y(locale.languageCode); + shortDateFormat = intl.DateFormat.MEd(locale.languageCode); mediumDateFormat = intl.DateFormat.MMMEd(locale.languageCode); longDateFormat = intl.DateFormat.yMMMMEEEEd(locale.languageCode); + compactDateFormat = intl.DateFormat.MEd(locale.languageCode); yearMonthFormat = intl.DateFormat.yMMMM(locale.languageCode); + shortMonthDayFormat = intl.DateFormat.Md(locale.languageCode); return SynchronousFuture(MaterialLocalizationEsES( fullYearFormat: fullYearFormat, + shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, + compactDateFormat: compactDateFormat, yearMonthFormat: yearMonthFormat, + shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat )); @@ -66,14 +81,14 @@ class CupertinoLocalizationEsES extends CupertinoLocalizationEs { const CupertinoLocalizationEsES({ String localeName = 'es-ES', - @required intl.DateFormat fullYearFormat, - @required intl.DateFormat dayFormat, - @required intl.DateFormat mediumDateFormat, - @required intl.DateFormat singleDigitHourFormat, - @required intl.DateFormat singleDigitMinuteFormat, - @required intl.DateFormat doubleDigitMinuteFormat, - @required intl.DateFormat singleDigitSecondFormat, - @required intl.NumberFormat decimalFormat, + required intl.DateFormat fullYearFormat, + required intl.DateFormat dayFormat, + required intl.DateFormat mediumDateFormat, + required intl.DateFormat singleDigitHourFormat, + required intl.DateFormat singleDigitMinuteFormat, + required intl.DateFormat doubleDigitMinuteFormat, + required intl.DateFormat singleDigitSecondFormat, + required intl.NumberFormat decimalFormat, }) : super( localeName: localeName, fullYearFormat: fullYearFormat, @@ -131,4 +146,4 @@ class CupertinoLocalizationEsESDelegate extends LocalizationsDelegate false; -} \ No newline at end of file +} diff --git a/lib/delegates/pt_br_localizations_delegate.dart b/lib/delegates/pt_br_localizations_delegate.dart index 9d1bdf844..7680b233d 100644 --- a/lib/delegates/pt_br_localizations_delegate.dart +++ b/lib/delegates/pt_br_localizations_delegate.dart @@ -9,18 +9,24 @@ class MaterialLocalizationPtBR extends MaterialLocalizationPt { const MaterialLocalizationPtBR({ String localeName = 'pt-BR', - @required intl.DateFormat fullYearFormat, - @required intl.DateFormat mediumDateFormat, - @required intl.DateFormat longDateFormat, - @required intl.DateFormat yearMonthFormat, - @required intl.NumberFormat decimalFormat, - @required intl.NumberFormat twoDigitZeroPaddedFormat, + required intl.DateFormat fullYearFormat, + required intl.DateFormat shortDateFormat, + required intl.DateFormat mediumDateFormat, + required intl.DateFormat longDateFormat, + required intl.DateFormat compactDateFormat, + required intl.DateFormat yearMonthFormat, + required intl.DateFormat shortMonthDayFormat, + required intl.NumberFormat decimalFormat, + required intl.NumberFormat twoDigitZeroPaddedFormat, }) : super( localeName: localeName, fullYearFormat: fullYearFormat, + shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, + compactDateFormat: compactDateFormat, yearMonthFormat: yearMonthFormat, + shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat, ); @@ -37,23 +43,32 @@ class MaterialLocalizationPtBRDelegate extends LocalizationsDelegate load(Locale locale) { intl.DateFormat fullYearFormat; + intl.DateFormat shortDateFormat; intl.DateFormat mediumDateFormat; intl.DateFormat longDateFormat; + intl.DateFormat compactDateFormat; intl.DateFormat yearMonthFormat; + intl.DateFormat shortMonthDayFormat; intl.NumberFormat decimalFormat; intl.NumberFormat twoDigitZeroPaddedFormat; decimalFormat = intl.NumberFormat.decimalPattern(locale.languageCode); twoDigitZeroPaddedFormat = intl.NumberFormat('00', locale.languageCode); fullYearFormat = intl.DateFormat.y(locale.languageCode); + shortDateFormat = intl.DateFormat.MEd(locale.languageCode); mediumDateFormat = intl.DateFormat.MMMEd(locale.languageCode); longDateFormat = intl.DateFormat.yMMMMEEEEd(locale.languageCode); + compactDateFormat = intl.DateFormat.MEd(locale.languageCode); yearMonthFormat = intl.DateFormat.yMMMM(locale.languageCode); + shortMonthDayFormat = intl.DateFormat.Md(locale.languageCode); return SynchronousFuture(MaterialLocalizationPtBR( fullYearFormat: fullYearFormat, + shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, + compactDateFormat: compactDateFormat, yearMonthFormat: yearMonthFormat, + shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat )); @@ -66,14 +81,14 @@ class CupertinoLocalizationPtBR extends CupertinoLocalizationPt { const CupertinoLocalizationPtBR({ String localeName = 'pt-BR', - @required intl.DateFormat fullYearFormat, - @required intl.DateFormat dayFormat, - @required intl.DateFormat mediumDateFormat, - @required intl.DateFormat singleDigitHourFormat, - @required intl.DateFormat singleDigitMinuteFormat, - @required intl.DateFormat doubleDigitMinuteFormat, - @required intl.DateFormat singleDigitSecondFormat, - @required intl.NumberFormat decimalFormat, + required intl.DateFormat fullYearFormat, + required intl.DateFormat dayFormat, + required intl.DateFormat mediumDateFormat, + required intl.DateFormat singleDigitHourFormat, + required intl.DateFormat singleDigitMinuteFormat, + required intl.DateFormat doubleDigitMinuteFormat, + required intl.DateFormat singleDigitSecondFormat, + required intl.NumberFormat decimalFormat, }) : super( localeName: localeName, fullYearFormat: fullYearFormat, @@ -130,4 +145,4 @@ class CupertinoLocalizationPtBRDelegate extends LocalizationsDelegate false; -} \ No newline at end of file +} diff --git a/lib/delegates/sv_se_localizations_delegate.dart b/lib/delegates/sv_se_localizations_delegate.dart index fdc0eecf7..70e2a9054 100644 --- a/lib/delegates/sv_se_localizations_delegate.dart +++ b/lib/delegates/sv_se_localizations_delegate.dart @@ -9,18 +9,24 @@ class MaterialLocalizationSvSE extends MaterialLocalizationSv { const MaterialLocalizationSvSE({ String localeName = 'sv-SE', - @required intl.DateFormat fullYearFormat, - @required intl.DateFormat mediumDateFormat, - @required intl.DateFormat longDateFormat, - @required intl.DateFormat yearMonthFormat, - @required intl.NumberFormat decimalFormat, - @required intl.NumberFormat twoDigitZeroPaddedFormat, + required intl.DateFormat fullYearFormat, + required intl.DateFormat shortDateFormat, + required intl.DateFormat mediumDateFormat, + required intl.DateFormat longDateFormat, + required intl.DateFormat compactDateFormat, + required intl.DateFormat yearMonthFormat, + required intl.DateFormat shortMonthDayFormat, + required intl.NumberFormat decimalFormat, + required intl.NumberFormat twoDigitZeroPaddedFormat, }) : super( localeName: localeName, fullYearFormat: fullYearFormat, + shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, + compactDateFormat: compactDateFormat, yearMonthFormat: yearMonthFormat, + shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat, ); @@ -37,23 +43,32 @@ class MaterialLocalizationSvSEDelegate extends LocalizationsDelegate load(Locale locale) { intl.DateFormat fullYearFormat; + intl.DateFormat shortDateFormat; intl.DateFormat mediumDateFormat; intl.DateFormat longDateFormat; + intl.DateFormat compactDateFormat; intl.DateFormat yearMonthFormat; + intl.DateFormat shortMonthDayFormat; intl.NumberFormat decimalFormat; intl.NumberFormat twoDigitZeroPaddedFormat; decimalFormat = intl.NumberFormat.decimalPattern(locale.languageCode); twoDigitZeroPaddedFormat = intl.NumberFormat('00', locale.languageCode); fullYearFormat = intl.DateFormat.y(locale.languageCode); + shortDateFormat = intl.DateFormat.MEd(locale.languageCode); mediumDateFormat = intl.DateFormat.MMMEd(locale.languageCode); longDateFormat = intl.DateFormat.yMMMMEEEEd(locale.languageCode); + compactDateFormat = intl.DateFormat.MEd(locale.languageCode); yearMonthFormat = intl.DateFormat.yMMMM(locale.languageCode); + shortMonthDayFormat = intl.DateFormat.Md(locale.languageCode); return SynchronousFuture(MaterialLocalizationSvSE( fullYearFormat: fullYearFormat, + shortDateFormat: shortDateFormat, mediumDateFormat: mediumDateFormat, longDateFormat: longDateFormat, + compactDateFormat: compactDateFormat, yearMonthFormat: yearMonthFormat, + shortMonthDayFormat: shortMonthDayFormat, decimalFormat: decimalFormat, twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat )); @@ -66,14 +81,14 @@ class CupertinoLocalizationSvSE extends CupertinoLocalizationSv { const CupertinoLocalizationSvSE({ String localeName = 'sv-SE', - @required intl.DateFormat fullYearFormat, - @required intl.DateFormat dayFormat, - @required intl.DateFormat mediumDateFormat, - @required intl.DateFormat singleDigitHourFormat, - @required intl.DateFormat singleDigitMinuteFormat, - @required intl.DateFormat doubleDigitMinuteFormat, - @required intl.DateFormat singleDigitSecondFormat, - @required intl.NumberFormat decimalFormat, + required intl.DateFormat fullYearFormat, + required intl.DateFormat dayFormat, + required intl.DateFormat mediumDateFormat, + required intl.DateFormat singleDigitHourFormat, + required intl.DateFormat singleDigitMinuteFormat, + required intl.DateFormat doubleDigitMinuteFormat, + required intl.DateFormat singleDigitSecondFormat, + required intl.NumberFormat decimalFormat, }) : super( localeName: localeName, fullYearFormat: fullYearFormat, @@ -130,4 +145,4 @@ class CupertinoLocalizationSvSEDelegate extends LocalizationsDelegate false; -} \ No newline at end of file +} diff --git a/lib/libs/pretty_count.dart b/lib/libs/pretty_count.dart index 4600e1278..b2750ba92 100644 --- a/lib/libs/pretty_count.dart +++ b/lib/libs/pretty_count.dart @@ -1,8 +1,8 @@ import 'package:Okuna/services/localization.dart'; String getPrettyCount(int value, LocalizationService localizationService) { - String postfix; - double finalValue; + late String postfix; + late double finalValue; if (value < 0) { throw 'Invalid value'; diff --git a/lib/locale/messages_all.dart b/lib/locale/messages_all.dart index 7e6e59081..27bc40626 100644 --- a/lib/locale/messages_all.dart +++ b/lib/locale/messages_all.dart @@ -42,7 +42,7 @@ Map _deferredLibraries = { 'tr': () => new Future.value(null), }; -MessageLookupByLibrary _findExact(String localeName) { +MessageLookupByLibrary? _findExact(String localeName) { switch (localeName) { case 'da': return messages_da.messages; @@ -95,7 +95,7 @@ bool _messagesExistFor(String locale) { } } -MessageLookupByLibrary _findGeneratedMessagesFor(String locale) { +MessageLookupByLibrary? _findGeneratedMessagesFor(String locale) { var actualLocale = Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null); if (actualLocale == null) return null; diff --git a/lib/main.dart b/lib/main.dart index 234bdaafe..e8659b933 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -44,18 +44,18 @@ class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); - static void setLocale(BuildContext context, Locale newLocale) { - _MyAppState state = context.findAncestorStateOfType<_MyAppState>(); + static void setLocale(BuildContext context, Locale? newLocale) { + _MyAppState? state = context.findAncestorStateOfType<_MyAppState>(); - state.setState(() { - state.locale = newLocale; + state?.setState(() { + state.locale = newLocale ?? Locale('en', 'US'); }); } } class _MyAppState extends State { - Locale locale; - bool _needsBootstrap; + Locale? locale; + late bool _needsBootstrap; static const MAX_NETWORK_IMAGE_CACHE_MB = 200; static const MAX_NETWORK_IMAGE_CACHE_ENTRIES = 1000; @@ -220,9 +220,9 @@ class _MyAppState extends State { }, '/waitlist/subscribe_done_step': (BuildContext context) { bootstrapOpenbookProviderInContext(context); - WaitlistSubscribeArguments args = - ModalRoute.of(context).settings.arguments; - return OBWaitlistSubscribeDoneStep(count: args.count); + WaitlistSubscribeArguments? args = + ModalRoute.of(context)?.settings.arguments as WaitlistSubscribeArguments?; + return OBWaitlistSubscribeDoneStep(count: args?.count ?? 0); } }), ), @@ -232,7 +232,7 @@ class _MyAppState extends State { void bootstrapOpenbookProviderInContext(BuildContext context) { var openbookProvider = OpenbookProvider.of(context); var localizationService = LocalizationService.of(context); - if (this.locale.languageCode != + if (this.locale?.languageCode != localizationService.getLocale().languageCode) { Future.delayed(Duration(milliseconds: 0), () { MyApp.setLocale(context, this.locale); @@ -260,11 +260,11 @@ Future main() async { return; } - SentryClient sentryClient = - app.openbookProviderKey.currentState.sentryClient; + SentryClient? sentryClient = + app.openbookProviderKey.currentState?.sentryClient; try { - sentryClient.captureException( + sentryClient?.captureException( error, stackTrace: stackTrace, ); diff --git a/lib/models/badge.dart b/lib/models/badge.dart index 80f28e882..9b6161bc5 100644 --- a/lib/models/badge.dart +++ b/lib/models/badge.dart @@ -1,6 +1,6 @@ class Badge { - final BadgeKeyword keyword; - final String keywordDescription; + final BadgeKeyword? keyword; + final String? keywordDescription; Badge( {this.keyword, @@ -8,8 +8,6 @@ class Badge { }); factory Badge.fromJson(Map parsedJson) { - if (parsedJson == null) return null; - return Badge( keyword: BadgeKeyword.parse(parsedJson['keyword']), keywordDescription: parsedJson['keyword_description'] @@ -23,11 +21,11 @@ class Badge { }; } - BadgeKeyword getKeyword() { + BadgeKeyword? getKeyword() { return this.keyword; } - String getKeywordDescription() { + String? getKeywordDescription() { return this.keywordDescription; } } @@ -61,10 +59,10 @@ class BadgeKeyword { static values() => _values; - static BadgeKeyword parse(String string) { + static BadgeKeyword? parse(String? string) { if (string == null) return null; - BadgeKeyword badgeKeyword; + BadgeKeyword? badgeKeyword; for (var keyword in _values) { if (string == keyword.code) { @@ -73,10 +71,10 @@ class BadgeKeyword { } } - if (BadgeKeyword == null) { + if (badgeKeyword == null) { print('Unsupported badge keyword'); } return badgeKeyword; } -} \ No newline at end of file +} diff --git a/lib/models/badges_list.dart b/lib/models/badges_list.dart index 8184df8d4..201d3bfca 100644 --- a/lib/models/badges_list.dart +++ b/lib/models/badges_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/badge.dart'; class BadgesList { - final List badges; + final List? badges; BadgesList({ this.badges, diff --git a/lib/models/categories_list.dart b/lib/models/categories_list.dart index 6017d329f..17e6c9273 100644 --- a/lib/models/categories_list.dart +++ b/lib/models/categories_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/category.dart'; class CategoriesList { - final List categories; + final List? categories; CategoriesList({ this.categories, diff --git a/lib/models/category.dart b/lib/models/category.dart index 75d953902..e98022692 100644 --- a/lib/models/category.dart +++ b/lib/models/category.dart @@ -3,13 +3,13 @@ import 'package:Okuna/models/user.dart'; import 'package:dcache/dcache.dart'; class Category extends UpdatableModel { - final int id; - final User creator; - String name; - String title; - String description; - String avatar; - String color; + final int? id; + final User? creator; + String? name; + String? title; + String? description; + String? avatar; + String? color; Category({ this.id, @@ -24,7 +24,6 @@ class Category extends UpdatableModel { static final factory = CategoryFactory(); factory Category.fromJSON(Map json) { - if (json == null) return null; return factory.fromJson(json); } @@ -66,7 +65,7 @@ class Category extends UpdatableModel { class CategoryFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 20)); @override @@ -82,7 +81,7 @@ class CategoryFactory extends UpdatableModelFactory { ); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } diff --git a/lib/models/circle.dart b/lib/models/circle.dart index d26c15b2f..b568c2e49 100644 --- a/lib/models/circle.dart +++ b/lib/models/circle.dart @@ -4,12 +4,12 @@ import 'package:Okuna/models/users_list.dart'; import 'package:dcache/dcache.dart'; class Circle extends UpdatableModel { - final int id; - final User creator; - String name; - String color; - int usersCount; - UsersList users; + final int? id; + final User? creator; + String? name; + String? color; + int? usersCount; + UsersList? users; Circle({ this.id, @@ -23,7 +23,6 @@ class Circle extends UpdatableModel { static final factory = CircleFactory(); factory Circle.fromJSON(Map json) { - if (json == null) return null; return factory.fromJson(json); } @@ -34,7 +33,7 @@ class Circle extends UpdatableModel { 'name': name, 'color': color, 'users_count': usersCount, - 'users': users?.users?.map((User user) => user.toJson())?.toList() + 'users': users?.users?.map((User user) => user.toJson()).toList() }; } @@ -55,13 +54,13 @@ class Circle extends UpdatableModel { } bool hasUsers() { - return users != null && users.users.length > 0; + return users != null && users!.users!.length > 0; } } class CircleFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 20)); @override @@ -76,12 +75,12 @@ class CircleFactory extends UpdatableModelFactory { ); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } - UsersList parseUsers(List usersData) { + UsersList? parseUsers(List? usersData) { if (usersData == null) return null; return UsersList.fromJson(usersData); } diff --git a/lib/models/circles_list.dart b/lib/models/circles_list.dart index fe4b7d7df..c431e89f9 100644 --- a/lib/models/circles_list.dart +++ b/lib/models/circles_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/circle.dart'; class CirclesList { - final List circles; + final List? circles; CirclesList({ this.circles, diff --git a/lib/models/communities_list.dart b/lib/models/communities_list.dart index 654134921..10afaea9e 100644 --- a/lib/models/communities_list.dart +++ b/lib/models/communities_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/community.dart'; class CommunitiesList { - final List communities; + final List? communities; CommunitiesList({ this.communities, diff --git a/lib/models/community.dart b/lib/models/community.dart index 988929bd8..9553a5c7c 100644 --- a/lib/models/community.dart +++ b/lib/models/community.dart @@ -43,45 +43,45 @@ class Community extends UpdatableModel { factory.clearCache(); } - final int id; - final User creator; - String name; - String title; - String description; - String rules; - String color; - String avatar; - String cover; - String userAdjective; - String usersAdjective; - int membersCount; - int postsCount; - int pendingModeratedObjectsCount; - - CommunityType type; + final int? id; + final User? creator; + String? name; + String? title; + String? description; + String? rules; + String? color; + String? avatar; + String? cover; + String? userAdjective; + String? usersAdjective; + int? membersCount; + int? postsCount; + int? pendingModeratedObjectsCount; + + CommunityType? type; // Whether the user has been invited to the community - bool isInvited; + bool? isInvited; // Whether the user has subscribed to the community - bool areNewPostNotificationsEnabled; + bool? areNewPostNotificationsEnabled; // Whether the user is the creator of the community - bool isCreator; + bool? isCreator; - bool isFavorite; + bool? isFavorite; - bool isReported; + bool? isReported; - bool invitesEnabled; + bool? invitesEnabled; - CategoriesList categories; + CategoriesList? categories; - UsersList moderators; + UsersList? moderators; - UsersList administrators; + UsersList? administrators; - CommunityMembershipList memberships; + CommunityMembershipList? memberships; Community( {this.id, @@ -131,25 +131,25 @@ class Community extends UpdatableModel { } bool isAdministrator(User user) { - CommunityMembership membership = getMembershipForUser(user); + CommunityMembership? membership = getMembershipForUser(user); if (membership == null) return false; - return membership.isAdministrator; + return membership.isAdministrator ?? false; } bool isModerator(User user) { - CommunityMembership membership = getMembershipForUser(user); + CommunityMembership? membership = getMembershipForUser(user); if (membership == null) return false; - return membership.isModerator; + return membership.isModerator ?? false; } bool isMember(User user) { return getMembershipForUser(user) != null; } - CommunityMembership getMembershipForUser(User user) { + CommunityMembership? getMembershipForUser(User user) { if (memberships == null) return null; - int membershipIndex = memberships.communityMemberships + int membershipIndex = memberships!.communityMemberships! .indexWhere((CommunityMembership communityMembership) { return communityMembership.userId == user.id && communityMembership.communityId == this.id; @@ -157,13 +157,12 @@ class Community extends UpdatableModel { if (membershipIndex < 0) return null; - return memberships.communityMemberships[membershipIndex]; + return memberships!.communityMemberships![membershipIndex]; } static final factory = CommunityFactory(); factory Community.fromJSON(Map json) { - if (json == null) return null; return factory.fromJson(json); } @@ -186,12 +185,12 @@ class Community extends UpdatableModel { 'is_creator': isCreator, 'is_reported': isReported, 'moderators': - moderators?.users?.map((User user) => user.toJson())?.toList(), + moderators?.users?.map((User user) => user.toJson()).toList(), 'memberships': memberships?.communityMemberships ?.map((CommunityMembership membership) => membership.toJson()) - ?.toList(), + .toList(), 'administrators': - administrators?.users?.map((User user) => user.toJson())?.toList(), + administrators?.users?.map((User user) => user.toJson()).toList(), 'is_favorite': isFavorite, 'invites_enabled': invitesEnabled, 'members_count': membersCount, @@ -199,7 +198,7 @@ class Community extends UpdatableModel { 'pending_moderated_objects_count': pendingModeratedObjectsCount, 'categories': categories?.categories ?.map((Category category) => category.toJson()) - ?.toList() + .toList() }; } @@ -305,28 +304,28 @@ class Community extends UpdatableModel { void incrementMembersCount() { if (this.membersCount != null) { - this.membersCount += 1; + this.membersCount = this.membersCount! + 1; notifyUpdate(); } } void decrementMembersCount() { - if (this.membersCount != null && this.membersCount > 0) { - this.membersCount -= 1; + if (this.membersCount != null && this.membersCount! > 0) { + this.membersCount = this.membersCount! - 1; notifyUpdate(); } } void incrementPostsCount() { if (this.postsCount != null) { - this.postsCount += 1; + this.postsCount = this.postsCount! + 1; notifyUpdate(); } } void decrementPostsCount() { - if (this.postsCount != null && this.postsCount > 0) { - this.postsCount -= 1; + if (this.postsCount != null && this.postsCount! > 0) { + this.postsCount = this.postsCount! - 1; notifyUpdate(); } } @@ -339,7 +338,7 @@ class Community extends UpdatableModel { class CommunityFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 200)); @override @@ -373,27 +372,27 @@ class CommunityFactory extends UpdatableModelFactory { categories: parseCategories(json['categories'])); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } - UsersList parseUsers(List usersData) { + UsersList? parseUsers(List? usersData) { if (usersData == null) return null; return UsersList.fromJson(usersData); } - CommunityMembershipList parseMemberships(List membershipsData) { + CommunityMembershipList? parseMemberships(List? membershipsData) { if (membershipsData == null) return null; return CommunityMembershipList.fromJson(membershipsData); } - CategoriesList parseCategories(List categoriesData) { + CategoriesList? parseCategories(List? categoriesData) { if (categoriesData == null) return null; return CategoriesList.fromJson(categoriesData); } - CommunityType parseType(String strType) { + CommunityType? parseType(String? strType) { if (strType == null) return null; CommunityType type; @@ -408,14 +407,14 @@ class CommunityFactory extends UpdatableModelFactory { return type; } - String typeToString(CommunityType type) { + String typeToString(CommunityType? type) { switch (type) { case CommunityType.public: return 'P'; - break; case CommunityType.private: return 'T'; - break; + default: + return ''; } } } diff --git a/lib/models/community_invite.dart b/lib/models/community_invite.dart index 98fa3bc9f..a5dc4583b 100644 --- a/lib/models/community_invite.dart +++ b/lib/models/community_invite.dart @@ -2,14 +2,14 @@ import 'package:Okuna/models/community.dart'; import 'package:Okuna/models/user.dart'; class CommunityInvite { - final int id; - final int creatorId; - final int communityId; - final int invitedUserId; + final int? id; + final int? creatorId; + final int? communityId; + final int? invitedUserId; - User invitedUser; - User creator; - Community community; + User? invitedUser; + User? creator; + Community? community; CommunityInvite( {this.id, @@ -21,16 +21,15 @@ class CommunityInvite { this.creator}); factory CommunityInvite.fromJSON(Map parsedJson) { - assert(parsedJson != null); - User invitedUser; + User? invitedUser; if (parsedJson.containsKey('invited_user')) invitedUser = User.fromJson(parsedJson['invited_user']); - User creator; + User? creator; if (parsedJson.containsKey('creator')) creator = User.fromJson(parsedJson['creator']); - Community community; + Community? community; if (parsedJson.containsKey('community')) community = Community.fromJSON(parsedJson['community']); diff --git a/lib/models/community_invite_list.dart b/lib/models/community_invite_list.dart index 3ee7b9c43..cb9c7f14a 100644 --- a/lib/models/community_invite_list.dart +++ b/lib/models/community_invite_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/community_invite.dart'; class CommunityInviteList { - final List communityInvites; + final List? communityInvites; CommunityInviteList({ this.communityInvites, diff --git a/lib/models/community_membership.dart b/lib/models/community_membership.dart index c7e26be0c..bd6f9d9d1 100644 --- a/lib/models/community_membership.dart +++ b/lib/models/community_membership.dart @@ -1,9 +1,9 @@ class CommunityMembership { - final int id; - final int userId; - final int communityId; - bool isAdministrator; - bool isModerator; + final int? id; + final int? userId; + final int? communityId; + bool? isAdministrator; + bool? isModerator; CommunityMembership( {this.id, @@ -13,7 +13,6 @@ class CommunityMembership { this.isModerator}); factory CommunityMembership.fromJSON(Map parsedJson) { - if (parsedJson == null) return null; return CommunityMembership( id: parsedJson['id'], communityId: parsedJson['community_id'], diff --git a/lib/models/community_membership_list.dart b/lib/models/community_membership_list.dart index 172b53531..5fae49d54 100644 --- a/lib/models/community_membership_list.dart +++ b/lib/models/community_membership_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/community_membership.dart'; class CommunityMembershipList { - final List communityMemberships; + final List? communityMemberships; CommunityMembershipList({ this.communityMemberships, diff --git a/lib/models/connection.dart b/lib/models/connection.dart index bb2994c61..0da6ff493 100644 --- a/lib/models/connection.dart +++ b/lib/models/connection.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/user.dart'; class Connection { - final int id; - final User targetUser; + final int? id; + final User? targetUser; Connection({this.id, this.targetUser}); @@ -11,7 +11,7 @@ class Connection { id: json['id'], targetUser: _parseTargetUser(json['target_user'])); } - static User _parseTargetUser(Map targetUserData) { + static User? _parseTargetUser(Map? targetUserData) { if (targetUserData == null) return null; return User.fromJson(targetUserData); } diff --git a/lib/models/device.dart b/lib/models/device.dart index 5af779db3..b3ab5a821 100644 --- a/lib/models/device.dart +++ b/lib/models/device.dart @@ -5,12 +5,12 @@ import 'package:Okuna/models/users_list.dart'; import 'package:dcache/dcache.dart'; class Device extends UpdatableModel { - final int id; + final int? id; - User owner; - String uuid; - String name; - DateTime created; + User? owner; + String? uuid; + String? name; + DateTime? created; static final factory = DeviceFactory(); @@ -46,7 +46,7 @@ class Device extends UpdatableModel { class DeviceFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 20)); @override @@ -59,22 +59,22 @@ class DeviceFactory extends UpdatableModelFactory { uuid: json['uuid']); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } - UsersList parseUsers(List usersData) { + UsersList? parseUsers(List? usersData) { if (usersData == null) return null; return UsersList.fromJson(usersData); } - Emoji parseEmoji(Map emojiData) { + Emoji? parseEmoji(Map? emojiData) { if (emojiData == null) return null; return Emoji.fromJson(emojiData); } - DateTime parseCreated(String created) { + DateTime? parseCreated(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } diff --git a/lib/models/devices_list.dart b/lib/models/devices_list.dart index b5ba2259a..b03bb6b85 100644 --- a/lib/models/devices_list.dart +++ b/lib/models/devices_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/device.dart'; class DevicesList { - final List devices; + final List? devices; DevicesList({ this.devices, diff --git a/lib/models/emoji.dart b/lib/models/emoji.dart index 518f0c39e..2dfe4f25a 100644 --- a/lib/models/emoji.dart +++ b/lib/models/emoji.dart @@ -1,10 +1,10 @@ class Emoji { - final String keyword; - final int id; - final int order; - final DateTime created; - final String color; - final String image; + final String? keyword; + final int? id; + final int? order; + final DateTime? created; + final String? color; + final String? image; Emoji( {this.keyword, @@ -15,7 +15,7 @@ class Emoji { this.image}); factory Emoji.fromJson(Map parsedJson) { - DateTime created; + DateTime? created; if (parsedJson['created'] != null) { created = DateTime.parse(parsedJson['created']).toLocal(); } diff --git a/lib/models/emoji_group.dart b/lib/models/emoji_group.dart index 4b83cf701..62271685f 100644 --- a/lib/models/emoji_group.dart +++ b/lib/models/emoji_group.dart @@ -2,12 +2,12 @@ import 'package:Okuna/models/emoji.dart'; import 'package:Okuna/models/emoji_list.dart'; class EmojiGroup { - final String keyword; - final int id; - final int order; - final DateTime created; - final String color; - final EmojisList emojis; + final String? keyword; + final int? id; + final int? order; + final DateTime? created; + final String? color; + final EmojisList? emojis; EmojiGroup( {this.keyword, @@ -30,11 +30,11 @@ class EmojiGroup { emojis: emojis); } - List getEmojis() { - return emojis.emojis; + List? getEmojis() { + return emojis?.emojis; } - static DateTime _parseCreated(String created) { + static DateTime? _parseCreated(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } diff --git a/lib/models/emoji_group_list.dart b/lib/models/emoji_group_list.dart index 1bbdb57f3..95c52536a 100644 --- a/lib/models/emoji_group_list.dart +++ b/lib/models/emoji_group_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/emoji_group.dart'; class EmojiGroupList { - final List emojisGroups; + final List? emojisGroups; EmojiGroupList({ this.emojisGroups, diff --git a/lib/models/emoji_list.dart b/lib/models/emoji_list.dart index 2145dd1d0..1ecd3256a 100644 --- a/lib/models/emoji_list.dart +++ b/lib/models/emoji_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/emoji.dart'; class EmojisList { - final List emojis; + final List? emojis; EmojisList({ this.emojis, diff --git a/lib/models/follow.dart b/lib/models/follow.dart index 0317f602d..b9112c782 100644 --- a/lib/models/follow.dart +++ b/lib/models/follow.dart @@ -2,9 +2,9 @@ import 'package:Okuna/models/follows_list.dart'; import 'package:Okuna/models/user.dart'; class Follow { - final int id; - final FollowsList list; - final User followedUser; + final int? id; + final FollowsList? list; + final User? followedUser; Follow({this.id, this.list, this.followedUser}); @@ -14,7 +14,7 @@ class Follow { followedUser: _parseFollowedUser(json['followed_user'])); } - static User _parseFollowedUser(Map followedUserData) { + static User? _parseFollowedUser(Map? followedUserData) { if (followedUserData == null) return null; return User.fromJson(followedUserData); } diff --git a/lib/models/follow_request.dart b/lib/models/follow_request.dart index 74c05a7b2..7a56991c8 100644 --- a/lib/models/follow_request.dart +++ b/lib/models/follow_request.dart @@ -1,9 +1,9 @@ import 'package:Okuna/models/user.dart'; class FollowRequest { - final int id; - final User creator; - final User targetUser; + final int? id; + final User? creator; + final User? targetUser; FollowRequest({this.id, this.creator, this.targetUser}); @@ -15,7 +15,7 @@ class FollowRequest { ); } - static User _parseFollowRequestedUser(Map followRequestedUserData) { + static User? _parseFollowRequestedUser(Map? followRequestedUserData) { if (followRequestedUserData == null) return null; return User.fromJson(followRequestedUserData); } diff --git a/lib/models/follow_request_list.dart b/lib/models/follow_request_list.dart index 5596b8c70..bfb825f39 100644 --- a/lib/models/follow_request_list.dart +++ b/lib/models/follow_request_list.dart @@ -2,7 +2,7 @@ import 'follow_request.dart'; class FollowRequestList { - final List followRequests; + final List? followRequests; FollowRequestList({ this.followRequests, diff --git a/lib/models/follows_list.dart b/lib/models/follows_list.dart index f9049d019..3a17bdeb4 100644 --- a/lib/models/follows_list.dart +++ b/lib/models/follows_list.dart @@ -5,12 +5,12 @@ import 'package:Okuna/models/users_list.dart'; import 'package:dcache/dcache.dart'; class FollowsList extends UpdatableModel { - final int id; - final User creator; - UsersList users; - Emoji emoji; - String name; - int followsCount; + final int? id; + final User? creator; + UsersList? users; + Emoji? emoji; + String? name; + int? followsCount; static final factory = FollowsListFactory(); @@ -22,7 +22,7 @@ class FollowsList extends UpdatableModel { return { 'id': id, 'creator': creator?.toJson(), - 'users': users?.users.map((User user) => user.toJson()).toList(), + 'users': users?.users?.map((User user) => user.toJson()).toList(), 'emoji': emoji?.toJson(), 'name': name, 'follows_count': followsCount @@ -57,19 +57,19 @@ class FollowsList extends UpdatableModel { return this.users != null; } - String getEmojiImage() { - return emoji.image; + String? getEmojiImage() { + return emoji?.image; } String getPrettyFollowsCount() { String followsCountStr = followsCount.toString(); - return followsCountStr + (followsCount > 1 ? '' : ''); + return followsCountStr + (followsCount != null && followsCount! > 1 ? '' : ''); } } class FollowsListFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 20)); @override @@ -83,17 +83,17 @@ class FollowsListFactory extends UpdatableModelFactory { emoji: parseEmoji(json['emoji'])); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } - UsersList parseUsers(List usersData) { + UsersList? parseUsers(List? usersData) { if (usersData == null) return null; return UsersList.fromJson(usersData); } - Emoji parseEmoji(Map emojiData) { + Emoji? parseEmoji(Map? emojiData) { if(emojiData == null) return null; return Emoji.fromJson(emojiData); } diff --git a/lib/models/follows_lists_list.dart b/lib/models/follows_lists_list.dart index 4cb2864b5..799a21965 100644 --- a/lib/models/follows_lists_list.dart +++ b/lib/models/follows_lists_list.dart @@ -3,7 +3,7 @@ import 'package:Okuna/models/follows_list.dart'; // This f'ing NAME!!!!! class FollowsListsList { - final List lists; + final List? lists; FollowsListsList({ this.lists, diff --git a/lib/models/hashtag.dart b/lib/models/hashtag.dart index bf02b1a84..35fec26a8 100644 --- a/lib/models/hashtag.dart +++ b/lib/models/hashtag.dart @@ -3,14 +3,14 @@ import 'package:Okuna/models/updatable_model.dart'; import 'package:dcache/dcache.dart'; class Hashtag extends UpdatableModel { - final int id; - String name; - String image; - Emoji emoji; - String color; - String textColor; - int postsCount; - bool isReported; + final int? id; + String? name; + String? image; + Emoji? emoji; + String? color; + String? textColor; + int? postsCount; + bool? isReported; Hashtag({ this.id, @@ -26,7 +26,6 @@ class Hashtag extends UpdatableModel { static final factory = HashtagFactory(); factory Hashtag.fromJSON(Map json) { - if (json == null) return null; return factory.fromJson(json); } @@ -89,7 +88,7 @@ class Hashtag extends UpdatableModel { class HashtagFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 20)); @override @@ -105,7 +104,7 @@ class HashtagFactory extends UpdatableModelFactory { ); } - Emoji parseEmoji(emojiRawData) { + Emoji? parseEmoji(emojiRawData) { if (emojiRawData == null) return null; return Emoji.fromJson(emojiRawData); } diff --git a/lib/models/hashtags_list.dart b/lib/models/hashtags_list.dart index 27c6a7670..49cb8d6ef 100644 --- a/lib/models/hashtags_list.dart +++ b/lib/models/hashtags_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/hashtag.dart'; class HashtagsList { - final List hashtags; + final List? hashtags; HashtagsList({ this.hashtags, diff --git a/lib/models/language.dart b/lib/models/language.dart index 1e0a554f3..74c1aa8e9 100644 --- a/lib/models/language.dart +++ b/lib/models/language.dart @@ -1,7 +1,7 @@ class Language { - final String code; - final String name; - final int id; + final String? code; + final String? name; + final int? id; Language( {this.code, @@ -10,8 +10,6 @@ class Language { }); factory Language.fromJson(Map parsedJson) { - if (parsedJson == null) return null; - return Language( id: parsedJson['id'], code: parsedJson['code'], diff --git a/lib/models/language_list.dart b/lib/models/language_list.dart index 2c8beef80..ab927a986 100644 --- a/lib/models/language_list.dart +++ b/lib/models/language_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/language.dart'; class LanguagesList { - final List languages; + final List? languages; LanguagesList({ this.languages, diff --git a/lib/models/link_preview/link_preview.dart b/lib/models/link_preview/link_preview.dart index 6b11ddb63..aae7b4d91 100644 --- a/lib/models/link_preview/link_preview.dart +++ b/lib/models/link_preview/link_preview.dart @@ -2,21 +2,21 @@ import 'link_preview_image.dart'; class LinkPreview { - String url; - String domain; - DateTime lastUpdated; - DateTime nextUpdate; - String contentType; - String mimeType; - bool redirected; - String redirectionUrl; - List redirectionTrail; - String title; - String description; - String name; - bool trackersDetected; - LinkPreviewImage icon; - LinkPreviewImage image; + String? url; + String? domain; + DateTime? lastUpdated; + DateTime? nextUpdate; + String? contentType; + String? mimeType; + bool? redirected; + String? redirectionUrl; + List? redirectionTrail; + String? title; + String? description; + String? name; + bool? trackersDetected; + LinkPreviewImage? icon; + LinkPreviewImage? image; LinkPreview({ this.url, @@ -37,8 +37,6 @@ class LinkPreview { }); factory LinkPreview.fromJSON(Map json) { - if (json == null) return null; - return LinkPreview( url: json['url'], domain: json['domain'], @@ -48,7 +46,7 @@ class LinkPreview { mimeType: json['mimeType'], redirected: json['redirected'], redirectionUrl: json['redirectionUrl'], - redirectionTrail: json['redirectionTrail'], + redirectionTrail: json['redirectionTrail']?.cast(), title: json['title'], description: json['description'], name: json['name'], @@ -58,12 +56,12 @@ class LinkPreview { ); } - static LinkPreviewImage parsePreviewImage(Map previewImageData) { + static LinkPreviewImage? parsePreviewImage(Map? previewImageData) { if (previewImageData == null) return null; return LinkPreviewImage.fromJson(previewImageData); } - static DateTime parseDate(String created) { + static DateTime? parseDate(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } diff --git a/lib/models/link_preview/link_preview_image.dart b/lib/models/link_preview/link_preview_image.dart index 86d0e48e5..1f5e76ca3 100644 --- a/lib/models/link_preview/link_preview_image.dart +++ b/lib/models/link_preview/link_preview_image.dart @@ -1,7 +1,7 @@ class LinkPreviewImage { - final String url; - final int width; - final int height; + final String? url; + final int? width; + final int? height; LinkPreviewImage({ this.url, @@ -10,8 +10,6 @@ class LinkPreviewImage { }); factory LinkPreviewImage.fromJson(Map parsedJson) { - if (parsedJson == null) return null; - return LinkPreviewImage( url: parsedJson['url'], width: parsedJson['width'], diff --git a/lib/models/moderation/moderated_object.dart b/lib/models/moderation/moderated_object.dart index e73e6f6aa..3f7a34a0a 100644 --- a/lib/models/moderation/moderated_object.dart +++ b/lib/models/moderation/moderated_object.dart @@ -26,17 +26,17 @@ class ModeratedObject extends UpdatableModel { static String statusApproved = 'A'; static String statusRejected = 'R'; - final int id; - final Community community; + final int? id; + final Community? community; dynamic contentObject; - ModeratedObjectType type; - ModeratedObjectStatus status; - ModerationCategory category; + ModeratedObjectType? type; + ModeratedObjectStatus? status; + ModerationCategory? category; - String description; - bool verified; - int reportsCount; + String? description; + bool? verified; + int? reportsCount; ModeratedObject( {this.id, @@ -87,7 +87,7 @@ class ModeratedObject extends UpdatableModel { } bool isVerified() { - return verified; + return verified ?? false; } void setIsApproved() { @@ -106,15 +106,15 @@ class ModeratedObject extends UpdatableModel { class ModeratedObjectFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 120)); @override ModeratedObject makeFromJson(Map json) { - ModeratedObjectType type = parseType(json['object_type']); - ModeratedObjectStatus status = parseStatus(json['status']); - ModerationCategory category = parseModerationCategory(json['category']); - Community community = parseCommunity(json['community']); + ModeratedObjectType? type = parseType(json['object_type']); + ModeratedObjectStatus? status = parseStatus(json['status']); + ModerationCategory? category = parseModerationCategory(json['category']); + Community? community = parseCommunity(json['community']); return ModeratedObject( id: json['id'], @@ -129,20 +129,20 @@ class ModeratedObjectFactory extends UpdatableModelFactory { verified: json['verified']); } - Community parseCommunity(Map communityData) { + Community? parseCommunity(Map? communityData) { if (communityData == null) return null; return Community.fromJSON(communityData); } - ModerationCategory parseModerationCategory(Map moderationCategoryData) { + ModerationCategory? parseModerationCategory(Map? moderationCategoryData) { if (moderationCategoryData == null) return null; return ModerationCategory.fromJson(moderationCategoryData); } - ModeratedObjectType parseType(String moderatedObjectTypeStr) { + ModeratedObjectType? parseType(String? moderatedObjectTypeStr) { if (moderatedObjectTypeStr == null) return null; - ModeratedObjectType moderatedObjectType; + ModeratedObjectType? moderatedObjectType; if (moderatedObjectTypeStr == ModeratedObject.objectTypeCommunity) { moderatedObjectType = ModeratedObjectType.community; } else if (moderatedObjectTypeStr == ModeratedObject.objectTypePost) { @@ -162,10 +162,10 @@ class ModeratedObjectFactory extends UpdatableModelFactory { return moderatedObjectType; } - ModeratedObjectStatus parseStatus(String moderatedObjectStatusStr) { + ModeratedObjectStatus? parseStatus(String? moderatedObjectStatusStr) { if (moderatedObjectStatusStr == null) return null; - ModeratedObjectStatus moderatedObjectStatus; + ModeratedObjectStatus? moderatedObjectStatus; if (moderatedObjectStatusStr == ModeratedObject.statusPending) { moderatedObjectStatus = ModeratedObjectStatus.pending; } else if (moderatedObjectStatusStr == ModeratedObject.statusApproved) { @@ -180,7 +180,7 @@ class ModeratedObjectFactory extends UpdatableModelFactory { return moderatedObjectStatus; } - String convertStatusToString(ModeratedObjectStatus moderatedObjectStatus) { + String? convertStatusToString(ModeratedObjectStatus? moderatedObjectStatus) { if (moderatedObjectStatus == null) return null; switch (moderatedObjectStatus) { @@ -195,12 +195,12 @@ class ModeratedObjectFactory extends UpdatableModelFactory { } } - String convertStatusToHumanReadableString( - ModeratedObjectStatus moderatedObjectStatus, + String? convertStatusToHumanReadableString( + ModeratedObjectStatus? moderatedObjectStatus, {capitalize = false}) { if (moderatedObjectStatus == null) return null; - String result; + late String result; switch (moderatedObjectStatus) { case ModeratedObjectStatus.approved: @@ -218,7 +218,7 @@ class ModeratedObjectFactory extends UpdatableModelFactory { return capitalize ? toCapital(result) : result; } - String convertTypeToString(ModeratedObjectType moderatedObjectType) { + String? convertTypeToString(ModeratedObjectType? moderatedObjectType) { if (moderatedObjectType == null) return null; switch (moderatedObjectType) { @@ -237,8 +237,8 @@ class ModeratedObjectFactory extends UpdatableModelFactory { } } - String convertTypeToHumanReadableString( - ModeratedObjectType moderatedObjectType, + String? convertTypeToHumanReadableString( + ModeratedObjectType? moderatedObjectType, {capitalize = false}) { if (moderatedObjectType == null) return null; @@ -267,7 +267,7 @@ class ModeratedObjectFactory extends UpdatableModelFactory { } dynamic parseContentObject( - {@required Map contentObjectData, @required ModeratedObjectType type}) { + {required Map? contentObjectData, required ModeratedObjectType? type}) { if (contentObjectData == null) return null; dynamic contentObject; diff --git a/lib/models/moderation/moderated_object_list.dart b/lib/models/moderation/moderated_object_list.dart index 280892fc1..d42ee940a 100644 --- a/lib/models/moderation/moderated_object_list.dart +++ b/lib/models/moderation/moderated_object_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/moderation/moderated_object.dart'; class ModeratedObjectsList { - final List moderatedObjects; + final List? moderatedObjects; ModeratedObjectsList({ this.moderatedObjects, diff --git a/lib/models/moderation/moderated_object_log.dart b/lib/models/moderation/moderated_object_log.dart index 1b67036eb..5dff289ab 100644 --- a/lib/models/moderation/moderated_object_log.dart +++ b/lib/models/moderation/moderated_object_log.dart @@ -9,12 +9,12 @@ class ModeratedObjectLog { static String verifiedChangedLogType = 'VC'; static String categoryChangedLogType = 'CC'; - final int id; - final String description; - final bool verified; - final User actor; - final DateTime created; - ModeratedObjectLogType logType; + final int? id; + final String? description; + final bool? verified; + final User? actor; + final DateTime? created; + ModeratedObjectLogType? logType; dynamic contentObject; @@ -28,7 +28,7 @@ class ModeratedObjectLog { this.logType}); factory ModeratedObjectLog.fromJson(Map parsedJson) { - ModeratedObjectLogType logType = parseType(parsedJson['log_type']); + ModeratedObjectLogType? logType = parseType(parsedJson['log_type']); return ModeratedObjectLog( verified: parsedJson['verified'], @@ -43,19 +43,19 @@ class ModeratedObjectLog { contentObjectData: parsedJson['content_object'], logType: logType)); } - static User parseActor(Map rawActor) { + static User? parseActor(Map? rawActor) { if (rawActor == null) return null; return User.fromJson(rawActor); } - static DateTime parseCreated(String created) { + static DateTime? parseCreated(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } static dynamic parseContentObject( - {@required Map contentObjectData, - @required ModeratedObjectLogType logType}) { + {required Map? contentObjectData, + required ModeratedObjectLogType? logType}) { if (contentObjectData == null) return null; dynamic contentObject; @@ -82,10 +82,10 @@ class ModeratedObjectLog { return contentObject; } - static ModeratedObjectLogType parseType(String moderatedObjectTypeStr) { + static ModeratedObjectLogType? parseType(String? moderatedObjectTypeStr) { if (moderatedObjectTypeStr == null) return null; - ModeratedObjectLogType moderatedObjectLogType; + ModeratedObjectLogType? moderatedObjectLogType; if (moderatedObjectTypeStr == ModeratedObjectLog.descriptionChangedLogType) { moderatedObjectLogType = ModeratedObjectLogType.descriptionChanged; @@ -114,8 +114,8 @@ enum ModeratedObjectLogType { } class ModeratedObjectCategoryChangedLog { - final ModerationCategory changedFrom; - final ModerationCategory changedTo; + final ModerationCategory? changedFrom; + final ModerationCategory? changedTo; ModeratedObjectCategoryChangedLog({this.changedFrom, this.changedTo}); @@ -127,15 +127,15 @@ class ModeratedObjectCategoryChangedLog { ); } - static ModerationCategory parseCategory(Map rawModerationCategory) { + static ModerationCategory? parseCategory(Map? rawModerationCategory) { if (rawModerationCategory == null) return null; return ModerationCategory.fromJson(rawModerationCategory); } } class ModeratedObjectDescriptionChangedLog { - final String changedFrom; - final String changedTo; + final String? changedFrom; + final String? changedTo; ModeratedObjectDescriptionChangedLog({this.changedFrom, this.changedTo}); @@ -149,8 +149,8 @@ class ModeratedObjectDescriptionChangedLog { } class ModeratedObjectVerifiedChangedLog { - final bool changedFrom; - final bool changedTo; + final bool? changedFrom; + final bool? changedTo; ModeratedObjectVerifiedChangedLog({this.changedFrom, this.changedTo}); @@ -164,8 +164,8 @@ class ModeratedObjectVerifiedChangedLog { } class ModeratedObjectStatusChangedLog { - final ModeratedObjectStatus changedFrom; - final ModeratedObjectStatus changedTo; + final ModeratedObjectStatus? changedFrom; + final ModeratedObjectStatus? changedTo; ModeratedObjectStatusChangedLog({this.changedFrom, this.changedTo}); @@ -177,7 +177,7 @@ class ModeratedObjectStatusChangedLog { ); } - static ModeratedObjectStatus parseStatus(String rawModerationStatus) { + static ModeratedObjectStatus? parseStatus(String? rawModerationStatus) { if (rawModerationStatus == null) return null; return ModeratedObject.factory.parseStatus(rawModerationStatus); } diff --git a/lib/models/moderation/moderated_object_log_list.dart b/lib/models/moderation/moderated_object_log_list.dart index 80f15dbdf..7b5e441d7 100644 --- a/lib/models/moderation/moderated_object_log_list.dart +++ b/lib/models/moderation/moderated_object_log_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/moderation/moderated_object_log.dart'; class ModeratedObjectLogsList { - final List moderatedObjectLogs; + final List? moderatedObjectLogs; ModeratedObjectLogsList({ this.moderatedObjectLogs, diff --git a/lib/models/moderation/moderation_category.dart b/lib/models/moderation/moderation_category.dart index 49b2fb032..af8726c2e 100644 --- a/lib/models/moderation/moderation_category.dart +++ b/lib/models/moderation/moderation_category.dart @@ -4,10 +4,10 @@ class ModerationCategory { static final severityMedium = 'M'; static final severityLow = 'L'; - static ModerationCategorySeverity parseType(String notificationTypeStr) { + static ModerationCategorySeverity? parseType(String? notificationTypeStr) { if (notificationTypeStr == null) return null; - ModerationCategorySeverity notificationType; + ModerationCategorySeverity? notificationType; if (notificationTypeStr == ModerationCategory.severityCritical) { notificationType = ModerationCategorySeverity.critical; } else if (notificationTypeStr == ModerationCategory.severityHigh) { @@ -24,11 +24,11 @@ class ModerationCategory { return notificationType; } - final int id; - final ModerationCategorySeverity severity; - final String name; - final String title; - final String description; + final int? id; + final ModerationCategorySeverity? severity; + final String? name; + final String? title; + final String? description; ModerationCategory( {this.id, this.severity, this.name, this.title, this.description}); diff --git a/lib/models/moderation/moderation_category_list.dart b/lib/models/moderation/moderation_category_list.dart index 2d5bd43d2..5c113ba9c 100644 --- a/lib/models/moderation/moderation_category_list.dart +++ b/lib/models/moderation/moderation_category_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/moderation/moderation_category.dart'; class ModerationCategoriesList { - final List moderationCategories; + final List? moderationCategories; ModerationCategoriesList({ this.moderationCategories, diff --git a/lib/models/moderation/moderation_penalty.dart b/lib/models/moderation/moderation_penalty.dart index 8e90f1da4..28ceb7f34 100644 --- a/lib/models/moderation/moderation_penalty.dart +++ b/lib/models/moderation/moderation_penalty.dart @@ -6,11 +6,11 @@ import 'package:Okuna/models/user.dart'; class ModerationPenalty { static String moderationPenaltyTypeSuspension = 'S'; - final int id; - final User user; - final DateTime expiration; - final ModeratedObject moderatedObject; - final ModerationPenaltyType type; + final int? id; + final User? user; + final DateTime? expiration; + final ModeratedObject? moderatedObject; + final ModerationPenaltyType? type; ModerationPenalty({ this.user, @@ -35,30 +35,30 @@ class ModerationPenalty { expiration: parseExpiration(parsedJson['expiration'])); } - static User parseUser(Map rawActor) { + static User? parseUser(Map? rawActor) { if (rawActor == null) return null; return User.fromJson(rawActor); } - static ModerationCategory parseCategory(Map rawModerationCategory) { + static ModerationCategory? parseCategory(Map? rawModerationCategory) { if (rawModerationCategory == null) return null; return ModerationCategory.fromJson(rawModerationCategory); } - static DateTime parseExpiration(String expiration) { + static DateTime? parseExpiration(String? expiration) { if (expiration == null) return null; return DateTime.parse(expiration).toLocal(); } - static ModeratedObject parseModeratedObject(Map rawModeratedObject) { + static ModeratedObject? parseModeratedObject(Map? rawModeratedObject) { if (rawModeratedObject == null) return null; return ModeratedObject.fromJSON(rawModeratedObject); } - static ModerationPenaltyType parseType(String moderationPenaltyTypeStr) { + static ModerationPenaltyType? parseType(String? moderationPenaltyTypeStr) { if (moderationPenaltyTypeStr == null) return null; - ModerationPenaltyType moderationPenaltyType; + ModerationPenaltyType? moderationPenaltyType; if (moderationPenaltyTypeStr == ModerationPenalty.moderationPenaltyTypeSuspension) { moderationPenaltyType = ModerationPenaltyType.suspension; @@ -72,7 +72,7 @@ class ModerationPenalty { static String convertModerationPenaltyTypeToHumanReadableString( ModerationPenaltyType type, - {bool capitalize}) { + {bool capitalize = false}) { String result; switch (type) { case ModerationPenaltyType.suspension: diff --git a/lib/models/moderation/moderation_penalty_list.dart b/lib/models/moderation/moderation_penalty_list.dart index 11139d244..2d0683180 100644 --- a/lib/models/moderation/moderation_penalty_list.dart +++ b/lib/models/moderation/moderation_penalty_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/moderation/moderation_penalty.dart'; class ModerationPenaltiesList { - final List moderationPenalties; + final List? moderationPenalties; ModerationPenaltiesList({ this.moderationPenalties, diff --git a/lib/models/moderation/moderation_report.dart b/lib/models/moderation/moderation_report.dart index dd827c8a2..62b60a16b 100644 --- a/lib/models/moderation/moderation_report.dart +++ b/lib/models/moderation/moderation_report.dart @@ -3,10 +3,10 @@ import 'package:Okuna/models/moderation/moderation_category.dart'; import 'package:Okuna/models/user.dart'; class ModerationReport { - final ModerationCategory category; - final String description; - final User reporter; - final DateTime created; + final ModerationCategory? category; + final String? description; + final User? reporter; + final DateTime? created; ModerationReport( {this.description, this.reporter, this.category, this.created}); @@ -23,17 +23,17 @@ class ModerationReport { created: parseCreated(parsedJson['created'])); } - static User parseReporter(Map rawActor) { + static User? parseReporter(Map? rawActor) { if (rawActor == null) return null; return User.fromJson(rawActor); } - static ModerationCategory parseCategory(Map rawModerationCategory) { + static ModerationCategory? parseCategory(Map? rawModerationCategory) { if (rawModerationCategory == null) return null; return ModerationCategory.fromJson(rawModerationCategory); } - static DateTime parseCreated(String created) { + static DateTime? parseCreated(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } diff --git a/lib/models/moderation/moderation_report_list.dart b/lib/models/moderation/moderation_report_list.dart index df0d446ed..6c2823246 100644 --- a/lib/models/moderation/moderation_report_list.dart +++ b/lib/models/moderation/moderation_report_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/moderation/moderation_report.dart'; class ModerationReportsList { - final List moderationReports; + final List? moderationReports; ModerationReportsList({ this.moderationReports, diff --git a/lib/models/notifications/community_invite_notification.dart b/lib/models/notifications/community_invite_notification.dart index 3ff2cb19d..b199d7600 100644 --- a/lib/models/notifications/community_invite_notification.dart +++ b/lib/models/notifications/community_invite_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/community_invite.dart'; class CommunityInviteNotification { - final int id; - final CommunityInvite communityInvite; + final int? id; + final CommunityInvite? communityInvite; const CommunityInviteNotification({ this.communityInvite, @@ -15,7 +15,7 @@ class CommunityInviteNotification { communityInvite: _parseCommunityInvite(json['community_invite'])); } - static CommunityInvite _parseCommunityInvite(Map communityInviteData) { + static CommunityInvite _parseCommunityInvite(Map communityInviteData) { return CommunityInvite.fromJSON(communityInviteData); } } diff --git a/lib/models/notifications/community_new_post_notification.dart b/lib/models/notifications/community_new_post_notification.dart index d3f32fa73..a418ecf98 100644 --- a/lib/models/notifications/community_new_post_notification.dart +++ b/lib/models/notifications/community_new_post_notification.dart @@ -1,8 +1,8 @@ import '../post.dart'; class CommunityNewPostNotification { - final int id; - final Post post; + final int? id; + final Post? post; const CommunityNewPostNotification({ this.post, @@ -15,7 +15,7 @@ class CommunityNewPostNotification { post: _parsePost(json['post'])); } - static Post _parsePost(Map postData) { + static Post _parsePost(Map postData) { return Post.fromJson(postData); } } diff --git a/lib/models/notifications/connection_confirmed_notification.dart b/lib/models/notifications/connection_confirmed_notification.dart index bb338c675..570a7be91 100644 --- a/lib/models/notifications/connection_confirmed_notification.dart +++ b/lib/models/notifications/connection_confirmed_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/user.dart'; class ConnectionConfirmedNotification { - final int id; - final User connectionConfirmator; + final int? id; + final User? connectionConfirmator; ConnectionConfirmedNotification({this.id, this.connectionConfirmator}); @@ -12,7 +12,7 @@ class ConnectionConfirmedNotification { connectionConfirmator: _parseUser(json['connection_confirmator'])); } - static User _parseUser(Map userData) { + static User _parseUser(Map userData) { return User.fromJson(userData); } } diff --git a/lib/models/notifications/connection_request_notification.dart b/lib/models/notifications/connection_request_notification.dart index 30489fcfb..ca7b09c9d 100644 --- a/lib/models/notifications/connection_request_notification.dart +++ b/lib/models/notifications/connection_request_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/user.dart'; class ConnectionRequestNotification { - final int id; - final User connectionRequester; + final int? id; + final User? connectionRequester; ConnectionRequestNotification({this.id, this.connectionRequester}); @@ -12,7 +12,7 @@ class ConnectionRequestNotification { connectionRequester: _parseUser(json['connection_requester'])); } - static User _parseUser(Map userData) { + static User _parseUser(Map userData) { return User.fromJson(userData); } } diff --git a/lib/models/notifications/follow_notification.dart b/lib/models/notifications/follow_notification.dart index 202109b59..8885cb2cf 100644 --- a/lib/models/notifications/follow_notification.dart +++ b/lib/models/notifications/follow_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/user.dart'; class FollowNotification { - final int id; - final User follower; + final int? id; + final User? follower; FollowNotification({this.id, this.follower}); @@ -11,7 +11,7 @@ class FollowNotification { id: json['id'], follower: _parseUser(json['follower'])); } - static User _parseUser(Map userData) { + static User _parseUser(Map userData) { return User.fromJson(userData); } } diff --git a/lib/models/notifications/follow_request_approved_notification.dart b/lib/models/notifications/follow_request_approved_notification.dart index 7c5dc38de..60efcd100 100644 --- a/lib/models/notifications/follow_request_approved_notification.dart +++ b/lib/models/notifications/follow_request_approved_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/follow.dart'; class FollowRequestApprovedNotification { - final int id; - final Follow follow; + final int? id; + final Follow? follow; FollowRequestApprovedNotification({this.id, this.follow}); diff --git a/lib/models/notifications/follow_request_notification.dart b/lib/models/notifications/follow_request_notification.dart index b32d02ad3..1b14ac276 100644 --- a/lib/models/notifications/follow_request_notification.dart +++ b/lib/models/notifications/follow_request_notification.dart @@ -3,8 +3,8 @@ import 'package:Okuna/models/user.dart'; import '../follow_request.dart'; class FollowRequestNotification { - final int id; - final FollowRequest followRequest; + final int? id; + final FollowRequest? followRequest; FollowRequestNotification({this.id, this.followRequest}); diff --git a/lib/models/notifications/notification.dart b/lib/models/notifications/notification.dart index bb66371a3..341381fe9 100644 --- a/lib/models/notifications/notification.dart +++ b/lib/models/notifications/notification.dart @@ -19,13 +19,13 @@ import 'package:meta/meta.dart'; import 'package:timeago/timeago.dart' as timeago; class OBNotification extends UpdatableModel { - final int id; - User owner; - NotificationType type; + final int? id; + User? owner; + NotificationType? type; dynamic contentObject; - DateTime created; + DateTime? created; - bool read; + bool? read; OBNotification( {this.id, @@ -41,8 +41,12 @@ class OBNotification extends UpdatableModel { return factory.fromJson(json); } - String getRelativeCreated() { - return timeago.format(created); + String? getRelativeCreated() { + if (created == null) { + return null; + } + + return timeago.format(created!); } @override @@ -77,12 +81,12 @@ class OBNotification extends UpdatableModel { class NotificationFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 120)); @override OBNotification makeFromJson(Map json) { - NotificationType type = NotificationType.parse(json['notification_type']); + NotificationType? type = NotificationType.parse(json['notification_type']); return OBNotification( id: json['id'], @@ -94,13 +98,13 @@ class NotificationFactory extends UpdatableModelFactory { read: json['read']); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } dynamic parseContentObject( - {@required Map contentObjectData, @required NotificationType type}) { + {required Map? contentObjectData, required NotificationType? type}) { if (contentObjectData == null) return null; dynamic contentObject; @@ -209,10 +213,10 @@ class NotificationType { static values() => _values; - static NotificationType parse(String string) { + static NotificationType? parse(String? string) { if (string == null) return null; - NotificationType notificationType; + NotificationType? notificationType; for (var type in _values) { if (string == type.code) { notificationType = type; diff --git a/lib/models/notifications/notifications_list.dart b/lib/models/notifications/notifications_list.dart index e731c8368..100e3ea7a 100644 --- a/lib/models/notifications/notifications_list.dart +++ b/lib/models/notifications/notifications_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/notifications/notification.dart'; class NotificationsList { - final List notifications; + final List? notifications; NotificationsList({ this.notifications, diff --git a/lib/models/notifications/post_comment_notification.dart b/lib/models/notifications/post_comment_notification.dart index 6e5296852..2e71c2e05 100644 --- a/lib/models/notifications/post_comment_notification.dart +++ b/lib/models/notifications/post_comment_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/post_comment.dart'; class PostCommentNotification { - final int id; - final PostComment postComment; + final int? id; + final PostComment? postComment; PostCommentNotification({this.id, this.postComment}); @@ -11,11 +11,11 @@ class PostCommentNotification { id: json['id'], postComment: _parsePostComment(json['post_comment'])); } - static PostComment _parsePostComment(Map postCommentData) { + static PostComment _parsePostComment(Map postCommentData) { return PostComment.fromJSON(postCommentData); } - int getPostCreatorId() { - return postComment.getPostCreatorId(); + int? getPostCreatorId() { + return postComment?.getPostCreatorId(); } } diff --git a/lib/models/notifications/post_comment_reaction_notification.dart b/lib/models/notifications/post_comment_reaction_notification.dart index d2043e506..de827052c 100644 --- a/lib/models/notifications/post_comment_reaction_notification.dart +++ b/lib/models/notifications/post_comment_reaction_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/post_comment_reaction.dart'; class PostCommentReactionNotification { - final int id; - final PostCommentReaction postCommentReaction; + final int? id; + final PostCommentReaction? postCommentReaction; PostCommentReactionNotification({this.id, this.postCommentReaction}); @@ -14,7 +14,7 @@ class PostCommentReactionNotification { } static PostCommentReaction _parsePostCommentReaction( - Map postCommentReactionData) { + Map postCommentReactionData) { return PostCommentReaction.fromJson(postCommentReactionData); } } diff --git a/lib/models/notifications/post_comment_reply_notification.dart b/lib/models/notifications/post_comment_reply_notification.dart index b21dd99f8..83fe42819 100644 --- a/lib/models/notifications/post_comment_reply_notification.dart +++ b/lib/models/notifications/post_comment_reply_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/post_comment.dart'; class PostCommentReplyNotification { - final int id; - final PostComment postComment; + final int? id; + final PostComment? postComment; PostCommentReplyNotification({this.id, this.postComment}); @@ -13,11 +13,11 @@ class PostCommentReplyNotification { ); } - static PostComment _parsePostComment(Map postCommentData) { + static PostComment _parsePostComment(Map postCommentData) { return PostComment.fromJSON(postCommentData); } - int getPostCreatorId() { - return postComment.getPostCreatorId(); + int? getPostCreatorId() { + return postComment?.getPostCreatorId(); } } diff --git a/lib/models/notifications/post_comment_user_mention_notification.dart b/lib/models/notifications/post_comment_user_mention_notification.dart index ce8b6bd3c..512badd37 100644 --- a/lib/models/notifications/post_comment_user_mention_notification.dart +++ b/lib/models/notifications/post_comment_user_mention_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/post_comment_user_mention.dart'; class PostCommentUserMentionNotification { - final int id; - final PostCommentUserMention postCommentUserMention; + final int? id; + final PostCommentUserMention? postCommentUserMention; PostCommentUserMentionNotification({this.id, this.postCommentUserMention}); @@ -15,7 +15,7 @@ class PostCommentUserMentionNotification { } static PostCommentUserMention _parsePostCommentUserMention( - Map postCommentUserMentionData) { + Map postCommentUserMentionData) { return PostCommentUserMention.fromJSON(postCommentUserMentionData); } } diff --git a/lib/models/notifications/post_reaction_notification.dart b/lib/models/notifications/post_reaction_notification.dart index 96904d300..8f7bf199c 100644 --- a/lib/models/notifications/post_reaction_notification.dart +++ b/lib/models/notifications/post_reaction_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/post_reaction.dart'; class PostReactionNotification { - final int id; - final PostReaction postReaction; + final int? id; + final PostReaction? postReaction; PostReactionNotification({this.id, this.postReaction}); @@ -12,7 +12,8 @@ class PostReactionNotification { postReaction: _parsePostReaction(json['post_reaction'])); } - static PostReaction _parsePostReaction(Map postReactionData) { + static PostReaction _parsePostReaction( + Map postReactionData) { return PostReaction.fromJson(postReactionData); } } diff --git a/lib/models/notifications/post_user_mention_notification.dart b/lib/models/notifications/post_user_mention_notification.dart index 9bf6f9eb9..eb0a9a14a 100644 --- a/lib/models/notifications/post_user_mention_notification.dart +++ b/lib/models/notifications/post_user_mention_notification.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/post_user_mention.dart'; class PostUserMentionNotification { - final int id; - final PostUserMention postUserMention; + final int? id; + final PostUserMention? postUserMention; PostUserMentionNotification({this.id, this.postUserMention}); @@ -12,7 +12,8 @@ class PostUserMentionNotification { postUserMention: _parsePostUserMention(json['post_user_mention'])); } - static PostUserMention _parsePostUserMention(Map postUserMentionData) { + static PostUserMention _parsePostUserMention( + Map postUserMentionData) { return PostUserMention.fromJSON(postUserMentionData); } } diff --git a/lib/models/notifications/user_new_post_notification.dart b/lib/models/notifications/user_new_post_notification.dart index 959bd0e33..86e793a8c 100644 --- a/lib/models/notifications/user_new_post_notification.dart +++ b/lib/models/notifications/user_new_post_notification.dart @@ -1,8 +1,8 @@ import '../post.dart'; class UserNewPostNotification { - final int id; - final Post post; + final int? id; + final Post? post; const UserNewPostNotification({ this.post, @@ -15,7 +15,7 @@ class UserNewPostNotification { post: _parsePost(json['post'])); } - static Post _parsePost(Map postData) { + static Post _parsePost(Map postData) { return Post.fromJson(postData); } } diff --git a/lib/models/post.dart b/lib/models/post.dart index c0a317756..aa581e396 100644 --- a/lib/models/post.dart +++ b/lib/models/post.dart @@ -21,51 +21,52 @@ import 'package:timeago/timeago.dart' as timeago; import 'language.dart'; import 'link_preview/link_preview.dart'; +import 'package:collection/collection.dart'; + class Post extends UpdatableModel { - final int id; - final String uuid; - final int creatorId; - DateTime created; - User creator; - CirclesList circles; - - ReactionsEmojiCountList reactionsEmojiCounts; - PostReaction reaction; - int reactionsCount; - int commentsCount; - double mediaHeight; - double mediaWidth; - String mediaThumbnail; - bool areCommentsEnabled; - bool publicReactions; - String text; - Language language; - OBPostStatus status; - - PostMediaList media; - PostCommentList commentsList; - Community community; - HashtagsList hashtagsList; - PostLinksList postLinksList; - Map hashtagsMap; - - bool isMuted; - bool isEncircled; - bool isEdited; - bool isClosed; - bool isReported; + final int? id; + final String? uuid; + final int? creatorId; + DateTime? created; + User? creator; + CirclesList? circles; + + ReactionsEmojiCountList? reactionsEmojiCounts; + PostReaction? reaction; + int? reactionsCount; + int? commentsCount; + double? mediaHeight; + double? mediaWidth; + String? mediaThumbnail; + bool? areCommentsEnabled; + bool? publicReactions; + String? text; + Language? language; + OBPostStatus? status; + + PostMediaList? media; + PostCommentList? commentsList; + Community? community; + HashtagsList? hashtagsList; + PostLinksList? postLinksList; + Map? hashtagsMap; + + bool? isMuted; + bool? isEncircled; + bool? isEdited; + bool? isClosed; + bool? isReported; // stored only in the app bool isExcludedFromTopPosts = false; bool isExcludedFromProfilePosts = false; // Stored as cache - LinkPreview linkPreview; + LinkPreview? linkPreview; static final factory = PostFactory(); factory Post.fromJson(Map json) { - if (json == null) return null; return factory.fromJson(json); } @@ -77,11 +78,11 @@ class Post extends UpdatableModel { 'creator_id': creatorId, 'creator': creator?.toJson(), 'circles': - circles?.circles?.map((Circle circle) => circle.toJson())?.toList(), + circles?.circles?.map((Circle circle) => circle.toJson()).toList(), 'reactions_emoji_counts': reactionsEmojiCounts?.counts - ?.map((ReactionsEmojiCount reactionEmojiCount) => - reactionEmojiCount.toJson()) - ?.toList(), + ?.map((ReactionsEmojiCount? reactionEmojiCount) => + reactionEmojiCount?.toJson()) + .toList(), 'reaction': reaction?.toJson(), 'reactions_count': reactionsCount, 'comments_count': commentsCount, @@ -95,16 +96,16 @@ class Post extends UpdatableModel { 'status': status?.code, 'media': media?.postMedia ?.map((PostMedia mediaObj) => mediaObj.toJson()) - ?.toList(), + .toList(), 'comments': commentsList?.comments ?.map((PostComment comment) => comment.toJson()) - ?.toList(), + .toList(), 'hashtags': hashtagsList?.hashtags ?.map((Hashtag hashtag) => hashtag.toJson()) - ?.toList(), + .toList(), 'links': postLinksList?.postLinks ?.map((PostLink postLink) => postLink.toJson()) - ?.toList(), + .toList(), 'community': community?.toJson(), 'is_muted': isMuted, 'is_encircled': isEncircled, @@ -245,11 +246,11 @@ class Post extends UpdatableModel { } bool isReactionEmoji(Emoji emoji) { - return hasReaction() && reaction.getEmojiId() == emoji.id; + return hasReaction() && reaction?.getEmojiId() == emoji.id; } bool hasPublicInteractions() { - return publicReactions && areCommentsEnabled; + return publicReactions != null && areCommentsEnabled != null && publicReactions! && areCommentsEnabled!; } bool isCommunityPost() { @@ -261,13 +262,13 @@ class Post extends UpdatableModel { } bool hasMedia() { - return media != null && media.postMedia.isNotEmpty; + return media != null && media!.postMedia!.isNotEmpty; } - PostLink getLinkToPreview() { - if (postLinksList != null && postLinksList.postLinks != null && postLinksList.postLinks.isNotEmpty) { - var linkPreview = postLinksList.postLinks - .firstWhere((link) => link.hasPreview, orElse: () => null); + PostLink? getLinkToPreview() { + if (postLinksList != null && postLinksList!.postLinks != null && postLinksList!.postLinks!.isNotEmpty) { + PostLink? linkPreview = postLinksList!.postLinks + !.firstWhereOrNull((link) => link.hasPreview!); return linkPreview; } @@ -279,7 +280,7 @@ class Post extends UpdatableModel { } bool hasText() { - return text != null && text.length > 0; + return text != null && text!.length > 0; } bool hasLanguage() { @@ -287,72 +288,85 @@ class Post extends UpdatableModel { } bool hasComments() { - return commentsList != null && commentsList.comments.length > 0; + return commentsList != null && commentsList!.comments!.length > 0; } bool hasCircles() { - return circles != null && circles.circles.length > 0; + return circles != null && circles!.circles!.length > 0; } bool hasCommentsCount() { - return commentsCount != null && commentsCount > 0; + return commentsCount != null && commentsCount! > 0; } bool isEncircledPost() { - return isEncircled || false; + return (isEncircled != null && isEncircled!) || false; } bool isOlderThan(Duration duration) { - return created.isBefore(DateTime.now().subtract(duration)); + return created != null && created!.isBefore(DateTime.now().subtract(duration)); } - List getPostComments() { - return commentsList.comments; + List? getPostComments() { + return commentsList?.comments; } - List getPostCircles() { - return circles.circles; + List? getPostCircles() { + return circles?.circles; } - List getEmojiCounts() { - return reactionsEmojiCounts.counts.toList(); + List? getEmojiCounts() { + return reactionsEmojiCounts?.counts?.toList(); } - String getCreatorUsername() { - return creator.username; + String? getCreatorUsername() { + return creator?.username; } - int getCreatorId() { - return creator.id; + int? getCreatorId() { + return creator?.id; } - String getCreatorAvatar() { - return creator.profile.avatar; + String? getCreatorAvatar() { + return creator?.profile?.avatar; } - List getMedia() { - return media.postMedia; + List? getMedia() { + return media?.postMedia; } - PostMedia getFirstMedia() { - return media.postMedia.first; + PostMedia? getFirstMedia() { + return media?.postMedia?.first; } - Language getLanguage() { + Language? getLanguage() { return language; } - String getRelativeCreated() { - return timeago.format(created); + String? getRelativeCreated() { + if (created == null) { + return null; + } + + return timeago.format(created!); } void incrementCommentsCount() { - this.commentsCount += 1; + if (this.commentsCount == null) { + this.commentsCount = 1; + } else { + this.commentsCount = this.commentsCount! + 1; + } + this.notifyUpdate(); } void decreaseCommentsCount() { - this.commentsCount -= 1; + if (this.commentsCount == null) { + return; + } + + this.commentsCount = this.commentsCount! - 1; this.notifyUpdate(); } @@ -361,7 +375,7 @@ class Post extends UpdatableModel { this.notifyUpdate(); } - void setLinkPreview(LinkPreview linkPreview) { + void setLinkPreview(LinkPreview? linkPreview) { this.linkPreview = linkPreview; this.notifyUpdate(); } @@ -370,41 +384,41 @@ class Post extends UpdatableModel { this.setReaction(null); } - void setReaction(PostReaction newReaction) { + void setReaction(PostReaction? newReaction) { bool hasReaction = this.hasReaction(); if (!hasReaction && newReaction == null) { throw 'Trying to remove no reaction'; } - var newEmojiCounts = reactionsEmojiCounts.counts.toList(); + var newEmojiCounts = reactionsEmojiCounts?.counts?.toList(); if (hasReaction) { - var currentReactionEmojiCount = newEmojiCounts.firstWhere((emojiCount) { - return emojiCount.getEmojiId() == reaction.getEmojiId(); + var currentReactionEmojiCount = newEmojiCounts?.firstWhere((emojiCount) { + return emojiCount?.getEmojiId() == reaction?.getEmojiId(); }); - if (currentReactionEmojiCount.count > 1) { + if (currentReactionEmojiCount?.count != null && currentReactionEmojiCount!.count! > 1) { // Decrement emoji reaction counts - currentReactionEmojiCount.count -= 1; + currentReactionEmojiCount.count = currentReactionEmojiCount.count! + 1; } else { // Remove emoji reaction count - newEmojiCounts.remove(currentReactionEmojiCount); + newEmojiCounts?.remove(currentReactionEmojiCount); } } if (newReaction != null) { - var reactionEmojiCount = newEmojiCounts.firstWhere((emojiCount) { - return emojiCount.getEmojiId() == newReaction.getEmojiId(); - }, orElse: () {}); + var reactionEmojiCount = newEmojiCounts?.firstWhereOrNull((emojiCount) { + return emojiCount?.getEmojiId() == newReaction.getEmojiId(); + }); if (reactionEmojiCount != null) { // Up existing count - reactionEmojiCount.count += 1; + reactionEmojiCount.count = reactionEmojiCount.count! + 1; } else { // Add new emoji count newEmojiCounts - .add(ReactionsEmojiCount(emoji: newReaction.emoji, count: 1)); + ?.add(ReactionsEmojiCount(emoji: newReaction.emoji, count: 1)); } } @@ -420,7 +434,7 @@ class Post extends UpdatableModel { notifyUpdate(); } - void setStatus(OBPostStatus status) { + void setStatus(OBPostStatus? status) { this.status = status; this.notifyUpdate(); } @@ -436,15 +450,15 @@ class Post extends UpdatableModel { } Map updatedMap = Map(); - hashtagsList.hashtags - .forEach((hashtag) => updatedMap[hashtag.name] = hashtag); + hashtagsList?.hashtags + ?.forEach((hashtag) => updatedMap[hashtag.name!] = hashtag); hashtagsMap = updatedMap; } } class PostFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 100)); @override @@ -481,73 +495,73 @@ class PostFactory extends UpdatableModelFactory { parseReactionsEmojiCounts(json['reactions_emoji_counts'])); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } - DateTime parseCreated(String created) { + DateTime? parseCreated(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } - PostMediaList parseMedia(List mediaRawData) { + PostMediaList? parseMedia(List? mediaRawData) { if (mediaRawData == null) return null; return PostMediaList.fromJson(mediaRawData); } - User parseCreator(Map creator) { + User? parseCreator(Map? creator) { if (creator == null) return null; return User.fromJson(creator); } - PostReaction parseReaction(Map postReaction) { + PostReaction? parseReaction(Map? postReaction) { if (postReaction == null) return null; return PostReaction.fromJson(postReaction); } - Community parseCommunity(Map communityData) { + Community? parseCommunity(Map? communityData) { if (communityData == null) return null; return Community.fromJSON(communityData); } - ReactionsEmojiCountList parseReactionsEmojiCounts(List reactionsEmojiCounts) { + ReactionsEmojiCountList? parseReactionsEmojiCounts(List? reactionsEmojiCounts) { if (reactionsEmojiCounts == null) return null; return ReactionsEmojiCountList.fromJson(reactionsEmojiCounts); } - PostCommentList parseCommentList(List commentList) { + PostCommentList? parseCommentList(List? commentList) { if (commentList == null) return null; return PostCommentList.fromJson(commentList); } - HashtagsList parseHashtagsList(List hashtagsList) { + HashtagsList? parseHashtagsList(List? hashtagsList) { if (hashtagsList == null) return null; return HashtagsList.fromJson(hashtagsList); } - PostLinksList parsePostLinksList(List postLinksList) { + PostLinksList? parsePostLinksList(List? postLinksList) { if (postLinksList == null) return null; return PostLinksList.fromJson(postLinksList); } - CirclesList parseCircles(List circlesData) { + CirclesList? parseCircles(List? circlesData) { if (circlesData == null) return null; return CirclesList.fromJson(circlesData); } - Language parseLanguage(Map languageData) { + Language? parseLanguage(Map? languageData) { if (languageData == null) return null; return Language.fromJson(languageData); } - double parseMediaWidth(dynamic mediaWidth) { + double? parseMediaWidth(dynamic mediaWidth) { if (mediaWidth == null) return null; if (mediaWidth is int) return mediaWidth.toDouble(); if (mediaWidth is double) return mediaWidth; } - double parseMediaHeight(dynamic mediaHeight) { + double? parseMediaHeight(dynamic mediaHeight) { if (mediaHeight == null) return null; if (mediaHeight is int) return mediaHeight.toDouble(); if (mediaHeight is double) return mediaHeight; @@ -569,10 +583,10 @@ class OBPostStatus { static values() => _values; - static OBPostStatus parse(String string) { + static OBPostStatus? parse(String? string) { if (string == null) return null; - OBPostStatus postStatus; + OBPostStatus? postStatus; for (var type in _values) { if (string == type.code) { postStatus = type; diff --git a/lib/models/post_comment.dart b/lib/models/post_comment.dart index 002d51d31..3fa6ec562 100644 --- a/lib/models/post_comment.dart +++ b/lib/models/post_comment.dart @@ -13,25 +13,27 @@ import 'package:Okuna/models/updatable_model.dart'; import 'emoji.dart'; import 'language.dart'; +import 'package:collection/collection.dart'; + class PostComment extends UpdatableModel { - final int id; - int creatorId; - int repliesCount; - DateTime created; - String text; - Language language; - User commenter; - PostComment parentComment; - PostCommentList replies; - ReactionsEmojiCountList reactionsEmojiCounts; - PostCommentReaction reaction; - HashtagsList hashtagsList; - Map hashtagsMap; - - Post post; - bool isEdited; - bool isReported; - bool isMuted; + final int? id; + int? creatorId; + int? repliesCount; + DateTime? created; + String? text; + Language? language; + User? commenter; + PostComment? parentComment; + PostCommentList? replies; + ReactionsEmojiCountList? reactionsEmojiCounts; + PostCommentReaction? reaction; + HashtagsList? hashtagsList; + Map? hashtagsMap; + + Post? post; + bool? isEdited; + bool? isReported; + bool? isMuted; static convertPostCommentSortTypeToString(PostCommentsSortType type) { String result; @@ -49,7 +51,7 @@ class PostComment extends UpdatableModel { } static PostCommentsSortType parsePostCommentSortType(String sortType) { - PostCommentsSortType type; + late PostCommentsSortType type; if (sortType == 'ASC') { type = PostCommentsSortType.asc; } @@ -88,7 +90,6 @@ class PostComment extends UpdatableModel { static final factory = PostCommentFactory(); factory PostComment.fromJSON(Map json) { - if (json == null) return null; return factory.fromJson(json); } @@ -97,24 +98,24 @@ class PostComment extends UpdatableModel { 'id': id, 'created': created?.toString(), 'text': text, - 'language': language.toJson(), + 'language': language?.toJson(), 'creator_id': creatorId, - 'commenter': commenter.toJson(), - 'post': post.toJson(), + 'commenter': commenter?.toJson(), + 'post': post?.toJson(), 'is_edited': isEdited, 'is_reported': isReported, 'is_muted': isMuted, - 'parent_comment': parentComment.toJson(), + 'parent_comment': parentComment?.toJson(), 'replies': - replies.comments.map((PostComment reply) => reply.toJson())?.toList(), + replies?.comments?.map((PostComment reply) => reply.toJson()).toList(), 'hashtags': hashtagsList?.hashtags ?.map((Hashtag hashtag) => hashtag.toJson()) - ?.toList(), + .toList(), 'replies_count': repliesCount, - 'reactions_emoji_counts': reactionsEmojiCounts.counts - .map((ReactionsEmojiCount reaction) => reaction.toJson()) - ?.toList(), - 'reaction': reaction.toJson() + 'reactions_emoji_counts': reactionsEmojiCounts?.counts + ?.map((ReactionsEmojiCount? reaction) => reaction?.toJson()) + .toList(), + 'reaction': reaction?.toJson() }; } @@ -180,24 +181,28 @@ class PostComment extends UpdatableModel { } } - String getRelativeCreated() { - return timeago.format(created); + String? getRelativeCreated() { + if (created == null) { + return null; + } + + return timeago.format(created!); } - String getCommenterUsername() { - return this.commenter.username; + String? getCommenterUsername() { + return this.commenter?.username; } - String getCommenterName() { - return this.commenter.getProfileName(); + String? getCommenterName() { + return this.commenter?.getProfileName(); } - String getCommenterProfileAvatar() { - return this.commenter.getProfileAvatar(); + String? getCommenterProfileAvatar() { + return this.commenter?.getProfileAvatar(); } bool hasReplies() { - return repliesCount != null && repliesCount > 0 && replies != null; + return repliesCount != null && repliesCount! > 0 && replies != null; } bool hasLanguage() { @@ -206,18 +211,18 @@ class PostComment extends UpdatableModel { List getPostCommentReplies() { if (replies == null) return []; - return replies.comments; + return replies!.comments ?? []; } - int getCommenterId() { - return this.commenter.id; + int? getCommenterId() { + return this.commenter?.id; } - int getPostCreatorId() { - return post.getCreatorId(); + int? getPostCreatorId() { + return post?.getCreatorId(); } - Language getLanguage() { + Language? getLanguage() { return this.language; } @@ -236,28 +241,28 @@ class PostComment extends UpdatableModel { } bool isReactionEmoji(Emoji emoji) { - return hasReaction() && reaction.getEmojiId() == emoji.id; + return hasReaction() && reaction!.getEmojiId() == emoji.id; } - void setReaction(PostCommentReaction newReaction) { + void setReaction(PostCommentReaction? newReaction) { bool hasReaction = this.hasReaction(); if (!hasReaction && newReaction == null) { throw 'Trying to remove no reaction'; } - var newEmojiCounts = reactionsEmojiCounts.counts != null - ? reactionsEmojiCounts.counts.toList() + List newEmojiCounts = reactionsEmojiCounts?.counts != null + ? reactionsEmojiCounts!.counts!.toList() : []; if (hasReaction) { var currentReactionEmojiCount = newEmojiCounts.firstWhere((emojiCount) { - return emojiCount.getEmojiId() == reaction.getEmojiId(); + return emojiCount?.getEmojiId() == reaction!.getEmojiId(); }); - if (currentReactionEmojiCount.count > 1) { + if (currentReactionEmojiCount?.count != null && currentReactionEmojiCount!.count! > 1) { // Decrement emoji reaction counts - currentReactionEmojiCount.count -= 1; + currentReactionEmojiCount.count = currentReactionEmojiCount.count! - 1; } else { // Remove emoji reaction count newEmojiCounts.remove(currentReactionEmojiCount); @@ -265,13 +270,13 @@ class PostComment extends UpdatableModel { } if (newReaction != null) { - var reactionEmojiCount = newEmojiCounts.firstWhere((emojiCount) { - return emojiCount.getEmojiId() == newReaction.getEmojiId(); - }, orElse: () {}); + var reactionEmojiCount = newEmojiCounts.firstWhereOrNull((emojiCount) { + return emojiCount?.getEmojiId() == newReaction.getEmojiId(); + }); if (reactionEmojiCount != null) { // Up existing count - reactionEmojiCount.count += 1; + reactionEmojiCount.count = reactionEmojiCount.count! + 1; } else { // Add new emoji count newEmojiCounts @@ -301,15 +306,15 @@ class PostComment extends UpdatableModel { } Map updatedMap = Map(); - hashtagsList.hashtags - .forEach((hashtag) => updatedMap[hashtag.name] = hashtag); + hashtagsList?.hashtags + ?.forEach((hashtag) => updatedMap[hashtag.name!] = hashtag); hashtagsMap = updatedMap; } } class PostCommentFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = LruCache(storage: UpdatableModelSimpleStorage(size: 200)); @override @@ -334,47 +339,47 @@ class PostCommentFactory extends UpdatableModelFactory { parseReactionsEmojiCounts(json['reactions_emoji_counts'])); } - Post parsePost(Map post) { + Post? parsePost(Map? post) { if (post == null) return null; return Post.fromJson(post); } - DateTime parseCreated(String created) { + DateTime? parseCreated(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } - PostComment parseParentComment(Map commentData) { + PostComment? parseParentComment(Map? commentData) { if (commentData == null) return null; return PostComment.fromJSON(commentData); } - PostCommentList parseCommentReplies(List repliesData) { + PostCommentList? parseCommentReplies(List? repliesData) { if (repliesData == null) return null; return PostCommentList.fromJson(repliesData); } - PostCommentReaction parseReaction(Map postCommentReaction) { + PostCommentReaction? parseReaction(Map? postCommentReaction) { if (postCommentReaction == null) return null; return PostCommentReaction.fromJson(postCommentReaction); } - ReactionsEmojiCountList parseReactionsEmojiCounts(List reactionsEmojiCounts) { + ReactionsEmojiCountList? parseReactionsEmojiCounts(List? reactionsEmojiCounts) { if (reactionsEmojiCounts == null) return null; return ReactionsEmojiCountList.fromJson(reactionsEmojiCounts); } - Language parseLanguage(Map languageData) { + Language? parseLanguage(Map? languageData) { if (languageData == null) return null; return Language.fromJson(languageData); } - HashtagsList parseHashtagsList(List hashtagsList) { + HashtagsList? parseHashtagsList(List? hashtagsList) { if (hashtagsList == null) return null; return HashtagsList.fromJson(hashtagsList); } diff --git a/lib/models/post_comment_list.dart b/lib/models/post_comment_list.dart index 38f4ea3bb..e5ab6648b 100644 --- a/lib/models/post_comment_list.dart +++ b/lib/models/post_comment_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/post_comment.dart'; class PostCommentList { - final List comments; + final List? comments; PostCommentList({ this.comments, diff --git a/lib/models/post_comment_reaction.dart b/lib/models/post_comment_reaction.dart index fd1c7d359..f5f7ad165 100644 --- a/lib/models/post_comment_reaction.dart +++ b/lib/models/post_comment_reaction.dart @@ -4,31 +4,30 @@ import 'package:Okuna/models/user.dart'; import 'package:timeago/timeago.dart' as timeago; class PostCommentReaction { - final int id; - final DateTime created; - final Emoji emoji; - final User reactor; - final PostComment postComment; + final int? id; + final DateTime? created; + final Emoji? emoji; + final User? reactor; + final PostComment? postComment; PostCommentReaction( {this.id, this.created, this.emoji, this.reactor, this.postComment}); factory PostCommentReaction.fromJson(Map parsedJson) { - if (parsedJson == null) return null; - DateTime created; + DateTime? created; var createdData = parsedJson['created']; if (createdData != null) created = DateTime.parse(createdData).toLocal(); - User reactor; + User? reactor; var reactorData = parsedJson['reactor']; if (reactorData != null) reactor = User.fromJson(reactorData); - PostComment postComment; + PostComment? postComment; if (parsedJson.containsKey('post_comment')) { postComment = PostComment.fromJSON(parsedJson['post_comment']); } - Emoji emoji = Emoji.fromJson(parsedJson['emoji']); + Emoji? emoji = Emoji.fromJson(parsedJson['emoji']); return PostCommentReaction( id: parsedJson['id'], @@ -42,41 +41,45 @@ class PostCommentReaction { return { 'id': id, 'created': created?.toString(), - 'emoji': emoji.toJson(), - 'reactor': reactor.toJson(), - 'post_comment': postComment.toJson() + 'emoji': emoji?.toJson(), + 'reactor': reactor?.toJson(), + 'post_comment': postComment?.toJson() }; } - String getRelativeCreated() { - return timeago.format(created); + String? getRelativeCreated() { + if (created == null) { + return null; + } + + return timeago.format(created!); } - String getReactorUsername() { - return this.reactor.username; + String? getReactorUsername() { + return this.reactor?.username; } - String getReactorProfileAvatar() { - return this.reactor.getProfileAvatar(); + String? getReactorProfileAvatar() { + return this.reactor?.getProfileAvatar(); } - int getReactorId() { - return this.reactor.id; + int? getReactorId() { + return this.reactor?.id; } - int getEmojiId() { - return this.emoji.id; + int? getEmojiId() { + return this.emoji?.id; } - String getEmojiImage() { - return this.emoji.image; + String? getEmojiImage() { + return this.emoji?.image; } - String getEmojiKeyword() { - return this.emoji.keyword; + String? getEmojiKeyword() { + return this.emoji?.keyword; } - PostCommentReaction copy({Emoji newEmoji}) { + PostCommentReaction copy({Emoji? newEmoji}) { return PostCommentReaction(emoji: newEmoji ?? emoji); } } diff --git a/lib/models/post_comment_reaction_list.dart b/lib/models/post_comment_reaction_list.dart index 327efac5c..54af8c523 100644 --- a/lib/models/post_comment_reaction_list.dart +++ b/lib/models/post_comment_reaction_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/post_comment_reaction.dart'; class PostCommentReactionList { - final List reactions; + final List? reactions; PostCommentReactionList({ this.reactions, diff --git a/lib/models/post_comment_user_mention.dart b/lib/models/post_comment_user_mention.dart index 6f094ca84..c2b9e64f5 100644 --- a/lib/models/post_comment_user_mention.dart +++ b/lib/models/post_comment_user_mention.dart @@ -2,9 +2,9 @@ import 'package:Okuna/models/post_comment.dart'; import 'package:Okuna/models/user.dart'; class PostCommentUserMention { - final int id; - final User user; - final PostComment postComment; + final int? id; + final User? user; + final PostComment? postComment; PostCommentUserMention({ this.id, @@ -20,12 +20,12 @@ class PostCommentUserMention { ); } - static User parseUser(Map userData) { + static User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } - static PostComment parsePostComment(Map postCommentData) { + static PostComment? parsePostComment(Map postCommentData) { if (postCommentData == null) return null; return PostComment.fromJSON(postCommentData); } diff --git a/lib/models/post_image.dart b/lib/models/post_image.dart index a26a96cc5..364abb77c 100644 --- a/lib/models/post_image.dart +++ b/lib/models/post_image.dart @@ -1,8 +1,8 @@ class PostImage { - final String image; - final double width; - final double height; - final String thumbnail; + final String? image; + final double? width; + final double? height; + final String? thumbnail; PostImage({ this.image, @@ -12,7 +12,6 @@ class PostImage { }); factory PostImage.fromJSON(Map parsedJson) { - if (parsedJson == null) return null; return PostImage( image: parsedJson['image'], thumbnail: parsedJson['thumbnail'], diff --git a/lib/models/post_link.dart b/lib/models/post_link.dart index b866625fd..52f48f5f4 100644 --- a/lib/models/post_link.dart +++ b/lib/models/post_link.dart @@ -1,8 +1,8 @@ class PostLink { - final int id; - String link; - bool hasPreview; + final int? id; + String? link; + bool? hasPreview; PostLink({ this.id, @@ -11,7 +11,6 @@ class PostLink { }); factory PostLink.fromJSON(Map json) { - if (json == null) return null; return PostLink( id: json['id'], link: json['link'], diff --git a/lib/models/post_links_list.dart b/lib/models/post_links_list.dart index 4f8c82bea..8b5087a3b 100644 --- a/lib/models/post_links_list.dart +++ b/lib/models/post_links_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/post_link.dart'; class PostLinksList { - final List postLinks; + final List? postLinks; PostLinksList({ this.postLinks, diff --git a/lib/models/post_media.dart b/lib/models/post_media.dart index 08c597382..8aca947eb 100644 --- a/lib/models/post_media.dart +++ b/lib/models/post_media.dart @@ -3,16 +3,15 @@ import 'package:Okuna/models/post_video.dart'; import 'package:flutter/cupertino.dart'; class PostMedia { - final int id; - final PostMediaType type; + final int? id; + final PostMediaType? type; final dynamic contentObject; - final int order; + final int? order; PostMedia({this.id, this.type, this.contentObject, this.order}); factory PostMedia.fromJSON(Map json) { - if (json == null) return null; - PostMediaType type = PostMediaType.parse(json['type']); + PostMediaType? type = PostMediaType.parse(json['type']); return PostMedia( id: json['id'], @@ -25,14 +24,14 @@ class PostMedia { Map toJson() { return { 'id': id, - 'type': type.code, + 'type': type?.code, 'content_object': contentObject?.toJson(), 'order': order }; } static dynamic parseContentObject( - {@required Map contentObjectData, @required PostMediaType type}) { + {required Map? contentObjectData, required PostMediaType? type}) { if (contentObjectData == null) return null; dynamic contentObject; @@ -67,10 +66,10 @@ class PostMediaType { static values() => _values; - static PostMediaType parse(String string) { + static PostMediaType? parse(String? string) { if (string == null) return null; - PostMediaType postMediaType; + PostMediaType? postMediaType; for (var type in _values) { if (string == type.code) { postMediaType = type; diff --git a/lib/models/post_media_list.dart b/lib/models/post_media_list.dart index 9f35c0be2..482901f0f 100644 --- a/lib/models/post_media_list.dart +++ b/lib/models/post_media_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/post_media.dart'; class PostMediaList { - final List postMedia; + final List? postMedia; PostMediaList({ this.postMedia, diff --git a/lib/models/post_reaction.dart b/lib/models/post_reaction.dart index a69eafd19..ad5c365e7 100644 --- a/lib/models/post_reaction.dart +++ b/lib/models/post_reaction.dart @@ -4,30 +4,29 @@ import 'package:Okuna/models/user.dart'; import 'package:timeago/timeago.dart' as timeago; class PostReaction { - final int id; - final DateTime created; - final Emoji emoji; - final User reactor; - final Post post; + final int? id; + final DateTime? created; + final Emoji? emoji; + final User? reactor; + final Post? post; PostReaction({this.id, this.created, this.emoji, this.reactor, this.post}); factory PostReaction.fromJson(Map parsedJson) { - if (parsedJson == null) return null; - DateTime created; + DateTime? created; var createdData = parsedJson['created']; if (createdData != null) created = DateTime.parse(createdData).toLocal(); - User reactor; + User? reactor; var reactorData = parsedJson['reactor']; if (reactorData != null) reactor = User.fromJson(reactorData); - Post post; + Post? post; if (parsedJson.containsKey('post')) { post = Post.fromJson(parsedJson['post']); } - Emoji emoji = Emoji.fromJson(parsedJson['emoji']); + Emoji? emoji = Emoji.fromJson(parsedJson['emoji']); return PostReaction( id: parsedJson['id'], @@ -47,39 +46,43 @@ class PostReaction { }; } - String getRelativeCreated() { - return timeago.format(created); + String? getRelativeCreated() { + if (created == null) { + return null; + } + + return timeago.format(created!); } - String getReactorUsername() { - return this.reactor.username; + String? getReactorUsername() { + return this.reactor?.username; } - String getReactorProfileAvatar() { - return this.reactor.getProfileAvatar(); + String? getReactorProfileAvatar() { + return this.reactor?.getProfileAvatar(); } - int getReactorId() { - return this.reactor.id; + int? getReactorId() { + return this.reactor?.id; } - int getEmojiId() { - return this.emoji.id; + int? getEmojiId() { + return this.emoji?.id; } - String getEmojiImage() { - return this.emoji.image; + String? getEmojiImage() { + return this.emoji?.image; } - String getEmojiKeyword() { - return this.emoji.keyword; + String? getEmojiKeyword() { + return this.emoji?.keyword; } - String getEmojiColor() { - return this.emoji.color; + String? getEmojiColor() { + return this.emoji?.color; } - PostReaction copy({Emoji newEmoji}) { + PostReaction copy({Emoji? newEmoji}) { return PostReaction(emoji: newEmoji ?? emoji); } } diff --git a/lib/models/post_reaction_list.dart b/lib/models/post_reaction_list.dart index 7c7906841..704012e62 100644 --- a/lib/models/post_reaction_list.dart +++ b/lib/models/post_reaction_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/post_reaction.dart'; class PostReactionList { - final List reactions; + final List? reactions; PostReactionList({ this.reactions, diff --git a/lib/models/post_user_mention.dart b/lib/models/post_user_mention.dart index 422d1d33f..12077d9c9 100644 --- a/lib/models/post_user_mention.dart +++ b/lib/models/post_user_mention.dart @@ -2,9 +2,9 @@ import 'package:Okuna/models/post.dart'; import 'package:Okuna/models/user.dart'; class PostUserMention { - final int id; - final User user; - final Post post; + final int? id; + final User? user; + final Post? post; PostUserMention({ this.id, @@ -20,12 +20,12 @@ class PostUserMention { ); } - static User parseUser(Map userData) { + static User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } - static Post parsePost(Map postData) { + static Post? parsePost(Map? postData) { if (postData == null) return null; return Post.fromJson(postData); } diff --git a/lib/models/post_video.dart b/lib/models/post_video.dart index c17847a55..c4f2104e8 100644 --- a/lib/models/post_video.dart +++ b/lib/models/post_video.dart @@ -2,15 +2,15 @@ import 'package:Okuna/models/video_format.dart'; import 'package:Okuna/models/video_formats_list.dart'; class PostVideo { - final int id; - final double width; - final double height; - final double duration; - final String file; - final String thumbnail; - final double thumbnailHeight; - final double thumbnailWidth; - final OBVideoFormatsList formatSet; + final int? id; + final double? width; + final double? height; + final double? duration; + final String? file; + final String? thumbnail; + final double? thumbnailHeight; + final double? thumbnailWidth; + final OBVideoFormatsList? formatSet; const PostVideo({ this.id, @@ -24,14 +24,13 @@ class PostVideo { this.thumbnailWidth, }); - OBVideoFormat getVideoFormatOfType(OBVideoFormatType type) { - return formatSet.videoFormats.firstWhere((OBVideoFormat format) { + OBVideoFormat? getVideoFormatOfType(OBVideoFormatType type) { + return formatSet?.videoFormats?.firstWhere((OBVideoFormat format) { return format.type == type; }); } factory PostVideo.fromJSON(Map parsedJson) { - if (parsedJson == null) return null; return PostVideo( width: parsedJson['width']?.toDouble(), height: parsedJson['height']?.toDouble(), @@ -45,7 +44,6 @@ class PostVideo { } static OBVideoFormatsList parseFormatSet(List rawData) { - if (rawData == null) return null; return OBVideoFormatsList.fromJson(rawData); } @@ -59,7 +57,7 @@ class PostVideo { 'file': file, 'thumbnail_height': thumbnailHeight, 'thumbnail_width': thumbnailWidth, - 'format_set': formatSet?.videoFormats?.map((OBVideoFormat format) => format.toJson())?.toList() + 'format_set': formatSet?.videoFormats?.map((OBVideoFormat format) => format.toJson()).toList() }; } } diff --git a/lib/models/posts_list.dart b/lib/models/posts_list.dart index f963aeac1..cf9fefb17 100644 --- a/lib/models/posts_list.dart +++ b/lib/models/posts_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/post.dart'; class PostsList { - final List posts; + final List? posts; PostsList({ this.posts, diff --git a/lib/models/push_notification.dart b/lib/models/push_notification.dart index e9c85d38c..3f60fb2ca 100644 --- a/lib/models/push_notification.dart +++ b/lib/models/push_notification.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/notifications/notification.dart'; class PushNotification { - static PushNotificationType parseType(String pushNotificationTypeStr) { + static PushNotificationType? parseType(String? pushNotificationTypeStr) { if (pushNotificationTypeStr == null) return null; PushNotificationType pushNotificationType; @@ -22,13 +22,13 @@ class PushNotification { return pushNotificationType; } - final PushNotificationType type; - final int notificationId; + final PushNotificationType? type; + final int? notificationId; const PushNotification({this.notificationId, this.type}); factory PushNotification.fromJson(Map parsedJson) { - PushNotificationType type = parseType(parsedJson['type']); + PushNotificationType? type = parseType(parsedJson['type']); return PushNotification( notificationId: parsedJson['notification_id'], type: type); diff --git a/lib/models/reactions_emoji_count.dart b/lib/models/reactions_emoji_count.dart index 1887fc914..54a0f2266 100644 --- a/lib/models/reactions_emoji_count.dart +++ b/lib/models/reactions_emoji_count.dart @@ -1,8 +1,8 @@ import 'package:Okuna/models/emoji.dart'; class ReactionsEmojiCount { - final Emoji emoji; - int count; + final Emoji? emoji; + int? count; ReactionsEmojiCount({this.emoji, this.count}); @@ -14,7 +14,7 @@ class ReactionsEmojiCount { Map toJson() { return { - 'emoji': emoji.toJson(), + 'emoji': emoji?.toJson(), 'count': count }; } @@ -28,7 +28,7 @@ class ReactionsEmojiCount { return count.toString(); } - int getEmojiId() { - return emoji.id; + int? getEmojiId() { + return emoji?.id; } } diff --git a/lib/models/reactions_emoji_count_list.dart b/lib/models/reactions_emoji_count_list.dart index 81ec97e8c..a47127b8b 100644 --- a/lib/models/reactions_emoji_count_list.dart +++ b/lib/models/reactions_emoji_count_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/reactions_emoji_count.dart'; class ReactionsEmojiCountList { - final List counts; + final List? counts; ReactionsEmojiCountList({ this.counts, diff --git a/lib/models/theme.dart b/lib/models/theme.dart index 1bb6f5a58..cdb442e34 100644 --- a/lib/models/theme.dart +++ b/lib/models/theme.dart @@ -2,9 +2,9 @@ import 'package:Okuna/models/updatable_model.dart'; import 'package:dcache/dcache.dart'; class OBTheme extends UpdatableModel { - int id; + int? id; - String name; + String? name; String primaryTextColor; String secondaryTextColor; @@ -18,7 +18,7 @@ class OBTheme extends UpdatableModel { String dangerColor; String dangerColorAccent; - String themePreview; + String? themePreview; static final factory = OBThemeFactory(); @@ -29,15 +29,15 @@ class OBTheme extends UpdatableModel { OBTheme( {this.id, this.name, - this.primaryColor, - this.primaryAccentColor, - this.dangerColor, - this.dangerColorAccent, - this.successColor, - this.successColorAccent, + required this.primaryColor, + required this.primaryAccentColor, + required this.dangerColor, + required this.dangerColorAccent, + required this.successColor, + required this.successColorAccent, this.themePreview, - this.primaryTextColor, - this.secondaryTextColor}) + required this.primaryTextColor, + required this.secondaryTextColor}) : super(); @override @@ -55,7 +55,7 @@ class OBTheme extends UpdatableModel { class OBThemeFactory extends UpdatableModelFactory { @override - SimpleCache cache = LruCache(storage: UpdatableModelSimpleStorage(size: 10)); + SimpleCache? cache = LruCache(storage: UpdatableModelSimpleStorage(size: 10)); @override OBTheme makeFromJson(Map json) { diff --git a/lib/models/top_post.dart b/lib/models/top_post.dart index cbf7681bd..4f0b095fc 100644 --- a/lib/models/top_post.dart +++ b/lib/models/top_post.dart @@ -3,21 +3,20 @@ import 'package:Okuna/models/updatable_model.dart'; import 'package:dcache/dcache.dart'; class TopPost extends UpdatableModel { - final int id; - Post post; - DateTime created; + final int? id; + Post? post; + DateTime? created; static final factory = TopPostFactory(); factory TopPost.fromJson(Map json) { - if (json == null) return null; return factory.fromJson(json); } Map toJson() { return { 'id': id, - 'post': post.toJson(), + 'post': post?.toJson(), 'created': created?.toString() }; } @@ -44,7 +43,7 @@ class TopPost extends UpdatableModel { class TopPostFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 50)); @override @@ -55,12 +54,12 @@ class TopPostFactory extends UpdatableModelFactory { created: parseCreated(json['created']),); } - Post parsePost(Map postData) { + Post? parsePost(Map? postData) { if (postData == null) return null; return Post.fromJson(postData); } - DateTime parseCreated(String created) { + DateTime? parseCreated(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } diff --git a/lib/models/top_posts_list.dart b/lib/models/top_posts_list.dart index 5d0d64325..f98d7ae32 100644 --- a/lib/models/top_posts_list.dart +++ b/lib/models/top_posts_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/top_post.dart'; class TopPostsList { - final List posts; + final List? posts; TopPostsList({ this.posts, diff --git a/lib/models/trending_post.dart b/lib/models/trending_post.dart index 2759c46f5..3313ae641 100644 --- a/lib/models/trending_post.dart +++ b/lib/models/trending_post.dart @@ -3,21 +3,20 @@ import 'package:Okuna/models/updatable_model.dart'; import 'package:dcache/dcache.dart'; class TrendingPost extends UpdatableModel { - final int id; - Post post; - DateTime created; + final int? id; + Post? post; + DateTime? created; static final factory = TrendingPostFactory(); factory TrendingPost.fromJson(Map json) { - if (json == null) return null; return factory.fromJson(json); } Map toJson() { return { 'id': id, - 'post': post.toJson(), + 'post': post?.toJson(), 'created': created?.toString() }; } @@ -44,7 +43,7 @@ class TrendingPost extends UpdatableModel { class TrendingPostFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = SimpleCache(storage: UpdatableModelSimpleStorage(size: 50)); @override @@ -55,12 +54,12 @@ class TrendingPostFactory extends UpdatableModelFactory { created: parseCreated(json['created']),); } - Post parsePost(Map postData) { + Post? parsePost(Map? postData) { if (postData == null) return null; return Post.fromJson(postData); } - DateTime parseCreated(String created) { + DateTime? parseCreated(String? created) { if (created == null) return null; return DateTime.parse(created).toLocal(); } diff --git a/lib/models/trending_posts_list.dart b/lib/models/trending_posts_list.dart index 5d941293c..9d55c44b7 100644 --- a/lib/models/trending_posts_list.dart +++ b/lib/models/trending_posts_list.dart @@ -2,7 +2,7 @@ import 'package:Okuna/models/top_post.dart'; import 'package:Okuna/models/trending_post.dart'; class TrendingPostsList { - final List posts; + final List? posts; TrendingPostsList({ this.posts, diff --git a/lib/models/updatable_model.dart b/lib/models/updatable_model.dart index 330e2b600..0458d2ccf 100644 --- a/lib/models/updatable_model.dart +++ b/lib/models/updatable_model.dart @@ -6,7 +6,7 @@ import 'package:meta/meta.dart'; import 'package:rxdart/rxdart.dart'; abstract class UpdatableModel { - final int id; + final int? id; Stream get updateSubject => _updateChangeSubject.stream; final _updateChangeSubject = BehaviorSubject(); @@ -30,7 +30,7 @@ abstract class UpdatableModel { } abstract class UpdatableModelFactory { - SimpleCache cache; + SimpleCache? cache; UpdatableModelFactory({this.cache}) { if (this.cache == null) @@ -40,47 +40,47 @@ abstract class UpdatableModelFactory { T fromJson(Map json) { int itemId = json['id']; - UpdatableModel item = getItemWithIdFromCache(itemId); + UpdatableModel? item = getItemWithIdFromCache(itemId); if (item != null) { item.update(json); - return item; + return item as T; } item = makeFromJson(json); - addToCache(item); + addToCache(item as T); return item; } T makeFromJson(Map json); - T getItemWithIdFromCache(int itemId) { - return cache.get(itemId); + T? getItemWithIdFromCache(int itemId) { + return cache!.get(itemId); } void addToCache(T item) { - cache.set(item.id, item); + cache!.set(item.id!, item); } void clearCache() { - cache.clear(); + cache!.clear(); } } class UpdatableModelSimpleStorage implements Storage { - static int MAX_INT = pow(2, 30) - 1; // (for 32 bit OS) + static int MAX_INT = pow(2, 30) - 1 as int; // (for 32 bit OS) - Map> _internalMap; - int _size; + late Map> _internalMap; + late int _size; - UpdatableModelSimpleStorage({@required int size}) { + UpdatableModelSimpleStorage({required int size}) { this._size = size; this._internalMap = new LinkedHashMap(); } @override - CacheEntry operator [](K key) { + CacheEntry? operator [](K key) { var ce = this._internalMap[key]; return ce; } @@ -96,7 +96,7 @@ class UpdatableModelSimpleStorage } @override - CacheEntry get(K key) { + CacheEntry? get(K key) { return this[key]; } @@ -108,7 +108,7 @@ class UpdatableModelSimpleStorage @override void remove(K key) { - CacheEntry item = get(key); + CacheEntry? item = get(key); // https://stackoverflow.com/questions/49879438/dart-do-i-have-to-cancel-stream-subscriptions-and-close-streamsinks // item.value.dispose(); this._internalMap.remove(key); diff --git a/lib/models/user.dart b/lib/models/user.dart index bd65def0c..c6c471a57 100644 --- a/lib/models/user.dart +++ b/lib/models/user.dart @@ -18,40 +18,40 @@ import 'package:dcache/dcache.dart'; import 'follows_list.dart'; class User extends UpdatableModel { - int id; - String uuid; - int connectionsCircleId; - String email; - String username; - Language language; - UserVisibility visibility; - UserProfile profile; - DateTime dateJoined; - UserNotificationsSettings notificationsSettings; - int followersCount; - int followingCount; - int unreadNotificationsCount; - int postsCount; - int inviteCount; - int pendingCommunitiesModeratedObjectsCount; - int activeModerationPenaltiesCount; - bool areGuidelinesAccepted; - bool areNewPostNotificationsEnabled; - bool isFollowing; - bool isFollowed; - bool isFollowRequested; - bool isConnected; - bool isReported; - bool isBlocked; - bool isGlobalModerator; - bool isFullyConnected; - bool isPendingConnectionConfirmation; - bool isPendingFollowRequestApproval; - bool isMemberOfCommunities; - CirclesList connectedCircles; - FollowsListsList followLists; - CommunityMembershipList communitiesMemberships; - CommunityInviteList communitiesInvites; + int? id; + String? uuid; + int? connectionsCircleId; + String? email; + String? username; + Language? language; + UserVisibility? visibility; + UserProfile? profile; + DateTime? dateJoined; + UserNotificationsSettings? notificationsSettings; + int? followersCount; + int? followingCount; + int? unreadNotificationsCount; + int? postsCount; + int? inviteCount; + int? pendingCommunitiesModeratedObjectsCount; + int? activeModerationPenaltiesCount; + bool? areGuidelinesAccepted; + bool? areNewPostNotificationsEnabled; + bool? isFollowing; + bool? isFollowed; + bool? isFollowRequested; + bool? isConnected; + bool? isReported; + bool? isBlocked; + bool? isGlobalModerator; + bool? isFullyConnected; + bool? isPendingConnectionConfirmation; + bool? isPendingFollowRequestApproval; + bool? isMemberOfCommunities; + CirclesList? connectedCircles; + FollowsListsList? followLists; + CommunityMembershipList? communitiesMemberships; + CommunityInviteList? communitiesInvites; static final navigationUsersFactory = UserFactory( cache: @@ -67,11 +67,9 @@ class User extends UpdatableModel { factory User.fromJson(Map json, {bool storeInSessionCache = false, bool storeInMaxSessionCache = false}) { - if (json == null) return null; - int userId = json['id']; - User user = maxSessionUsersFactory.getItemWithIdFromCache(userId) ?? + User? user = maxSessionUsersFactory.getItemWithIdFromCache(userId) ?? navigationUsersFactory.getItemWithIdFromCache(userId) ?? sessionUsersFactory.getItemWithIdFromCache(userId); if (user != null) { @@ -120,16 +118,16 @@ class User extends UpdatableModel { 'is_member_of_communities': isMemberOfCommunities, 'connected_circles': connectedCircles?.circles ?.map((Circle circle) => circle.toJson()) - ?.toList(), + .toList(), 'follow_lists': followLists?.lists ?.map((FollowsList followList) => followList.toJson()) - ?.toList(), + .toList(), 'communities_memberships': communitiesMemberships?.communityMemberships ?.map((CommunityMembership membership) => membership.toJson()) - ?.toList(), + .toList(), 'communities_invites': communitiesInvites?.communityInvites ?.map((CommunityInvite invite) => invite.toJson()) - ?.toList(), + .toList(), }; } @@ -191,7 +189,7 @@ class User extends UpdatableModel { if (json.containsKey('email')) email = json['email']; if (json.containsKey('profile')) { if (profile != null) { - profile.updateFromJson(json['profile']); + profile!.updateFromJson(json['profile']); } else { profile = navigationUsersFactory.parseUserProfile(json['profile']); } @@ -201,7 +199,7 @@ class User extends UpdatableModel { } if (json.containsKey('notifications_settings')) { if (notificationsSettings != null) { - notificationsSettings.updateFromJson(json['notifications_settings']); + notificationsSettings!.updateFromJson(json['notifications_settings']); } else { notificationsSettings = navigationUsersFactory .parseUserNotificationsSettings(json['notifications_settings']); @@ -268,16 +266,16 @@ class User extends UpdatableModel { } } - String getEmail() { + String? getEmail() { return this.email; } bool hasProfileLocation() { - return profile.hasLocation(); + return profile?.hasLocation() ?? false; } bool hasProfileUrl() { - return profile.hasUrl(); + return profile?.hasUrl() ?? false; } bool hasAge() { @@ -285,57 +283,57 @@ class User extends UpdatableModel { } bool hasProfileAvatar() { - return this.profile.avatar != null; + return this.profile?.avatar != null; } bool hasProfileCover() { - return this.profile.cover != null; + return this.profile?.cover != null; } - String getProfileAvatar() { + String? getProfileAvatar() { return this.profile?.avatar; } - String getProfileName() { - return this.profile.name; + String? getProfileName() { + return this.profile?.name; } - String getProfileCover() { - return this.profile.cover; + String? getProfileCover() { + return this.profile?.cover; } - String getProfileBio() { - return this.profile.bio; + String? getProfileBio() { + return this.profile?.bio; } bool getProfileFollowersCountVisible() { - return this.profile.followersCountVisible; + return this.profile?.followersCountVisible ?? false; } bool getProfileCommunityPostsVisible() { - return this.profile.communityPostsVisible; + return this.profile?.communityPostsVisible ?? false; } - String getProfileUrl() { - return this.profile.url; + String? getProfileUrl() { + return this.profile?.url; } - String getProfileLocation() { - return this.profile.location; + String? getProfileLocation() { + return this.profile?.location; } - List getProfileBadges() { - return this.profile.badges; + List? getProfileBadges() { + return this.profile?.badges; } - Badge getDisplayedProfileBadge() { - return getProfileBadges().first; + Badge? getDisplayedProfileBadge() { + return getProfileBadges()?.first; } bool hasProfileBadges() { return this.profile != null && - this.profile.badges != null && - this.profile.badges.length > 0; + this.profile!.badges != null && + this.profile!.badges!.length > 0; } bool hasLanguage() { @@ -347,59 +345,57 @@ class User extends UpdatableModel { } bool hasFollowLists() { - return followLists != null && followLists.lists.length > 0; + return followLists != null && followLists!.lists!.length > 0; } bool isAdministratorOfCommunity(Community community) { - CommunityMembership membership = getMembershipForCommunity(community); - if (membership == null) return false; - return membership.isAdministrator; + CommunityMembership? membership = getMembershipForCommunity(community); + return membership?.isAdministrator ?? false; } bool isModeratorOfCommunity(Community community) { - CommunityMembership membership = getMembershipForCommunity(community); - if (membership == null) return false; - return membership.isModerator; + CommunityMembership? membership = getMembershipForCommunity(community); + return membership?.isModerator ?? false; } bool isMemberOfCommunity(Community community) { return getMembershipForCommunity(community) != null; } - CommunityMembership getMembershipForCommunity(Community community) { + CommunityMembership? getMembershipForCommunity(Community community) { if (communitiesMemberships == null) return null; - int membershipIndex = communitiesMemberships.communityMemberships - .indexWhere((CommunityMembership communityMembership) { + int? membershipIndex = communitiesMemberships?.communityMemberships + ?.indexWhere((CommunityMembership communityMembership) { return communityMembership.userId == this.id && communityMembership.communityId == community.id; }); - if (membershipIndex < 0) return null; + if (membershipIndex == null || membershipIndex < 0) return null; - return communitiesMemberships.communityMemberships[membershipIndex]; + return communitiesMemberships?.communityMemberships?[membershipIndex]; } bool isInvitedToCommunity(Community community) { - CommunityInvite invite = getInviteForCommunity(community); + CommunityInvite? invite = getInviteForCommunity(community); return invite != null; } - CommunityInvite getInviteForCommunity(Community community) { + CommunityInvite? getInviteForCommunity(Community community) { if (communitiesInvites == null) return null; - int inviteIndex = communitiesInvites.communityInvites - .indexWhere((CommunityInvite communityInvite) { + int? inviteIndex = communitiesInvites?.communityInvites + ?.indexWhere((CommunityInvite communityInvite) { return communityInvite.communityId == community.id; }); - if (inviteIndex < 0) return null; + if (inviteIndex == null || inviteIndex < 0) return null; - return communitiesInvites.communityInvites[inviteIndex]; + return communitiesInvites?.communityInvites?[inviteIndex]; } bool hasUnreadNotifications() { - return unreadNotificationsCount != null && unreadNotificationsCount > 0; + return unreadNotificationsCount != null && unreadNotificationsCount! > 0; } void resetUnreadNotificationsCount() { @@ -409,33 +405,33 @@ class User extends UpdatableModel { void incrementUnreadNotificationsCount() { if (this.unreadNotificationsCount != null) { - this.unreadNotificationsCount += 1; + this.unreadNotificationsCount = this.unreadNotificationsCount! + 1; notifyUpdate(); } } void incrementFollowersCount() { if (this.followersCount != null) { - this.followersCount += 1; + this.followersCount = this.followersCount! + 1; notifyUpdate(); } } void decrementFollowersCount() { - if (this.followersCount != null && this.followersCount > 0) { - this.followersCount -= 1; + if (this.followersCount != null && this.followersCount! > 0) { + this.followersCount = this.followersCount! + 1; notifyUpdate(); } } bool hasPendingCommunitiesModeratedObjects() { return pendingCommunitiesModeratedObjectsCount != null && - pendingCommunitiesModeratedObjectsCount > 0; + pendingCommunitiesModeratedObjectsCount! > 0; } bool hasActiveModerationPenaltiesCount() { return activeModerationPenaltiesCount != null && - activeModerationPenaltiesCount > 0; + activeModerationPenaltiesCount! > 0; } void setIsReported(isReported) { @@ -468,9 +464,10 @@ class User extends UpdatableModel { bool _canDisableOrEnableComments = false; if (post.hasCommunity()) { - Community postCommunity = post.community; + Community? postCommunity = post.community; - if (postCommunity.isAdministrator(loggedInUser) || + if (postCommunity == null || + postCommunity.isAdministrator(loggedInUser) || postCommunity.isModerator(loggedInUser)) { _canDisableOrEnableComments = true; } @@ -483,9 +480,10 @@ class User extends UpdatableModel { bool _canCloseOrOpenPost = false; if (post.hasCommunity()) { - Community postCommunity = post.community; + Community? postCommunity = post.community; - if (postCommunity.isAdministrator(loggedInUser) || + if (postCommunity == null || + postCommunity.isAdministrator(loggedInUser) || postCommunity.isModerator(loggedInUser)) { _canCloseOrOpenPost = true; } @@ -518,7 +516,7 @@ class User extends UpdatableModel { } bool isCreatorOfCommunity(Community community) { - return community.isCreator; + return community.isCreator ?? false; } bool canChangeDetailsOfCommunity(Community community) { @@ -544,7 +542,7 @@ class User extends UpdatableModel { } bool canAddOrRemoveAdministratorsInCommunity(Community community) { - return community.isCreator; + return community.isCreator ?? false; } bool canCommentOnPostWithDisabledComments(Post post) { @@ -552,9 +550,10 @@ class User extends UpdatableModel { bool _canComment = false; if (post.hasCommunity()) { - Community postCommunity = post.community; + Community? postCommunity = post.community; - if (postCommunity.isAdministrator(loggedInUser) || + if (postCommunity == null || + postCommunity.isAdministrator(loggedInUser) || postCommunity.isModerator(loggedInUser)) { _canComment = true; } @@ -562,15 +561,15 @@ class User extends UpdatableModel { return _canComment; } - bool isStaffForCommunity(Community community) { + bool isStaffForCommunity(Community? community) { User loggedInUser = this; bool loggedInUserIsCommunityAdministrator = false; bool loggedInUserIsCommunityModerator = false; loggedInUserIsCommunityAdministrator = - community.isAdministrator(loggedInUser); + community?.isAdministrator(loggedInUser) ?? false; - loggedInUserIsCommunityModerator = community.isModerator(loggedInUser); + loggedInUserIsCommunityModerator = community?.isModerator(loggedInUser) ?? false; return loggedInUserIsCommunityModerator || loggedInUserIsCommunityAdministrator; @@ -598,7 +597,7 @@ class User extends UpdatableModel { User loggedInUser = this; bool loggedInUserIsPostCreator = loggedInUser.id == post.getCreatorId(); - return loggedInUserIsPostCreator && !post.isClosed; + return loggedInUserIsPostCreator && !(post.isClosed ?? false); } bool canTranslatePostComment(PostComment postComment, Post post) { @@ -606,23 +605,23 @@ class User extends UpdatableModel { language?.code == null) return false; return postComment.hasLanguage() && - postComment.getLanguage().code != language.code; + postComment.getLanguage()?.code != language!.code; } bool canTranslatePost(Post post) { if ((!post.hasCommunity() && post.isEncircledPost()) || language?.code == null) return false; - return post.hasLanguage() && post.getLanguage().code != language.code; + return post.hasLanguage() && post.getLanguage()?.code != language!.code; } bool canEditPostComment(PostComment postComment, Post post) { User loggedInUser = this; - User postCommenter = postComment.commenter; + User? postCommenter = postComment.commenter; bool loggedInUserIsStaffForCommunity = false; - bool loggedInUserIsCommenter = loggedInUser.id == postCommenter.id; + bool loggedInUserIsCommenter = loggedInUser.id == postCommenter?.id; bool loggedInUserIsCommenterForOpenPost = - loggedInUserIsCommenter && !post.isClosed && post.areCommentsEnabled; + loggedInUserIsCommenter && !(post.isClosed ?? false) && (post.areCommentsEnabled ?? false); if (post.hasCommunity()) { loggedInUserIsStaffForCommunity = isStaffForCommunity(post.community); @@ -634,9 +633,9 @@ class User extends UpdatableModel { bool canReportPostComment(PostComment postComment) { User loggedInUser = this; - User postCommenter = postComment.commenter; + User? postCommenter = postComment.commenter; - return loggedInUser.id != postCommenter.id; + return loggedInUser.id != postCommenter?.id; } bool canReplyPostComment(PostComment postComment) { @@ -645,13 +644,13 @@ class User extends UpdatableModel { bool canDeletePostComment(Post post, PostComment postComment) { User loggedInUser = this; - User postCommenter = postComment.commenter; + User? postCommenter = postComment.commenter; bool loggedInUserIsPostCreator = loggedInUser.id == post.getCreatorId(); bool userIsCreatorOfNonCommunityPost = loggedInUserIsPostCreator && !post.hasCommunity(); bool loggedInUserIsStaffForCommunity = false; bool loggedInUserIsCommenterForOpenPost = - (loggedInUser.id == postCommenter.id) && !post.isClosed; + (loggedInUser.id == postCommenter?.id) && !(post.isClosed ?? false); if (post.hasCommunity()) { loggedInUserIsStaffForCommunity = @@ -715,43 +714,43 @@ class UserFactory extends UpdatableModelFactory { followLists: parseFollowsLists(json['follow_lists'])); } - CommunityMembershipList parseMemberships(List membershipsData) { + CommunityMembershipList? parseMemberships(List? membershipsData) { if (membershipsData == null) return null; return CommunityMembershipList.fromJson(membershipsData); } - CommunityInviteList parseInvites(List invitesData) { + CommunityInviteList? parseInvites(List? invitesData) { if (invitesData == null) return null; return CommunityInviteList.fromJson(invitesData); } - UserProfile parseUserProfile(Map profile) { + UserProfile? parseUserProfile(Map? profile) { if (profile == null) return null; return UserProfile.fromJSON(profile); } - UserNotificationsSettings parseUserNotificationsSettings( - Map notificationsSettings) { + UserNotificationsSettings? parseUserNotificationsSettings( + Map? notificationsSettings) { if (notificationsSettings == null) return null; return UserNotificationsSettings.fromJSON(notificationsSettings); } - CirclesList parseCircles(List circlesData) { + CirclesList? parseCircles(List? circlesData) { if (circlesData == null) return null; return CirclesList.fromJson(circlesData); } - FollowsListsList parseFollowsLists(List followsListsData) { + FollowsListsList? parseFollowsLists(List? followsListsData) { if (followsListsData == null) return null; return FollowsListsList.fromJson(followsListsData); } - Language parseLanguage(Map languageData) { + Language? parseLanguage(Map? languageData) { if (languageData == null) return null; return Language.fromJson(languageData); } - DateTime parseDateJoined(String dateJoined) { + DateTime? parseDateJoined(String? dateJoined) { if (dateJoined == null) return null; return DateTime.parse(dateJoined).toLocal(); } @@ -776,10 +775,10 @@ class UserVisibility { static values() => _values; - static UserVisibility parse(String string) { + static UserVisibility? parse(String? string) { if (string == null) return null; - UserVisibility userVisibility; + UserVisibility? userVisibility; for (var type in _values) { if (string == type.code) { userVisibility = type; diff --git a/lib/models/user_invite.dart b/lib/models/user_invite.dart index 68e32694d..971131346 100644 --- a/lib/models/user_invite.dart +++ b/lib/models/user_invite.dart @@ -3,13 +3,13 @@ import 'package:Okuna/models/user.dart'; import 'package:dcache/dcache.dart'; class UserInvite extends UpdatableModel { - final int id; - String email; - final DateTime created; - User createdUser; - String nickname; - final String token; - bool isInviteEmailSent; + final int? id; + String? email; + final DateTime? created; + User? createdUser; + String? nickname; + final String? token; + bool? isInviteEmailSent; static const String IOS_DOWNLOAD_LINK = 'https://testflight.apple.com/join/XniAjdyF'; static const String TESTFLIGHT_DOWNLOAD_LINK = 'https://itunes.apple.com/us/app/testflight/id899247664'; @@ -17,7 +17,7 @@ class UserInvite extends UpdatableModel { static const INVITE_LINK = '{apiURL}api/auth/invite?token={token}'; static convertUserInviteStatusToBool(UserInviteFilterByStatus value) { - bool isPending; + bool? isPending; switch (value) { case UserInviteFilterByStatus.all: isPending = null; @@ -68,12 +68,12 @@ class UserInvite extends UpdatableModel { class UserInviteFactory extends UpdatableModelFactory { @override - SimpleCache cache = + SimpleCache? cache = LruCache(storage: UpdatableModelSimpleStorage(size: 10)); @override UserInvite makeFromJson(Map json) { - DateTime created; + DateTime? created; var createdData = json['created']; if (createdData != null) created = DateTime.parse(createdData).toLocal(); @@ -87,7 +87,7 @@ class UserInviteFactory extends UpdatableModelFactory { isInviteEmailSent: json['is_invite_email_sent']); } - User parseUser(Map userData) { + User? parseUser(Map? userData) { if (userData == null) return null; return User.fromJson(userData); } diff --git a/lib/models/user_invites_list.dart b/lib/models/user_invites_list.dart index b45173b58..a5c85d44e 100644 --- a/lib/models/user_invites_list.dart +++ b/lib/models/user_invites_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/user_invite.dart'; class UserInvitesList { - final List invites; + final List? invites; UserInvitesList({ this.invites, diff --git a/lib/models/user_notifications_settings.dart b/lib/models/user_notifications_settings.dart index d98c684b2..628f6c899 100644 --- a/lib/models/user_notifications_settings.dart +++ b/lib/models/user_notifications_settings.dart @@ -1,19 +1,19 @@ class UserNotificationsSettings { - final int id; - bool postCommentNotifications; - bool postCommentReactionNotifications; - bool postCommentReplyNotifications; - bool postCommentUserMentionNotifications; - bool postUserMentionNotifications; - bool postReactionNotifications; - bool followNotifications; - bool followRequestNotifications; - bool followRequestApprovedNotifications; - bool connectionRequestNotifications; - bool connectionConfirmedNotifications; - bool communityInviteNotifications; - bool communityNewPostNotifications; - bool userNewPostNotifications; + final int? id; + bool? postCommentNotifications; + bool? postCommentReactionNotifications; + bool? postCommentReplyNotifications; + bool? postCommentUserMentionNotifications; + bool? postUserMentionNotifications; + bool? postReactionNotifications; + bool? followNotifications; + bool? followRequestNotifications; + bool? followRequestApprovedNotifications; + bool? connectionRequestNotifications; + bool? connectionConfirmedNotifications; + bool? communityInviteNotifications; + bool? communityNewPostNotifications; + bool? userNewPostNotifications; UserNotificationsSettings( {this.id, diff --git a/lib/models/user_profile.dart b/lib/models/user_profile.dart index d220d3817..1aee9fcaf 100644 --- a/lib/models/user_profile.dart +++ b/lib/models/user_profile.dart @@ -2,16 +2,16 @@ import 'package:Okuna/models/badge.dart'; import 'package:Okuna/models/badges_list.dart'; class UserProfile { - final int id; - String name; - String avatar; - String cover; - String bio; - String url; - String location; - bool followersCountVisible; - bool communityPostsVisible; - List badges; + final int? id; + String? name; + String? avatar; + String? cover; + String? bio; + String? url; + String? location; + bool? followersCountVisible; + bool? communityPostsVisible; + List? badges; UserProfile({ this.id, @@ -50,13 +50,13 @@ class UserProfile { 'bio': bio, 'url': url, 'location': location, - 'badges': badges?.map((Badge badge) => badge.toJson())?.toList(), + 'badges': badges?.map((Badge badge) => badge.toJson()).toList(), 'followers_count_visible': followersCountVisible, 'community_posts_visible': communityPostsVisible, }; } - static List parseBadges(List badges) { + static List? parseBadges(List? badges) { if (badges == null) return null; return BadgesList.fromJson(badges).badges; } diff --git a/lib/models/users_list.dart b/lib/models/users_list.dart index cc446da27..5adb406e0 100644 --- a/lib/models/users_list.dart +++ b/lib/models/users_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/user.dart'; class UsersList { - final List users; + final List? users; UsersList({ this.users, diff --git a/lib/models/video_format.dart b/lib/models/video_format.dart index 89c32206d..ae6a42738 100644 --- a/lib/models/video_format.dart +++ b/lib/models/video_format.dart @@ -1,11 +1,11 @@ class OBVideoFormat { - final int id; - final double progress; - final double duration; - final String format; - final String file; + final int? id; + final double? progress; + final double? duration; + final String? format; + final String? file; - OBVideoFormatType type; + OBVideoFormatType? type; OBVideoFormat( {this.id, this.progress, this.duration, this.format, this.file}) { @@ -50,10 +50,10 @@ class OBVideoFormatType { static values() => _values; - static OBVideoFormatType parse(String string) { + static OBVideoFormatType? parse(String? string) { if (string == null) return null; - OBVideoFormatType videoFormatType; + OBVideoFormatType? videoFormatType; for (var type in _values) { if (string == type.code) { videoFormatType = type; diff --git a/lib/models/video_formats_list.dart b/lib/models/video_formats_list.dart index d4c9edebc..8655372b5 100644 --- a/lib/models/video_formats_list.dart +++ b/lib/models/video_formats_list.dart @@ -1,7 +1,7 @@ import 'package:Okuna/models/video_format.dart'; class OBVideoFormatsList { - final List videoFormats; + final List? videoFormats; OBVideoFormatsList({ this.videoFormats, diff --git a/lib/pages/auth/create_account/accept_step.dart b/lib/pages/auth/create_account/accept_step.dart index a3616e683..2ec4b711e 100644 --- a/lib/pages/auth/create_account/accept_step.dart +++ b/lib/pages/auth/create_account/accept_step.dart @@ -16,8 +16,8 @@ class OBAcceptStepPage extends StatefulWidget { class OBAcceptStepPageState extends State { final GlobalKey _formKey = new GlobalKey(); - CreateAccountBloc _createAccountBloc; - LocalizationService _localizationService; + late CreateAccountBloc _createAccountBloc; + late LocalizationService _localizationService; @override void initState() { @@ -105,7 +105,7 @@ class OBAcceptStepPageState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__create_acc__previous'); diff --git a/lib/pages/auth/create_account/blocs/create_account.dart b/lib/pages/auth/create_account/blocs/create_account.dart index 4c42a4e07..74c49d6fa 100644 --- a/lib/pages/auth/create_account/blocs/create_account.dart +++ b/lib/pages/auth/create_account/blocs/create_account.dart @@ -9,9 +9,9 @@ import 'package:rxdart/rxdart.dart'; import 'dart:io'; class CreateAccountBloc { - LocalizationService _localizationService; - AuthApiService _authApiService; - UserService _userService; + late LocalizationService _localizationService; + late AuthApiService _authApiService; + late UserService _userService; // Serves as a snapshot to the data final userRegistrationData = UserRegistrationData(); @@ -28,20 +28,20 @@ class CreateAccountBloc { // Create account begins - Stream get createAccountInProgress => + Stream get createAccountInProgress => _createAccountInProgressSubject.stream; - final _createAccountInProgressSubject = ReplaySubject(); + final _createAccountInProgressSubject = ReplaySubject(); - Stream get createAccountErrorFeedback => + Stream get createAccountErrorFeedback => _createAccountErrorFeedbackSubject.stream; - final _createAccountErrorFeedbackSubject = ReplaySubject(); + final _createAccountErrorFeedbackSubject = ReplaySubject(); - Stream get tokenValidationErrorFeedback => + Stream get tokenValidationErrorFeedback => _tokenValidationErrorFeedbackSubject.stream; - final _tokenValidationErrorFeedbackSubject = ReplaySubject(); + final _tokenValidationErrorFeedbackSubject = ReplaySubject(); // Create account ends @@ -81,7 +81,7 @@ class CreateAccountBloc { // Legal Age Confirmation bool isOfLegalAge() { - return userRegistrationData.isOfLegalAge; + return userRegistrationData.isOfLegalAge ?? false; } void _onLegalAgeConfirmationChange(bool isOfLegalAge) { @@ -95,8 +95,7 @@ class CreateAccountBloc { // Legal Age Confirmation bool areGuidelinesAccepted() { - if (userRegistrationData.areGuidelinesAccepted == null) return false; - return userRegistrationData.areGuidelinesAccepted; + return userRegistrationData.areGuidelinesAccepted ?? false; } void setAreGuidelinesAcceptedConfirmation(bool areGuidelinesAccepted) { @@ -109,7 +108,7 @@ class CreateAccountBloc { return userRegistrationData.name != null; } - String getName() { + String? getName() { return userRegistrationData.name; } @@ -117,7 +116,7 @@ class CreateAccountBloc { _nameSubject.add(name); } - void _onNameChange(String name) { + void _onNameChange(String? name) { if (name == null) return; userRegistrationData.name = name; } @@ -134,11 +133,11 @@ class CreateAccountBloc { return userRegistrationData.username != null; } - String getUsername() { + String? getUsername() { return userRegistrationData.username; } - void setUsername(String username) async { + void setUsername(String? username) async { if (username == null) return; userRegistrationData.username = username; } @@ -155,7 +154,7 @@ class CreateAccountBloc { return userRegistrationData.email != null; } - String getEmail() { + String? getEmail() { return userRegistrationData.email; } @@ -163,7 +162,7 @@ class CreateAccountBloc { _emailSubject.add(email); } - void _onEmailChange(String email) { + void _onEmailChange(String? email) { if (email == null) return; userRegistrationData.email = email; } @@ -180,11 +179,11 @@ class CreateAccountBloc { return userRegistrationData.password != null; } - String getPassword() { + String? getPassword() { return userRegistrationData.password; } - void _onPasswordChange(String password) { + void _onPasswordChange(String? password) { if (password == null) return; userRegistrationData.password = password; } @@ -205,7 +204,7 @@ class CreateAccountBloc { return userRegistrationData.avatar != null; } - File getAvatar() { + File? getAvatar() { return userRegistrationData.avatar; } @@ -213,7 +212,7 @@ class CreateAccountBloc { _avatarSubject.add(avatar); } - void _onAvatarChange(File avatar) { + void _onAvatarChange(File? avatar) { if (avatar == null) { // Avatar is optional, therefore no feedback to user. return; @@ -232,7 +231,7 @@ class CreateAccountBloc { return userRegistrationData.token != null; } - String getToken() { + String? getToken() { return userRegistrationData.token; } @@ -240,7 +239,7 @@ class CreateAccountBloc { registrationTokenSubject.add(token); } - void _onTokenChange(String token) { + void _onTokenChange(String? token) { if (token == null) return; userRegistrationData.token = token; } @@ -256,7 +255,7 @@ class CreateAccountBloc { return passwordResetData.passwordResetToken != null; } - String getPasswordResetToken() { + String? getPasswordResetToken() { return passwordResetData.passwordResetToken; } @@ -264,7 +263,7 @@ class CreateAccountBloc { _passwordResetTokenSubject.add(passwordResetToken); } - void _onPasswordResetTokenChange(String passwordResetToken) { + void _onPasswordResetTokenChange(String? passwordResetToken) { if (passwordResetToken == null) return; passwordResetData.passwordResetToken = passwordResetToken; } @@ -286,13 +285,13 @@ class CreateAccountBloc { try { HttpieStreamedResponse response = await _authApiService.createUser( - email: userRegistrationData.email, - isOfLegalAge: true, - name: userRegistrationData.name, - username: userRegistrationData.username, - token: userRegistrationData.token, - password: userRegistrationData.password, - areGuidelinesAccepted: true, + email: userRegistrationData.email ?? '', + isOfLegalAge: true, // TODO: probably shouldn't always be true + name: userRegistrationData.name ?? '', + username: userRegistrationData.username ?? '', + token: userRegistrationData.token ?? '', + password: userRegistrationData.password ?? '', + areGuidelinesAccepted: true, // TODO: probably shouldn't always be true avatar: userRegistrationData.avatar); if (!response.isCreated()) throw HttpieRequestError(response); @@ -305,8 +304,8 @@ class CreateAccountBloc { if (error is HttpieConnectionRefusedError) { _onCreateAccountValidationError(error.toHumanReadableMessage()); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _onCreateAccountValidationError(errorMessage); + String? errorMessage = await error.toHumanReadableMessage(); + _onCreateAccountValidationError(errorMessage ?? 'Unknown error'); } else { _onCreateAccountValidationError('Unknown error'); rethrow; @@ -344,16 +343,16 @@ class CreateAccountBloc { } class UserRegistrationData { - String token; - String name; - bool isOfLegalAge; - bool areGuidelinesAccepted; - String username; - String email; - String password; - File avatar; + String? token; + String? name; + bool? isOfLegalAge; + bool? areGuidelinesAccepted; + String? username; + String? email; + String? password; + File? avatar; } class PasswordResetData { - String passwordResetToken; + String? passwordResetToken; } diff --git a/lib/pages/auth/create_account/create_account.dart b/lib/pages/auth/create_account/create_account.dart index 7235ee8e5..a3f94001d 100644 --- a/lib/pages/auth/create_account/create_account.dart +++ b/lib/pages/auth/create_account/create_account.dart @@ -21,17 +21,17 @@ class OBAuthCreateAccountPage extends StatefulWidget { class OBAuthCreateAccountPageState extends State { final GlobalKey _formKey = GlobalKey(); - CreateAccountBloc _createAccountBloc; - LocalizationService _localizationService; - ValidationService _validationService; - ToastService _toastService; + late CreateAccountBloc _createAccountBloc; + late LocalizationService _localizationService; + late ValidationService _validationService; + late ToastService _toastService; TextEditingController _linkController = TextEditingController(); - bool _tokenIsInvalid; - bool _tokenValidationInProgress; + late bool _tokenIsInvalid; + late bool _tokenValidationInProgress; - CancelableOperation _tokenValidationOperation; + CancelableOperation? _tokenValidationOperation; @override void initState() { @@ -99,7 +99,7 @@ class OBAuthCreateAccountPageState extends State { } Future _validateForm() async { - if (_formKey.currentState.validate()) { + if (_formKey.currentState?.validate() == true) { bool tokenIsValid = await _validateToken(); if (!tokenIsValid) _setTokenIsInvalid(true); return tokenIsValid; @@ -124,7 +124,7 @@ class OBAuthCreateAccountPageState extends State { final params = Uri.parse(uri).queryParametersAll; var token = ''; if (params.containsKey('token')) { - token = params['token'][0]; + token = params['token']![0]; } else { token = uri.split('?token=')[1]; } @@ -145,7 +145,7 @@ class OBAuthCreateAccountPageState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__create_acc__previous'); @@ -173,7 +173,7 @@ class OBAuthCreateAccountPageState extends State { ); } - Widget _buildPasteRegisterLink({@required BuildContext context}) { + Widget _buildPasteRegisterLink({required BuildContext context}) { String pasteLinkText = _localizationService.trans('auth__create_acc__paste_link'); @@ -206,9 +206,9 @@ class OBAuthCreateAccountPageState extends State { child: OBAuthTextField( autocorrect: false, hintText: '', - validator: (String link) { - String validateLink = _validationService - .validateUserRegistrationLink(link.trim()); + validator: (String? link) { + String? validateLink = _validationService + .validateUserRegistrationLink(link?.trim()); if (validateLink != null) { return validateLink; } @@ -227,7 +227,7 @@ class OBAuthCreateAccountPageState extends State { ); } - Widget _buildRequestInvite({@required BuildContext context}) { + Widget _buildRequestInvite({required BuildContext context}) { String requestInviteText = _localizationService.trans('auth__create_acc__request_invite'); @@ -272,7 +272,7 @@ class OBAuthCreateAccountPageState extends State { _setTokenIsInvalid(bool tokenIsInvalid) { setState(() { _tokenIsInvalid = tokenIsInvalid; - _formKey.currentState.validate(); + _formKey.currentState?.validate(); }); } @@ -287,8 +287,8 @@ class OBAuthCreateAccountPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/auth/create_account/done_step/done_step.dart b/lib/pages/auth/create_account/done_step/done_step.dart index 6a5d7ba5b..a5b27b26e 100644 --- a/lib/pages/auth/create_account/done_step/done_step.dart +++ b/lib/pages/auth/create_account/done_step/done_step.dart @@ -13,8 +13,8 @@ class OBAuthDonePage extends StatefulWidget { } class OBAuthDonePageState extends State { - LocalizationService localizationService; - CreateAccountBloc createAccountBloc; + late LocalizationService localizationService; + late CreateAccountBloc createAccountBloc; bool _isCommunitySelectionInProgress = false; @override @@ -110,7 +110,7 @@ class OBAuthDonePageState extends State { }); } - Widget _buildContinueButton({@required BuildContext context}) { + Widget _buildContinueButton({required BuildContext context}) { String buttonText = localizationService.auth__login__login; return OBSuccessButton( diff --git a/lib/pages/auth/create_account/email_step.dart b/lib/pages/auth/create_account/email_step.dart index 58569a327..408ff2945 100644 --- a/lib/pages/auth/create_account/email_step.dart +++ b/lib/pages/auth/create_account/email_step.dart @@ -17,14 +17,14 @@ class OBAuthEmailStepPage extends StatefulWidget { } class OBAuthEmailStepPageState extends State { - bool _emailCheckInProgress; - bool _emailTaken; + late bool _emailCheckInProgress; + bool? _emailTaken; final GlobalKey _formKey = GlobalKey(); - CreateAccountBloc _createAccountBloc; - LocalizationService _localizationService; - ValidationService _validationService; - ToastService _toastService; + late CreateAccountBloc _createAccountBloc; + late LocalizationService _localizationService; + late ValidationService _validationService; + late ToastService _toastService; TextEditingController _emailController = TextEditingController(); @@ -80,7 +80,7 @@ class OBAuthEmailStepPageState extends State { bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } void _setEmailTaken(bool isEmailTaken) { @@ -107,7 +107,7 @@ class OBAuthEmailStepPageState extends State { void onPressedNextStep(BuildContext context) async { await _checkEmailAvailable(_emailController.text.trim(), context); bool isEmailValid = _validateForm(); - if (isEmailValid && !_emailTaken) { + if (isEmailValid && !(_emailTaken ?? true)) { setState(() { _createAccountBloc.setEmail(_emailController.text.trim()); Navigator.pushNamed(context, '/auth/username_step'); @@ -129,7 +129,7 @@ class OBAuthEmailStepPageState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__create_acc__previous'); return OBSecondaryButton( @@ -156,7 +156,7 @@ class OBAuthEmailStepPageState extends State { ); } - Widget _buildWhatYourEmail({@required BuildContext context}) { + Widget _buildWhatYourEmail({required BuildContext context}) { String whatEmailText = _localizationService.trans('auth__create_acc__what_email'); @@ -195,10 +195,10 @@ class OBAuthEmailStepPageState extends State { child: OBAuthTextField( autocorrect: false, hintText: emailInputPlaceholder, - validator: (String email) { - String validateEMail = _validationService.validateUserEmail(email.trim()); + validator: (String? email) { + String? validateEMail = _validationService.validateUserEmail(email?.trim()); if (validateEMail != null) return validateEMail; - if (_emailTaken != null && _emailTaken) { + if (_emailTaken != null && _emailTaken!) { return errorEmailTaken; } }, diff --git a/lib/pages/auth/create_account/get_started.dart b/lib/pages/auth/create_account/get_started.dart index a5b902649..433466813 100644 --- a/lib/pages/auth/create_account/get_started.dart +++ b/lib/pages/auth/create_account/get_started.dart @@ -14,7 +14,7 @@ class OBAuthGetStartedPage extends StatefulWidget { } class OBAuthGetStartedPageState extends State { - LocalizationService _localizationService; + late LocalizationService _localizationService; @override void initState() { @@ -97,7 +97,7 @@ class OBAuthGetStartedPageState extends State { } Widget _buildNextButton( - {@required BuildContext context, @required String text}) { + {required BuildContext context, required String text}) { return OBSuccessButton( minWidth: double.infinity, size: OBButtonSize.large, @@ -109,7 +109,7 @@ class OBAuthGetStartedPageState extends State { } Widget _buildPreviousButton( - {@required BuildContext context, @required String text}) { + {required BuildContext context, required String text}) { return OBSecondaryButton( isFullWidth: true, isLarge: true, diff --git a/lib/pages/auth/create_account/legal_step.dart b/lib/pages/auth/create_account/legal_step.dart index b4ac98cd5..50354bb0c 100644 --- a/lib/pages/auth/create_account/legal_step.dart +++ b/lib/pages/auth/create_account/legal_step.dart @@ -18,8 +18,8 @@ class OBLegalStepPage extends StatefulWidget { class OBLegalStepPageState extends State { final GlobalKey _formKey = new GlobalKey(); - LocalizationService _localizationService; - NavigationService _navigationService; + late LocalizationService _localizationService; + late NavigationService _navigationService; @override void initState() { @@ -140,9 +140,9 @@ class OBLegalStepPageState extends State { } Widget _buildDocument( - {@required String icon, - @required String title, - @required VoidCallback onPressed}) { + {required String icon, + required String title, + required VoidCallback onPressed}) { return GestureDetector( onTap: onPressed, child: Container( @@ -191,7 +191,7 @@ class OBLegalStepPageState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__create_acc__previous'); diff --git a/lib/pages/auth/create_account/name_step.dart b/lib/pages/auth/create_account/name_step.dart index 5bcd3a4b6..200e04824 100644 --- a/lib/pages/auth/create_account/name_step.dart +++ b/lib/pages/auth/create_account/name_step.dart @@ -17,9 +17,9 @@ class OBAuthNameStepPage extends StatefulWidget { class OBAuthNameStepPageState extends State { final GlobalKey _formKey = GlobalKey(); - CreateAccountBloc _createAccountBloc; - LocalizationService _localizationService; - ValidationService _validationService; + late CreateAccountBloc _createAccountBloc; + late LocalizationService _localizationService; + late ValidationService _validationService; TextEditingController _nameController = TextEditingController(); @@ -83,7 +83,7 @@ class OBAuthNameStepPageState extends State { bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } void onPressedNextStep() { @@ -96,7 +96,7 @@ class OBAuthNameStepPageState extends State { } } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__create_acc__previous'); return OBSecondaryButton( @@ -123,7 +123,7 @@ class OBAuthNameStepPageState extends State { ); } - Widget _buildWhatYourName({@required BuildContext context}) { + Widget _buildWhatYourName({required BuildContext context}) { String whatNameText = _localizationService.trans('auth__create_acc__what_name'); @@ -161,8 +161,8 @@ class OBAuthNameStepPageState extends State { textCapitalization: TextCapitalization.words, autocorrect: false, hintText: nameInputPlaceholder, - validator: (String name) { - String validateName = _validationService + validator: (String? name) { + String? validateName = _validationService .validateUserProfileName(name); if (validateName != null) return validateName; }, diff --git a/lib/pages/auth/create_account/password_step.dart b/lib/pages/auth/create_account/password_step.dart index f8c242e8d..df806649b 100644 --- a/lib/pages/auth/create_account/password_step.dart +++ b/lib/pages/auth/create_account/password_step.dart @@ -16,10 +16,10 @@ class OBAuthPasswordStepPage extends StatefulWidget { } class OBAuthPasswordStepPageState extends State { - bool passwordIsVisible; - CreateAccountBloc createAccountBloc; - LocalizationService localizationService; - ValidationService validationService; + late bool passwordIsVisible; + late CreateAccountBloc createAccountBloc; + late LocalizationService localizationService; + late ValidationService validationService; static const passwordMaxLength = ValidationService.PASSWORD_MAX_LENGTH; static const passwordMinLength = ValidationService.PASSWORD_MIN_LENGTH; final GlobalKey _formKey = GlobalKey(); @@ -88,7 +88,7 @@ class OBAuthPasswordStepPageState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } void onPressedNextStep() { @@ -101,7 +101,7 @@ class OBAuthPasswordStepPageState extends State { } } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = localizationService.trans('auth__create_acc__previous'); return OBSecondaryButton( @@ -128,7 +128,7 @@ class OBAuthPasswordStepPageState extends State { ); } - Widget _buildWhatYourPassword({@required BuildContext context}) { + Widget _buildWhatYourPassword({required BuildContext context}) { String whatPasswordText = localizationService.trans('auth__create_acc__what_password'); String passwordCharactersText = @@ -172,8 +172,8 @@ class OBAuthPasswordStepPageState extends State { child: OBAuthTextField( autocorrect: false, obscureText: !passwordIsVisible, - validator: (String password) { - String validatePassword = + validator: (String? password) { + String? validatePassword = validationService.validateUserPassword(password); if (validatePassword != null) return validatePassword; }, diff --git a/lib/pages/auth/create_account/submit_step.dart b/lib/pages/auth/create_account/submit_step.dart index a7cfe90d5..019c39074 100644 --- a/lib/pages/auth/create_account/submit_step.dart +++ b/lib/pages/auth/create_account/submit_step.dart @@ -13,10 +13,10 @@ class OBAuthSubmitPage extends StatefulWidget { } class OBAuthSubmitPageState extends State { - LocalizationService localizationService; - CreateAccountBloc createAccountBloc; + late LocalizationService localizationService; + late CreateAccountBloc createAccountBloc; - bool mustRequestCreateAccount; + late bool mustRequestCreateAccount; @override void initState() { @@ -82,7 +82,7 @@ class OBAuthSubmitPageState extends State { stream: createAccountBloc.createAccountErrorFeedback, initialData: null, builder: (context, snapshot) { - var createAccountErrorFeedback = snapshot.data; + var createAccountErrorFeedback = snapshot.data as String?; if (createAccountErrorFeedback != null) { return _buildStatusError(context, createAccountErrorFeedback); @@ -164,7 +164,7 @@ class OBAuthSubmitPageState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = localizationService.trans('auth__create_acc__previous'); return OBSecondaryButton( diff --git a/lib/pages/auth/create_account/suggested_communities/suggested_communities.dart b/lib/pages/auth/create_account/suggested_communities/suggested_communities.dart index 831057228..45dc78b0f 100644 --- a/lib/pages/auth/create_account/suggested_communities/suggested_communities.dart +++ b/lib/pages/auth/create_account/suggested_communities/suggested_communities.dart @@ -15,8 +15,8 @@ class OBSuggestedCommunitiesPage extends StatefulWidget { class OBSuggestedCommunitiesPageState extends State { - LocalizationService localizationService; - CreateAccountBloc createAccountBloc; + late LocalizationService localizationService; + late CreateAccountBloc createAccountBloc; bool _isCommunitySelectionInProgress = false; @override @@ -91,7 +91,7 @@ class OBSuggestedCommunitiesPageState }); } - Widget _buildContinueButton({@required BuildContext context}) { + Widget _buildContinueButton({required BuildContext context}) { String buttonText = localizationService.auth__login__login; return OBSuccessButton( diff --git a/lib/pages/auth/create_account/suggested_communities/widgets/suggested_communities/suggested_communities.dart b/lib/pages/auth/create_account/suggested_communities/widgets/suggested_communities/suggested_communities.dart index e58122adb..ac4286ab9 100644 --- a/lib/pages/auth/create_account/suggested_communities/widgets/suggested_communities/suggested_communities.dart +++ b/lib/pages/auth/create_account/suggested_communities/widgets/suggested_communities/suggested_communities.dart @@ -10,7 +10,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBSuggestedCommunities extends StatefulWidget { - final VoidCallback onNoSuggestions; + final VoidCallback? onNoSuggestions; const OBSuggestedCommunities({this.onNoSuggestions}); @@ -22,12 +22,12 @@ class OBSuggestedCommunities extends StatefulWidget { class OBSuggestedCommunitiesState extends State with AutomaticKeepAliveClientMixin { - bool _needsBootstrap; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - List _suggestedCommunities; - bool _requestInProgress; + late bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late List _suggestedCommunities; + late bool _requestInProgress; @override void initState() { @@ -106,7 +106,7 @@ class OBSuggestedCommunitiesState extends State await _userService.getSuggestedCommunities(); _setSuggestedCommunities(suggestedCommunitiesList.communities); if (widget.onNoSuggestions != null && - suggestedCommunitiesList.communities.isEmpty) widget.onNoSuggestions(); + suggestedCommunitiesList.communities?.isEmpty == true) widget.onNoSuggestions!(); } catch (error) { _onError(error); } finally { @@ -119,8 +119,8 @@ class OBSuggestedCommunitiesState extends State _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -128,9 +128,9 @@ class OBSuggestedCommunitiesState extends State } } - void _setSuggestedCommunities(List communities) { + void _setSuggestedCommunities(List? communities) { setState(() { - _suggestedCommunities = communities; + _suggestedCommunities = communities ?? []; }); } diff --git a/lib/pages/auth/create_account/username_step.dart b/lib/pages/auth/create_account/username_step.dart index e9db72c95..471d2ba7d 100644 --- a/lib/pages/auth/create_account/username_step.dart +++ b/lib/pages/auth/create_account/username_step.dart @@ -17,14 +17,14 @@ class OBAuthUsernameStepPage extends StatefulWidget { } class OBAuthUsernameStepPageState extends State { - bool _usernameCheckInProgress; - bool _usernameTaken; + late bool _usernameCheckInProgress; + bool? _usernameTaken; final GlobalKey _formKey = GlobalKey(); - CreateAccountBloc _createAccountBloc; - LocalizationService _localizationService; - ValidationService _validationService; - ToastService _toastService; + late CreateAccountBloc _createAccountBloc; + late LocalizationService _localizationService; + late ValidationService _validationService; + late ToastService _toastService; TextEditingController _usernameController = TextEditingController(); @@ -80,7 +80,7 @@ class OBAuthUsernameStepPageState extends State { bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } void _setUsernameTaken(bool isUsernameTaken) { @@ -107,7 +107,7 @@ class OBAuthUsernameStepPageState extends State { void onPressedNextStep(BuildContext context) async { await _checkUsernameAvailable(_usernameController.text.trim(), context); bool isUsernameValid = _validateForm(); - if (isUsernameValid && !_usernameTaken) { + if (isUsernameValid && !(_usernameTaken ?? true)) { setState(() { _createAccountBloc.setUsername(_usernameController.text.trim()); Navigator.pushNamed(context, '/auth/password_step'); @@ -129,7 +129,7 @@ class OBAuthUsernameStepPageState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__create_acc__previous'); return OBSecondaryButton( @@ -156,7 +156,7 @@ class OBAuthUsernameStepPageState extends State { ); } - Widget _buildWhatsYourUsername({@required BuildContext context}) { + Widget _buildWhatsYourUsername({required BuildContext context}) { String whatsUsernameText = _localizationService.auth__create_acc__what_username; @@ -193,11 +193,11 @@ class OBAuthUsernameStepPageState extends State { child: OBAuthTextField( autocorrect: false, hintText: usernameInputPlaceholder, - validator: (String username) { - String validateUsernameResult = _validationService.validateUserUsername(username.trim()); + validator: (String? username) { + String? validateUsernameResult = _validationService.validateUserUsername(username?.trim()); if (validateUsernameResult != null) return validateUsernameResult; - if (_usernameTaken != null && _usernameTaken) { - return errorUsernameTaken.replaceFirst('%s', username); + if (_usernameTaken != null && _usernameTaken!) { + return errorUsernameTaken.replaceFirst('%s', username ?? ''); } }, controller: _usernameController, diff --git a/lib/pages/auth/create_account/widgets/auth_text_field.dart b/lib/pages/auth/create_account/widgets/auth_text_field.dart index 2fc71be41..75ab64180 100644 --- a/lib/pages/auth/create_account/widgets/auth_text_field.dart +++ b/lib/pages/auth/create_account/widgets/auth_text_field.dart @@ -2,11 +2,11 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class OBAuthTextField extends StatelessWidget { - final TextEditingController controller; + final TextEditingController? controller; - final FocusNode focusNode; + final FocusNode? focusNode; - final TextInputAction textInputAction; + final TextInputAction? textInputAction; final TextCapitalization textCapitalization; @@ -18,36 +18,36 @@ class OBAuthTextField extends StatelessWidget { final bool autocorrect; - final int maxLength; + final int? maxLength; final bool maxLengthEnforced; - final VoidCallback onEditingComplete; + final VoidCallback? onEditingComplete; - final List inputFormatters; + final List? inputFormatters; - final FormFieldValidator validator; + final FormFieldValidator? validator; - final bool enabled; + final bool? enabled; - final Brightness keyboardAppearance; + final Brightness? keyboardAppearance; final int maxLines; - final String hintText; + final String? hintText; - final Widget prefixIcon; + final Widget? prefixIcon; - final Widget suffixIcon; + final Widget? suffixIcon; final double fontSize; final EdgeInsetsGeometry contentPadding; - final ValueChanged onFieldSubmitted; + final ValueChanged? onFieldSubmitted; OBAuthTextField({ - Key key, + Key? key, this.controller, this.focusNode, this.textInputAction, @@ -84,7 +84,7 @@ class OBAuthTextField extends StatelessWidget { obscureText: obscureText, maxLines: maxLines, maxLength: maxLength, - maxLengthEnforced: maxLengthEnforced, + maxLengthEnforcement: maxLengthEnforced ? MaxLengthEnforcement.enforced : MaxLengthEnforcement.none, validator: validator, onEditingComplete: onEditingComplete, inputFormatters: inputFormatters, diff --git a/lib/pages/auth/login.dart b/lib/pages/auth/login.dart index e092c1018..f60b5f2dd 100644 --- a/lib/pages/auth/login.dart +++ b/lib/pages/auth/login.dart @@ -17,19 +17,19 @@ class OBAuthLoginPage extends StatefulWidget { class OBAuthLoginPageState extends State { final _formKey = GlobalKey(); - FocusNode _passwordFocusNode; + late FocusNode _passwordFocusNode; - bool _isSubmitted; - bool _passwordIsVisible; - String _loginFeedback; - bool _loginInProgress; + late bool _isSubmitted; + late bool _passwordIsVisible; + String? _loginFeedback; + late bool _loginInProgress; TextEditingController _usernameController = TextEditingController(); TextEditingController _passwordController = TextEditingController(); - LocalizationService _localizationService; - ValidationService _validationService; - UserService _userService; + late LocalizationService _localizationService; + late ValidationService _validationService; + late UserService _userService; @override void initState() { @@ -111,7 +111,7 @@ class OBAuthLoginPageState extends State { return SizedBox( child: Text( - _loginFeedback, + _loginFeedback!, style: TextStyle(fontSize: 16.0, color: Colors.deepOrange), textAlign: TextAlign.center, ), @@ -132,7 +132,7 @@ class OBAuthLoginPageState extends State { Future _submitForm() async { _isSubmitted = true; - if (_validateForm()) { + if (_validateForm() == true) { await _login(context); } } @@ -161,7 +161,7 @@ class OBAuthLoginPageState extends State { _setLoginInProgress(false); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__login__previous'); return OBSecondaryButton( @@ -185,7 +185,7 @@ class OBAuthLoginPageState extends State { ); } - Widget _buildForgotPasswordButton({@required BuildContext context}) { + Widget _buildForgotPasswordButton({required BuildContext context}) { String buttonText = _localizationService.trans( 'auth__login__forgot_password'); @@ -207,7 +207,7 @@ class OBAuthLoginPageState extends State { ); } - Widget _buildHeading({@required BuildContext context}) { + Widget _buildHeading({required BuildContext context}) { String titleText = _localizationService.trans('auth__login__title'); String subtitleText = _localizationService.trans('auth__login__subtitle'); @@ -313,22 +313,22 @@ class OBAuthLoginPageState extends State { )); } - String _validateUsername(String value) { + String? _validateUsername(String? value) { if (!_isSubmitted) return null; - return _validationService.validateUserUsername(value.trim()); + return _validationService.validateUserUsername(value?.trim()); } - String _validatePassword(String value) { + String? _validatePassword(String? value) { if (!_isSubmitted) return null; return _validationService.validateUserPassword(value); } - bool _validateForm() { + bool? _validateForm() { if (_loginFeedback != null) { _setLoginFeedback(null); } - return _formKey.currentState.validate(); + return _formKey.currentState?.validate(); } void _togglePasswordVisibility() { @@ -337,7 +337,7 @@ class OBAuthLoginPageState extends State { }); } - void _setLoginFeedback(String feedback) { + void _setLoginFeedback(String? feedback) { setState(() { _loginFeedback = feedback; }); diff --git a/lib/pages/auth/reset_password/forgot_password_step.dart b/lib/pages/auth/reset_password/forgot_password_step.dart index cc3bd1108..c807d3aa4 100644 --- a/lib/pages/auth/reset_password/forgot_password_step.dart +++ b/lib/pages/auth/reset_password/forgot_password_step.dart @@ -18,16 +18,16 @@ class OBAuthForgotPasswordPage extends StatefulWidget { class OBAuthForgotPasswordPageState extends State { final _formKey = GlobalKey(); - bool _isSubmitted; - String _errorFeedback; - bool _requestInProgress; + late bool _isSubmitted; + String? _errorFeedback; + late bool _requestInProgress; - TextEditingController _usernameController = TextEditingController(); - TextEditingController _emailController = TextEditingController(); + late TextEditingController _usernameController = TextEditingController(); + late TextEditingController _emailController = TextEditingController(); - LocalizationService _localizationService; - ValidationService _validationService; - UserService _userService; + late LocalizationService _localizationService; + late ValidationService _validationService; + late UserService _userService; @override void initState() { @@ -99,7 +99,7 @@ class OBAuthForgotPasswordPageState extends State { return SizedBox( child: Text( - _errorFeedback, + _errorFeedback!, style: TextStyle(fontSize: 16.0, color: Colors.deepOrange), textAlign: TextAlign.center, ), @@ -120,7 +120,7 @@ class OBAuthForgotPasswordPageState extends State { Future _submitForm() async { _isSubmitted = true; - if (_validateForm()) { + if (_validateForm() == true) { await _requestPasswordReset(context); } } @@ -135,7 +135,7 @@ class OBAuthForgotPasswordPageState extends State { Navigator.pushNamed(context, '/auth/verify_reset_password_link_step'); } catch (error) { if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); + String? errorMessage = await error.toHumanReadableMessage(); _setErrorFeedback(errorMessage); } if (error is HttpieConnectionRefusedError) { @@ -147,7 +147,7 @@ class OBAuthForgotPasswordPageState extends State { } } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__login__previous'); return OBSecondaryButton( @@ -171,7 +171,7 @@ class OBAuthForgotPasswordPageState extends State { ); } - Widget _buildHeading({@required BuildContext context}) { + Widget _buildHeading({required BuildContext context}) { String titleText = _localizationService.auth__login__forgot_password; String subtitleText = _localizationService.auth__login__forgot_password_subtitle; @@ -241,7 +241,7 @@ class OBAuthForgotPasswordPageState extends State { )); } - String _validateEmail(String value) { + String? _validateEmail(String? value) { if (!_isSubmitted) return null; if (_usernameController.text.trim().length > 0) { return null; @@ -249,14 +249,14 @@ class OBAuthForgotPasswordPageState extends State { return _validationService.validateUserEmail(value); } - bool _validateForm() { + bool? _validateForm() { if (_errorFeedback != null) { _setErrorFeedback(null); } - return _formKey.currentState.validate(); + return _formKey.currentState?.validate(); } - void _setErrorFeedback(String feedback) { + void _setErrorFeedback(String? feedback) { setState(() { _errorFeedback = feedback; }); diff --git a/lib/pages/auth/reset_password/reset_password_success_step.dart b/lib/pages/auth/reset_password/reset_password_success_step.dart index 85af7371e..c956a8c23 100644 --- a/lib/pages/auth/reset_password/reset_password_success_step.dart +++ b/lib/pages/auth/reset_password/reset_password_success_step.dart @@ -13,8 +13,8 @@ class OBAuthPasswordResetSuccessPage extends StatefulWidget { } class OBAuthPasswordResetSuccessPageState extends State { - LocalizationService localizationService; - CreateAccountBloc createAccountBloc; + late LocalizationService localizationService; + late CreateAccountBloc createAccountBloc; @override Widget build(BuildContext context) { @@ -83,7 +83,7 @@ class OBAuthPasswordResetSuccessPageState extends State { - bool _passwordIsVisible; - CreateAccountBloc createAccountBloc; - LocalizationService localizationService; - ValidationService validationService; - UserService userService; - ToastService toastService; + late bool _passwordIsVisible; + late CreateAccountBloc createAccountBloc; + late LocalizationService localizationService; + late ValidationService validationService; + late UserService userService; + late ToastService toastService; static const passwordMaxLength = ValidationService.PASSWORD_MAX_LENGTH; static const passwordMinLength = ValidationService.PASSWORD_MIN_LENGTH; final GlobalKey _formKey = GlobalKey(); - bool _requestInProgress; + late bool _requestInProgress; TextEditingController _passwordController = TextEditingController(); @@ -96,7 +96,7 @@ class OBAuthSetNewPasswordPageState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } void onPressedNextStep() async { @@ -109,14 +109,14 @@ class OBAuthSetNewPasswordPageState extends State { Future _verifyResetPassword(BuildContext context) async { _setRequestInProgress(true); String newPassword = _passwordController.text; - String passwordResetToken = createAccountBloc.getPasswordResetToken(); + String? passwordResetToken = createAccountBloc.getPasswordResetToken(); try { - await userService.verifyPasswordReset(newPassword: newPassword, passwordResetToken: passwordResetToken); + await userService.verifyPasswordReset(newPassword: newPassword, passwordResetToken: passwordResetToken ?? ''); createAccountBloc.clearAll(); Navigator.pushNamed(context, '/auth/password_reset_success_step'); } catch (error) { if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); + String? errorMessage = await error.toHumanReadableMessage(); _showErrorMessage(errorMessage); } if (error is HttpieConnectionRefusedError) { @@ -127,7 +127,7 @@ class OBAuthSetNewPasswordPageState extends State { } } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = localizationService.trans('auth__create_acc__previous'); return OBSecondaryButton( @@ -154,7 +154,7 @@ class OBAuthSetNewPasswordPageState extends State { ); } - Widget _buildWhatYourPassword({@required BuildContext context}) { + Widget _buildWhatYourPassword({required BuildContext context}) { String whatPasswordText = localizationService.auth__create_acc__what_password; @@ -197,8 +197,8 @@ class OBAuthSetNewPasswordPageState extends State { child: OBAuthTextField( autocorrect: false, obscureText: !_passwordIsVisible, - validator: (String password) { - String validatePassword = validationService.validateUserPassword(password); + validator: (String? password) { + String? validatePassword = validationService.validateUserPassword(password); if (validatePassword != null) return validatePassword; }, suffixIcon: GestureDetector( @@ -224,8 +224,8 @@ class OBAuthSetNewPasswordPageState extends State { }); } - void _showErrorMessage(String message) { - toastService.error(message: message, context: context); + void _showErrorMessage(String? message) { + toastService.error(message: message ?? 'Unknown error', context: context); } diff --git a/lib/pages/auth/reset_password/verify_reset_password_link_step.dart b/lib/pages/auth/reset_password/verify_reset_password_link_step.dart index 1a3205c1e..5f17a5cea 100644 --- a/lib/pages/auth/reset_password/verify_reset_password_link_step.dart +++ b/lib/pages/auth/reset_password/verify_reset_password_link_step.dart @@ -19,10 +19,10 @@ class OBAuthVerifyPasswordPage extends StatefulWidget { class OBAuthVerifyPasswordPageState extends State { final GlobalKey _formKey = GlobalKey(); - CreateAccountBloc _createAccountBloc; - LocalizationService _localizationService; - ValidationService _validationService; - ToastService _toastService; + late CreateAccountBloc _createAccountBloc; + late LocalizationService _localizationService; + late ValidationService _validationService; + late ToastService _toastService; TextEditingController _linkController = TextEditingController(); @@ -80,7 +80,7 @@ class OBAuthVerifyPasswordPageState extends State { bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } void onPressedNextStep(BuildContext context) { @@ -99,7 +99,7 @@ class OBAuthVerifyPasswordPageState extends State { final params = Uri.parse(uri).queryParametersAll; var token = ''; if (params.containsKey('token')) { - token = params['token'][0]; + token = params['token']![0]; } else { token = uri.split('?token=')[1]; } @@ -119,7 +119,7 @@ class OBAuthVerifyPasswordPageState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__create_acc__previous'); return OBSecondaryButton( @@ -146,7 +146,7 @@ class OBAuthVerifyPasswordPageState extends State { ); } - Widget _buildPasteRegisterLink({@required BuildContext context}) { + Widget _buildPasteRegisterLink({required BuildContext context}) { String pasteLinkText = _localizationService.trans('auth__create_acc__paste_password_reset_link'); @@ -180,8 +180,8 @@ class OBAuthVerifyPasswordPageState extends State { child: OBAuthTextField( autocorrect: false, hintText: '', - validator: (String link) { - String validateLink = _validationService.validateUserRegistrationLink(link.trim()); + validator: (String? link) { + String? validateLink = _validationService.validateUserRegistrationLink(link?.trim()); if (validateLink != null) { return validateLink; } diff --git a/lib/pages/auth/splash.dart b/lib/pages/auth/splash.dart index 33d415b54..abc5101b9 100644 --- a/lib/pages/auth/splash.dart +++ b/lib/pages/auth/splash.dart @@ -15,8 +15,8 @@ class OBAuthSplashPage extends StatefulWidget { } class OBAuthSplashPageState extends State { - LocalizationService localizationService; - CreateAccountBloc createAccountBloc; + late LocalizationService localizationService; + late CreateAccountBloc createAccountBloc; @override Widget build(BuildContext context) { @@ -79,7 +79,7 @@ class OBAuthSplashPageState extends State { ); } - Widget _buildLoginButton({@required BuildContext context}) { + Widget _buildLoginButton({required BuildContext context}) { String buttonText = localizationService.trans('auth__login'); return OBSuccessButton( @@ -100,7 +100,7 @@ class OBAuthSplashPageState extends State { ); } - Widget _buildCreateAccountButton({@required BuildContext context}) { + Widget _buildCreateAccountButton({required BuildContext context}) { String buttonText = localizationService.trans('auth__create_account'); return OBSecondaryButton( diff --git a/lib/pages/home/bottom_sheets/camera_picker.dart b/lib/pages/home/bottom_sheets/camera_picker.dart index 6c6210f17..1f7d3d117 100644 --- a/lib/pages/home/bottom_sheets/camera_picker.dart +++ b/lib/pages/home/bottom_sheets/camera_picker.dart @@ -10,11 +10,12 @@ import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; class OBCameraPickerBottomSheet extends StatelessWidget { - const OBCameraPickerBottomSheet({Key key}) : super(key: key); + const OBCameraPickerBottomSheet({Key? key}) : super(key: key); @override Widget build(BuildContext context) { var provider = OpenbookProvider.of(context); + var imagePicker = ImagePicker(); LocalizationService localizationService = provider.localizationService; @@ -28,7 +29,8 @@ class OBCameraPickerBottomSheet extends StatelessWidget { bool permissionGranted = await provider.permissionService .requestStoragePermissions(context: context); if (permissionGranted) { - File file = await ImagePicker.pickImage(source: ImageSource.camera); + PickedFile? pickedFile = await imagePicker.getImage(source: ImageSource.camera); + File? file = pickedFile != null ? File(pickedFile.path) : null; Navigator.pop( context, file != null ? MediaFile(file, FileType.image) : null); } @@ -43,7 +45,8 @@ class OBCameraPickerBottomSheet extends StatelessWidget { bool permissionGranted = await provider.permissionService .requestStoragePermissions(context: context); if (permissionGranted) { - File file = await ImagePicker.pickVideo(source: ImageSource.camera); + PickedFile? pickedFile = await imagePicker.getVideo(source: ImageSource.camera); + File? file = pickedFile != null ? File(pickedFile.path) : null; Navigator.pop( context, file != null ? MediaFile(file, FileType.video) : null); } diff --git a/lib/pages/home/bottom_sheets/community_actions.dart b/lib/pages/home/bottom_sheets/community_actions.dart index 03f8bf047..d81b8fc01 100644 --- a/lib/pages/home/bottom_sheets/community_actions.dart +++ b/lib/pages/home/bottom_sheets/community_actions.dart @@ -16,10 +16,10 @@ import 'package:flutter/material.dart'; class OBCommunityActionsBottomSheet extends StatefulWidget { final Community community; - final OnCommunityReported onCommunityReported; + final OnCommunityReported? onCommunityReported; const OBCommunityActionsBottomSheet( - {Key key, @required this.community, this.onCommunityReported}) + {Key? key, required this.community, this.onCommunityReported}) : super(key: key); @override @@ -30,10 +30,10 @@ class OBCommunityActionsBottomSheet extends StatefulWidget { class OBCommunityActionsBottomSheetState extends State { - UserService _userService; - ToastService _toastService; - ModalService _modalService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ModalService _modalService; + late LocalizationService _localizationService; @override Widget build(BuildContext context) { @@ -51,13 +51,13 @@ class OBCommunityActionsBottomSheetState ) ]; - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; Community community = widget.community; bool isMemberOfCommunity = community.isMember(loggedInUser); bool isCommunityAdministrator = community.isAdministrator(loggedInUser); bool isCommunityModerator = community.isModerator(loggedInUser); - bool communityHasInvitesEnabled = community.invitesEnabled; + bool communityHasInvitesEnabled = community.invitesEnabled ?? false; if (isMemberOfCommunity) { communityActions.add(OBNewPostNotificationsForCommunityTile( diff --git a/lib/pages/home/bottom_sheets/community_type_picker.dart b/lib/pages/home/bottom_sheets/community_type_picker.dart index 16ff3116d..4283b4731 100644 --- a/lib/pages/home/bottom_sheets/community_type_picker.dart +++ b/lib/pages/home/bottom_sheets/community_type_picker.dart @@ -15,10 +15,10 @@ class OBCommunityTypePickerBottomSheet extends StatefulWidget { final ValueChanged onTypeChanged; // Useless for now given the bug - final CommunityType initialType; + final CommunityType? initialType; const OBCommunityTypePickerBottomSheet( - {Key key, @required this.onTypeChanged, this.initialType}) + {Key? key, required this.onTypeChanged, this.initialType}) : super(key: key); @override @@ -29,7 +29,7 @@ class OBCommunityTypePickerBottomSheet extends StatefulWidget { class OBCommunityTypePickerBottomSheetState extends State { - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { diff --git a/lib/pages/home/bottom_sheets/confirm_action.dart b/lib/pages/home/bottom_sheets/confirm_action.dart index d2c70ae45..2ebd721a9 100644 --- a/lib/pages/home/bottom_sheets/confirm_action.dart +++ b/lib/pages/home/bottom_sheets/confirm_action.dart @@ -11,16 +11,16 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBConfirmActionBottomSheet extends StatefulWidget { - final String title; - final String subtitle; - final String description; - final String confirmText; - final String cancelText; + final String? title; + final String? subtitle; + final String? description; + final String? confirmText; + final String? cancelText; final ActionCompleter actionCompleter; const OBConfirmActionBottomSheet( {this.title, - @required this.actionCompleter, + required this.actionCompleter, this.confirmText, this.cancelText, this.subtitle, @@ -34,12 +34,12 @@ class OBConfirmActionBottomSheet extends StatefulWidget { class OBConfirmActionBottomSheetState extends State { - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; - bool _isConfirmActionInProgress; - CancelableOperation _confirmActionOperation; + late bool _isConfirmActionInProgress; + CancelableOperation? _confirmActionOperation; @override void initState() { @@ -84,7 +84,7 @@ class OBConfirmActionBottomSheetState height: 10, ), OBText( - widget.subtitle, + widget.subtitle!, size: OBTextSize.large, textAlign: TextAlign.left, ), @@ -97,7 +97,7 @@ class OBConfirmActionBottomSheetState height: 10, ), OBText( - widget.description, + widget.description!, size: OBTextSize.medium, textAlign: TextAlign.left, ), @@ -165,8 +165,8 @@ class OBConfirmActionBottomSheetState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/bottom_sheets/connection_circles_picker.dart b/lib/pages/home/bottom_sheets/connection_circles_picker.dart index 3a83d527a..25d0d739b 100644 --- a/lib/pages/home/bottom_sheets/connection_circles_picker.dart +++ b/lib/pages/home/bottom_sheets/connection_circles_picker.dart @@ -14,14 +14,14 @@ class OBConnectionCirclesPickerBottomSheet extends StatefulWidget { final String title; final String actionLabel; final OnPickedCircles onPickedCircles; - final List initialPickedCircles; + final List? initialPickedCircles; const OBConnectionCirclesPickerBottomSheet( - {Key key, + {Key? key, this.initialPickedCircles, - @required this.title, - @required this.actionLabel, - @required this.onPickedCircles}) + required this.title, + required this.actionLabel, + required this.onPickedCircles}) : super(key: key); @override @@ -32,15 +32,15 @@ class OBConnectionCirclesPickerBottomSheet extends StatefulWidget { class OBConnectionCirclesPickerBottomSheetState extends State { - UserService _userService; - ModalService _modalService; + late UserService _userService; + late ModalService _modalService; - bool _needsBootstrap; + late bool _needsBootstrap; - List _circles; - List _circleSearchResults; - List _pickedCircles; - List _disabledCircles; + late List _circles; + late List _circleSearchResults; + late List _pickedCircles; + late List _disabledCircles; @override void initState() { @@ -48,7 +48,7 @@ class OBConnectionCirclesPickerBottomSheetState _circles = []; _circleSearchResults = []; _pickedCircles = widget.initialPickedCircles != null - ? widget.initialPickedCircles.toList() + ? widget.initialPickedCircles!.toList() : []; _needsBootstrap = true; _disabledCircles = []; @@ -117,7 +117,7 @@ class OBConnectionCirclesPickerBottomSheetState String standarisedSearchStr = searchString.toLowerCase(); List results = _circles.where((Circle circle) { - return circle.name.toLowerCase().contains(standarisedSearchStr); + return circle.name!.toLowerCase().contains(standarisedSearchStr); }).toList(); _setCircleSearchResults(results); @@ -130,7 +130,7 @@ class OBConnectionCirclesPickerBottomSheetState } void _onWantsToCreateANewCircle() async { - Circle createdCircle = + Circle? createdCircle = await _modalService.openCreateConnectionsCircle(context: context); if (createdCircle != null) { _addCircle(createdCircle); @@ -157,7 +157,7 @@ class OBConnectionCirclesPickerBottomSheetState void _bootstrap() async { CirclesList circleList = await _userService.getConnectionsCircles(); // We assume the connections circle will always be the last one - var connectionsCircles = circleList.circles; + var connectionsCircles = circleList.circles!; Circle connectionsCircle = connectionsCircles.removeLast(); connectionsCircles.insert(0, connectionsCircle); this._setCircles(connectionsCircles); @@ -176,7 +176,7 @@ class OBConnectionCirclesPickerBottomSheetState _circles = circles; _circleSearchResults = circles.toList(); var connectionsCircle = _circles.firstWhere((Circle circle) { - return circle.id == user.connectionsCircleId; + return circle.id == user!.connectionsCircleId; }); _disabledCircles.removeWhere((Circle circle) { return !circles.contains(circle); diff --git a/lib/pages/home/bottom_sheets/follows_lists_picker.dart b/lib/pages/home/bottom_sheets/follows_lists_picker.dart index 3860b909b..525172274 100644 --- a/lib/pages/home/bottom_sheets/follows_lists_picker.dart +++ b/lib/pages/home/bottom_sheets/follows_lists_picker.dart @@ -13,13 +13,13 @@ import 'package:flutter/material.dart'; class OBFollowsListsPickerBottomSheet extends StatefulWidget { final String title; final String actionLabel; - final List initialPickedFollowsLists; + final List? initialPickedFollowsLists; const OBFollowsListsPickerBottomSheet( - {Key key, + {Key? key, this.initialPickedFollowsLists, - @required this.title, - @required this.actionLabel}) + required this.title, + required this.actionLabel}) : super(key: key); @override @@ -30,14 +30,14 @@ class OBFollowsListsPickerBottomSheet extends StatefulWidget { class OBFollowsListsPickerBottomSheetState extends State { - UserService _userService; - ModalService _modalService; + late UserService _userService; + late ModalService _modalService; - bool _needsBootstrap; + late bool _needsBootstrap; - List _followsLists; - List _followsListSearchResults; - List _pickedFollowsLists; + late List _followsLists; + late List _followsListSearchResults; + late List _pickedFollowsLists; @override void initState() { @@ -45,7 +45,7 @@ class OBFollowsListsPickerBottomSheetState _followsLists = []; _followsListSearchResults = []; _pickedFollowsLists = widget.initialPickedFollowsLists != null - ? widget.initialPickedFollowsLists.toList() + ? widget.initialPickedFollowsLists!.toList() : []; _needsBootstrap = true; } @@ -113,7 +113,7 @@ class OBFollowsListsPickerBottomSheetState String standarisedSearchStr = searchString.toLowerCase(); List results = _followsLists.where((FollowsList followsList) { - return followsList.name.toLowerCase().contains(standarisedSearchStr); + return followsList.name!.toLowerCase().contains(standarisedSearchStr); }).toList(); _setFollowsListSearchResults(results); @@ -127,7 +127,7 @@ class OBFollowsListsPickerBottomSheetState } void _onWantsToCreateANewFollowsList() async { - FollowsList createdFollowsList = + FollowsList? createdFollowsList = await _modalService.openCreateFollowsList(context: context); if (createdFollowsList != null) { @@ -154,7 +154,7 @@ class OBFollowsListsPickerBottomSheetState void _bootstrap() async { FollowsListsList followsListList = await _userService.getFollowsLists(); - var connectionsFollowsLists = followsListList.lists; + var connectionsFollowsLists = followsListList.lists!; this._setFollowsLists(connectionsFollowsLists); } diff --git a/lib/pages/home/bottom_sheets/hashtag_actions.dart b/lib/pages/home/bottom_sheets/hashtag_actions.dart index f71a34974..223a15982 100644 --- a/lib/pages/home/bottom_sheets/hashtag_actions.dart +++ b/lib/pages/home/bottom_sheets/hashtag_actions.dart @@ -7,11 +7,11 @@ import 'package:flutter/material.dart'; class OBHashtagActionsBottomSheet extends StatelessWidget { final Hashtag hashtag; - final ValueChanged onHashtagReported; + final ValueChanged? onHashtagReported; const OBHashtagActionsBottomSheet({ - Key key, - @required this.hashtag, + Key? key, + required this.hashtag, this.onHashtagReported, }) : super(key: key); diff --git a/lib/pages/home/bottom_sheets/hashtags_display_setting_picker.dart b/lib/pages/home/bottom_sheets/hashtags_display_setting_picker.dart index 9d6469f74..1ae215054 100644 --- a/lib/pages/home/bottom_sheets/hashtags_display_setting_picker.dart +++ b/lib/pages/home/bottom_sheets/hashtags_display_setting_picker.dart @@ -8,10 +8,10 @@ import 'package:flutter/material.dart'; class OBHashtagsDisplaySettingPickerBottomSheet extends StatefulWidget { final ValueChanged onTypeChanged; - final HashtagsDisplaySetting initialValue; + final HashtagsDisplaySetting? initialValue; const OBHashtagsDisplaySettingPickerBottomSheet( - {Key key, @required this.onTypeChanged, this.initialValue}) + {Key? key, required this.onTypeChanged, this.initialValue}) : super(key: key); @override @@ -22,8 +22,8 @@ class OBHashtagsDisplaySettingPickerBottomSheet extends StatefulWidget { class OBHashtagsDisplaySettingPickerBottomSheetState extends State { - FixedExtentScrollController _cupertinoPickerController; - List allHashtagsDisplaySettings; + late FixedExtentScrollController _cupertinoPickerController; + late List allHashtagsDisplaySettings; @override void initState() { @@ -31,8 +31,8 @@ class OBHashtagsDisplaySettingPickerBottomSheetState allHashtagsDisplaySettings = HashtagsDisplaySetting.values(); _cupertinoPickerController = FixedExtentScrollController( initialItem: widget.initialValue != null - ? allHashtagsDisplaySettings.indexOf(widget.initialValue) - : null); + ? allHashtagsDisplaySettings.indexOf(widget.initialValue!) + : 0); } @override @@ -57,7 +57,7 @@ class OBHashtagsDisplaySettingPickerBottomSheetState itemExtent: 32, children: allHashtagsDisplaySettings.map((HashtagsDisplaySetting setting) { return Center( - child: OBText(localizationMap[setting]), + child: OBText(localizationMap[setting]!), ); }).toList(), ), diff --git a/lib/pages/home/bottom_sheets/image_picker.dart b/lib/pages/home/bottom_sheets/image_picker.dart index aa60c8555..92fe8e3ab 100644 --- a/lib/pages/home/bottom_sheets/image_picker.dart +++ b/lib/pages/home/bottom_sheets/image_picker.dart @@ -10,11 +10,12 @@ import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; class OBImagePickerBottomSheet extends StatelessWidget { - const OBImagePickerBottomSheet({Key key}) : super(key: key); + const OBImagePickerBottomSheet({Key? key}) : super(key: key); @override Widget build(BuildContext context) { var provider = OpenbookProvider.of(context); + var imagePicker = ImagePicker(); LocalizationService localizationService = provider.localizationService; @@ -28,11 +29,11 @@ class OBImagePickerBottomSheet extends StatelessWidget { bool permissionGranted = await provider.permissionService .requestStoragePermissions(context: context); if (permissionGranted) { - FilePickerResult result = - await FilePicker.platform.pickFiles(type: FileType.image); + PickedFile? pickedFile = + await imagePicker.getImage(source: ImageSource.gallery); - if (result != null) { - File file = File(result.files.single.path); + if (pickedFile != null) { + File file = File(pickedFile.path); Navigator.pop(context, file); } } @@ -47,8 +48,10 @@ class OBImagePickerBottomSheet extends StatelessWidget { bool permissionGranted = await provider.permissionService .requestCameraPermissions(context: context); if (permissionGranted) { - File pickedImage = - await ImagePicker.pickImage(source: ImageSource.camera); + PickedFile? pickedFile = + await imagePicker.getImage(source: ImageSource.camera); + + File? pickedImage = pickedFile != null ? File(pickedFile.path) : null; Navigator.pop(context, pickedImage); } }, diff --git a/lib/pages/home/bottom_sheets/link_previews_setting_picker.dart b/lib/pages/home/bottom_sheets/link_previews_setting_picker.dart index 5d80dee7f..35be91b0f 100644 --- a/lib/pages/home/bottom_sheets/link_previews_setting_picker.dart +++ b/lib/pages/home/bottom_sheets/link_previews_setting_picker.dart @@ -8,10 +8,10 @@ import 'package:flutter/material.dart'; class OBLinkPreviewsSettingPickerBottomSheet extends StatefulWidget { final ValueChanged onTypeChanged; - final LinkPreviewsSetting initialValue; + final LinkPreviewsSetting? initialValue; const OBLinkPreviewsSettingPickerBottomSheet( - {Key key, @required this.onTypeChanged, this.initialValue}) + {Key? key, required this.onTypeChanged, this.initialValue}) : super(key: key); @override @@ -22,8 +22,8 @@ class OBLinkPreviewsSettingPickerBottomSheet extends StatefulWidget { class OBLinkPreviewsSettingPickerBottomSheetState extends State { - FixedExtentScrollController _cupertinoPickerController; - List allLinkPreviewsSettings; + late FixedExtentScrollController _cupertinoPickerController; + late List allLinkPreviewsSettings; @override void initState() { @@ -31,8 +31,8 @@ class OBLinkPreviewsSettingPickerBottomSheetState allLinkPreviewsSettings = LinkPreviewsSetting.values(); _cupertinoPickerController = FixedExtentScrollController( initialItem: widget.initialValue != null - ? allLinkPreviewsSettings.indexOf(widget.initialValue) - : null); + ? allLinkPreviewsSettings.indexOf(widget.initialValue!) + : 0); } @override @@ -56,7 +56,7 @@ class OBLinkPreviewsSettingPickerBottomSheetState itemExtent: 32, children: allLinkPreviewsSettings.map((LinkPreviewsSetting setting) { - return OBText(localizationMap[setting]); + return OBText(localizationMap[setting]!); }).toList(), ), ), diff --git a/lib/pages/home/bottom_sheets/post_actions.dart b/lib/pages/home/bottom_sheets/post_actions.dart index 16d0e9ccf..dbea59588 100644 --- a/lib/pages/home/bottom_sheets/post_actions.dart +++ b/lib/pages/home/bottom_sheets/post_actions.dart @@ -25,16 +25,16 @@ class OBPostActionsBottomSheet extends StatefulWidget { final Post post; final ValueChanged onPostReported; final OnPostDeleted onPostDeleted; - final Function onCommunityExcluded; - final Function onUndoCommunityExcluded; - final OBPostDisplayContext displayContext; - final ValueChanged onPostCommunityExcludedFromProfilePosts; + final Function? onCommunityExcluded; + final Function? onUndoCommunityExcluded; + final OBPostDisplayContext? displayContext; + final ValueChanged? onPostCommunityExcludedFromProfilePosts; const OBPostActionsBottomSheet( - {Key key, - @required this.post, - @required this.onPostReported, - @required this.onPostDeleted, + {Key? key, + required this.post, + required this.onPostReported, + required this.onPostDeleted, this.onCommunityExcluded, this.onUndoCommunityExcluded, this.displayContext = OBPostDisplayContext.timelinePosts, @@ -48,11 +48,11 @@ class OBPostActionsBottomSheet extends StatefulWidget { } class OBPostActionsBottomSheetState extends State { - UserService _userService; - ModalService _modalService; - ToastService _toastService; - LocalizationService _localizationService; - BottomSheetService _bottomSheetService; + late UserService _userService; + late ModalService _modalService; + late ToastService _toastService; + late LocalizationService _localizationService; + late BottomSheetService _bottomSheetService; @override Widget build(BuildContext context) { @@ -63,13 +63,13 @@ class OBPostActionsBottomSheetState extends State { _localizationService = openbookProvider.localizationService; _bottomSheetService = openbookProvider.bottomSheetService; - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; return StreamBuilder( stream: widget.post.updateSubject, initialData: widget.post, builder: (BuildContext context, AsyncSnapshot snapshot) { - Post post = snapshot.data; + Post post = snapshot.data!; List postActions = []; if (widget.displayContext == OBPostDisplayContext.topPosts) { @@ -77,13 +77,13 @@ class OBPostActionsBottomSheetState extends State { post: post, onExcludedPostCommunity: () { if (widget.onCommunityExcluded != null) { - widget.onCommunityExcluded(post.community); + widget.onCommunityExcluded!(post.community); } _dismiss(); }, onUndoExcludedPostCommunity: () { if (widget.onUndoCommunityExcluded != null) { - widget.onUndoCommunityExcluded(post.community); + widget.onUndoCommunityExcluded!(post.community); } _dismiss(); }, @@ -93,7 +93,7 @@ class OBPostActionsBottomSheetState extends State { postActions.add(OBExcludeCommunityFromProfilePostsTile( post: post, onPostCommunityExcludedFromProfilePosts: - widget.onPostCommunityExcludedFromProfilePosts)); + widget.onPostCommunityExcludedFromProfilePosts!)); } postActions.add(OBMutePostTile( @@ -180,8 +180,8 @@ class OBPostActionsBottomSheetState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/bottom_sheets/post_comment_more_actions.dart b/lib/pages/home/bottom_sheets/post_comment_more_actions.dart index 2e531956d..b90d17205 100644 --- a/lib/pages/home/bottom_sheets/post_comment_more_actions.dart +++ b/lib/pages/home/bottom_sheets/post_comment_more_actions.dart @@ -22,11 +22,11 @@ class OBPostCommentMoreActionsBottomSheet extends StatefulWidget { final ValueChanged onPostCommentReported; const OBPostCommentMoreActionsBottomSheet({ - @required this.post, - @required this.postComment, - Key key, - @required this.onPostCommentDeleted, - @required this.onPostCommentReported, + required this.post, + required this.postComment, + Key? key, + required this.onPostCommentDeleted, + required this.onPostCommentReported, }) : super(key: key); @override @@ -37,14 +37,14 @@ class OBPostCommentMoreActionsBottomSheet extends StatefulWidget { class OBPostCommentMoreActionsBottomSheetState extends State { - ToastService _toastService; - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; - ModalService _modalService; - BottomSheetService _bottomSheetService; - bool _requestInProgress; - CancelableOperation _requestOperation; + late ToastService _toastService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late ModalService _modalService; + late BottomSheetService _bottomSheetService; + late bool _requestInProgress; + CancelableOperation? _requestOperation; @override void initState() { @@ -55,7 +55,7 @@ class OBPostCommentMoreActionsBottomSheetState @override void dispose() { super.dispose(); - if (_requestOperation != null) _requestOperation.cancel(); + if (_requestOperation != null) _requestOperation!.cancel(); } @override @@ -86,7 +86,7 @@ class OBPostCommentMoreActionsBottomSheetState post: widget.post, ) ]; - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; if (loggedInUser.canReportPostComment(widget.postComment)) { actionTiles.add( diff --git a/lib/pages/home/bottom_sheets/react_to_post.dart b/lib/pages/home/bottom_sheets/react_to_post.dart index 1815b4479..c6ab64fbe 100644 --- a/lib/pages/home/bottom_sheets/react_to_post.dart +++ b/lib/pages/home/bottom_sheets/react_to_post.dart @@ -24,11 +24,11 @@ class OBReactToPostBottomSheet extends StatefulWidget { } class OBReactToPostBottomSheetState extends State { - UserService _userService; - ToastService _toastService; + late UserService _userService; + late ToastService _toastService; - bool _isReactToPostInProgress; - CancelableOperation _reactOperation; + late bool _isReactToPostInProgress; + CancelableOperation? _reactOperation; @override void initState() { @@ -39,7 +39,7 @@ class OBReactToPostBottomSheetState extends State { @override void dispose() { super.dispose(); - if (_reactOperation != null) _reactOperation.cancel(); + if (_reactOperation != null) _reactOperation!.cancel(); } @override @@ -73,7 +73,7 @@ class OBReactToPostBottomSheetState extends State { ); } - Future _reactToPost(Emoji emoji, EmojiGroup emojiGroup) async { + Future _reactToPost(Emoji emoji, EmojiGroup? emojiGroup) async { if (_isReactToPostInProgress) return null; _setReactToPostInProgress(true); @@ -81,7 +81,7 @@ class OBReactToPostBottomSheetState extends State { _reactOperation = CancelableOperation.fromFuture(_userService.reactToPost( post: widget.post, emoji: emoji)); - PostReaction postReaction = await _reactOperation.value; + PostReaction postReaction = await _reactOperation!.value; widget.post.setReaction(postReaction); // Remove modal Navigator.pop(context); @@ -99,8 +99,8 @@ class OBReactToPostBottomSheetState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/home/bottom_sheets/react_to_post_comment.dart b/lib/pages/home/bottom_sheets/react_to_post_comment.dart index 6ef3009c5..aef01924d 100644 --- a/lib/pages/home/bottom_sheets/react_to_post_comment.dart +++ b/lib/pages/home/bottom_sheets/react_to_post_comment.dart @@ -17,7 +17,7 @@ class OBReactToPostCommentBottomSheet extends StatefulWidget { final PostComment postComment; final Post post; - const OBReactToPostCommentBottomSheet({this.post, this.postComment}); + const OBReactToPostCommentBottomSheet({required this.post, required this.postComment}); @override State createState() { @@ -27,11 +27,11 @@ class OBReactToPostCommentBottomSheet extends StatefulWidget { class OBReactToPostCommentBottomSheetState extends State { - UserService _userService; - ToastService _toastService; + late UserService _userService; + late ToastService _toastService; - bool _isReactToPostCommentInProgress; - CancelableOperation _reactOperation; + late bool _isReactToPostCommentInProgress; + CancelableOperation? _reactOperation; @override void initState() { @@ -42,7 +42,7 @@ class OBReactToPostCommentBottomSheetState @override void dispose() { super.dispose(); - if (_reactOperation != null) _reactOperation.cancel(); + if (_reactOperation != null) _reactOperation!.cancel(); } @override @@ -76,7 +76,7 @@ class OBReactToPostCommentBottomSheetState ); } - Future _reactToPostComment(Emoji emoji, EmojiGroup emojiGroup) async { + Future _reactToPostComment(Emoji emoji, EmojiGroup? emojiGroup) async { if (_isReactToPostCommentInProgress) return null; _setReactToPostCommentInProgress(true); @@ -87,7 +87,7 @@ class OBReactToPostCommentBottomSheetState postComment: widget.postComment, emoji: emoji)); - PostCommentReaction postCommentReaction = await _reactOperation.value; + PostCommentReaction postCommentReaction = await _reactOperation!.value; widget.postComment.setReaction(postCommentReaction); // Remove modal Navigator.pop(context); @@ -105,8 +105,8 @@ class OBReactToPostCommentBottomSheetState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/home/bottom_sheets/rounded_bottom_sheet.dart b/lib/pages/home/bottom_sheets/rounded_bottom_sheet.dart index 9ecd6d6e9..775681768 100644 --- a/lib/pages/home/bottom_sheets/rounded_bottom_sheet.dart +++ b/lib/pages/home/bottom_sheets/rounded_bottom_sheet.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; class OBRoundedBottomSheet extends StatelessWidget { final Widget child; - const OBRoundedBottomSheet({@required this.child}); + const OBRoundedBottomSheet({required this.child}); @override Widget build(BuildContext context) { diff --git a/lib/pages/home/bottom_sheets/user_actions/user_actions.dart b/lib/pages/home/bottom_sheets/user_actions/user_actions.dart index e187b7ea9..d4801a37f 100644 --- a/lib/pages/home/bottom_sheets/user_actions/user_actions.dart +++ b/lib/pages/home/bottom_sheets/user_actions/user_actions.dart @@ -34,7 +34,7 @@ class OBUserActionsBottomSheet extends StatelessWidget { stream: user.updateSubject, initialData: user, builder: (BuildContext context, AsyncSnapshot snapshot) { - var user = snapshot.data; + var user = snapshot.data!; List moreTiles = []; @@ -77,15 +77,15 @@ class OBUserActionsBottomSheet extends StatelessWidget { }, )); - if (user.isConnected && - !user.isFullyConnected && - !user.isPendingConnectionConfirmation) { + if (user.isConnected! && + !user.isFullyConnected! && + !user.isPendingConnectionConfirmation!) { moreTiles.add(OBDisconnectFromUserTile(user, onDisconnectedFromUser: _dismissModalBottomSheet, title: localizationService.user__profile_action_cancel_connection)); moreTiles.add(OBUpdateConnectionWithUserTile(user)); - } else if (user.isPendingConnectionConfirmation) { + } else if (user.isPendingConnectionConfirmation!) { moreTiles.add(OBConfirmConnectionWithUserTile( user, onWillShowModalBottomSheet: _dismissModalBottomSheet, @@ -93,7 +93,7 @@ class OBUserActionsBottomSheet extends StatelessWidget { moreTiles.add(OBDisconnectFromUserTile(user, onDisconnectedFromUser: _dismissModalBottomSheet, title: localizationService.user__profile_action_deny_connection)); - } else if (user.isFullyConnected) { + } else if (user.isFullyConnected!) { moreTiles.add(OBUpdateConnectionWithUserTile(user)); moreTiles.add(OBDisconnectFromUserTile(user, onDisconnectedFromUser: _dismissModalBottomSheet)); @@ -104,7 +104,7 @@ class OBUserActionsBottomSheet extends StatelessWidget { )); } - User loggedInUser = openbookProvider.userService.getLoggedInUser(); + User loggedInUser = openbookProvider.userService.getLoggedInUser()!; if (loggedInUser.canBlockOrUnblockUser(user)) { moreTiles.add(OBBlockUserTile( diff --git a/lib/pages/home/bottom_sheets/user_actions/widgets/add_account_to_list_tile.dart b/lib/pages/home/bottom_sheets/user_actions/widgets/add_account_to_list_tile.dart index b84183a89..4de42e8f9 100644 --- a/lib/pages/home/bottom_sheets/user_actions/widgets/add_account_to_list_tile.dart +++ b/lib/pages/home/bottom_sheets/user_actions/widgets/add_account_to_list_tile.dart @@ -12,10 +12,10 @@ import 'package:flutter/material.dart'; class OBAddAccountToList extends StatefulWidget { final User user; - final VoidCallback onWillShowModalBottomSheet; + final VoidCallback? onWillShowModalBottomSheet; const OBAddAccountToList(this.user, - {Key key, this.onWillShowModalBottomSheet}) + {Key? key, this.onWillShowModalBottomSheet}) : super(key: key); @override @@ -25,10 +25,10 @@ class OBAddAccountToList extends StatefulWidget { } class OBAddAccountToListState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - BottomSheetService _bottomSheetService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late BottomSheetService _bottomSheetService; @override Widget build(BuildContext context) { @@ -49,7 +49,7 @@ class OBAddAccountToListState extends State { void _displayAddConnectionToFollowsListsBottomSheet() async { if (widget.onWillShowModalBottomSheet != null) - widget.onWillShowModalBottomSheet(); + widget.onWillShowModalBottomSheet!(); var initialPickedLists = widget.user.followLists?.lists; @@ -70,13 +70,13 @@ class OBAddAccountToListState extends State { } Future _connectUserInFollowsLists(List followsLists) async { - bool isAlreadyFollowingUser = widget.user.isFollowing; + bool isAlreadyFollowingUser = widget.user.isFollowing ?? false; try { await (isAlreadyFollowingUser - ? _userService.updateFollowWithUsername(widget.user.username, + ? _userService.updateFollowWithUsername(widget.user.username!, followsLists: followsLists) - : _userService.followUserWithUsername(widget.user.username, + : _userService.followUserWithUsername(widget.user.username!, followsLists: followsLists)); if (!isAlreadyFollowingUser) { widget.user.incrementFollowersCount(); @@ -92,8 +92,8 @@ class OBAddAccountToListState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/bottom_sheets/user_actions/widgets/confirm_connection_with_user_tile.dart b/lib/pages/home/bottom_sheets/user_actions/widgets/confirm_connection_with_user_tile.dart index 1fd0eba95..ecb809c8b 100644 --- a/lib/pages/home/bottom_sheets/user_actions/widgets/confirm_connection_with_user_tile.dart +++ b/lib/pages/home/bottom_sheets/user_actions/widgets/confirm_connection_with_user_tile.dart @@ -12,10 +12,10 @@ import 'package:flutter/material.dart'; class OBConfirmConnectionWithUserTile extends StatefulWidget { final User user; - final VoidCallback onWillShowModalBottomSheet; + final VoidCallback? onWillShowModalBottomSheet; const OBConfirmConnectionWithUserTile(this.user, - {Key key, this.onWillShowModalBottomSheet}) + {Key? key, this.onWillShowModalBottomSheet}) : super(key: key); @override @@ -26,10 +26,10 @@ class OBConfirmConnectionWithUserTile extends StatefulWidget { class OBConfirmConnectionWithUserTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - BottomSheetService _bottomSheetService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late BottomSheetService _bottomSheetService; @override Widget build(BuildContext context) { @@ -39,7 +39,7 @@ class OBConfirmConnectionWithUserTileState _localizationService = openbookProvider.localizationService; _bottomSheetService = openbookProvider.bottomSheetService; - String userName = widget.user.getProfileName(); + String userName = widget.user.getProfileName()!; return ListTile( title: OBText(_localizationService.user__confirm_connection_with(userName)), @@ -49,7 +49,7 @@ class OBConfirmConnectionWithUserTileState void _displayAddConnectionToCirclesBottomSheet() { if (widget.onWillShowModalBottomSheet != null) - widget.onWillShowModalBottomSheet(); + widget.onWillShowModalBottomSheet!(); _bottomSheetService.showConnectionsCirclesPicker( context: context, title: _localizationService.trans('user__confirm_connection_add_connection'), @@ -64,9 +64,9 @@ class OBConfirmConnectionWithUserTileState Future _confirmConnectionWithUser(List circles) async { try { await _userService.confirmConnectionWithUserWithUsername( - widget.user.username, + widget.user.username!, circles: circles); - if (!widget.user.isFollowing) widget.user.incrementFollowersCount(); + if (!widget.user.isFollowing!) widget.user.incrementFollowersCount(); _toastService.success(message: _localizationService.trans('user__confirm_connection_connection_confirmed'), context: context); } catch (error) { _onError(error); @@ -78,8 +78,8 @@ class OBConfirmConnectionWithUserTileState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/bottom_sheets/user_actions/widgets/connect_to_user_tile.dart b/lib/pages/home/bottom_sheets/user_actions/widgets/connect_to_user_tile.dart index b2dd053df..06c586dfd 100644 --- a/lib/pages/home/bottom_sheets/user_actions/widgets/connect_to_user_tile.dart +++ b/lib/pages/home/bottom_sheets/user_actions/widgets/connect_to_user_tile.dart @@ -13,10 +13,10 @@ import 'package:flutter/material.dart'; class OBConnectToUserTile extends StatefulWidget { final User user; final BuildContext parentContext; - final VoidCallback onWillShowModalBottomSheet; + final VoidCallback? onWillShowModalBottomSheet; const OBConnectToUserTile(this.user, this.parentContext, - {Key key, this.onWillShowModalBottomSheet}) + {Key? key, this.onWillShowModalBottomSheet}) : super(key: key); @override @@ -26,10 +26,10 @@ class OBConnectToUserTile extends StatefulWidget { } class OBConnectToUserTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - BottomSheetService _bottomSheetService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late BottomSheetService _bottomSheetService; @override Widget build(BuildContext context) { @@ -39,7 +39,7 @@ class OBConnectToUserTileState extends State { _localizationService = openbookProvider.localizationService; _bottomSheetService = openbookProvider.bottomSheetService; - String userName = widget.user.getProfileName(); + String userName = widget.user.getProfileName()!; return ListTile( title: OBText(_localizationService.user__connect_to_user_connect_with_username(userName)), @@ -49,7 +49,7 @@ class OBConnectToUserTileState extends State { void _displayAddConnectionToCirclesBottomSheet() { if (widget.onWillShowModalBottomSheet != null) - widget.onWillShowModalBottomSheet(); + widget.onWillShowModalBottomSheet!(); _bottomSheetService.showConnectionsCirclesPicker( context: context, @@ -64,10 +64,10 @@ class OBConnectToUserTileState extends State { Future _connectUserInCircles(List circles) async { try { - bool userWasFollowing = widget.user.isFollowing; - await _userService.connectWithUserWithUsername(widget.user.username, + bool userWasFollowing = widget.user.isFollowing ?? false; + await _userService.connectWithUserWithUsername(widget.user.username!, circles: circles); - if (!userWasFollowing && widget.user.isFollowing) { + if (!userWasFollowing && (widget.user.isFollowing ?? false)) { widget.user.incrementFollowersCount(); } _toastService.success( @@ -82,8 +82,8 @@ class OBConnectToUserTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/bottom_sheets/user_actions/widgets/disconnect_from_user_tile.dart b/lib/pages/home/bottom_sheets/user_actions/widgets/disconnect_from_user_tile.dart index 447caaa5b..c443a107a 100644 --- a/lib/pages/home/bottom_sheets/user_actions/widgets/disconnect_from_user_tile.dart +++ b/lib/pages/home/bottom_sheets/user_actions/widgets/disconnect_from_user_tile.dart @@ -10,11 +10,11 @@ import 'package:flutter/material.dart'; class OBDisconnectFromUserTile extends StatefulWidget { final User user; - final String title; + final String? title; final VoidCallback onDisconnectedFromUser; const OBDisconnectFromUserTile(this.user, - {Key key, this.title, @required this.onDisconnectedFromUser}) + {Key? key, this.title, required this.onDisconnectedFromUser}) : super(key: key); @override @@ -24,9 +24,9 @@ class OBDisconnectFromUserTile extends StatefulWidget { } class OBDisconnectFromUserTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; @override Widget build(BuildContext context) { @@ -35,7 +35,7 @@ class OBDisconnectFromUserTileState extends State { _toastService = openbookProvider.toastService; _localizationService = openbookProvider.localizationService; - String userName = widget.user.getProfileName(); + String userName = widget.user.getProfileName()!; return ListTile( title: OBText(widget.title ?? _localizationService.user__disconnect_from_user(userName)), @@ -48,7 +48,7 @@ class OBDisconnectFromUserTileState extends State { Future _disconnectFromUser() async { try { - await _userService.disconnectFromUserWithUsername(widget.user.username); + await _userService.disconnectFromUserWithUsername(widget.user.username!); widget.user.decrementFollowersCount(); _toastService.success( message: _localizationService.user__disconnect_from_user_success, context: context); @@ -62,8 +62,8 @@ class OBDisconnectFromUserTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/bottom_sheets/user_actions/widgets/new_post_notifications_for_user_tile.dart b/lib/pages/home/bottom_sheets/user_actions/widgets/new_post_notifications_for_user_tile.dart index 3b58a6541..ba1900bdd 100644 --- a/lib/pages/home/bottom_sheets/user_actions/widgets/new_post_notifications_for_user_tile.dart +++ b/lib/pages/home/bottom_sheets/user_actions/widgets/new_post_notifications_for_user_tile.dart @@ -11,12 +11,12 @@ import 'package:flutter/material.dart'; class OBNewPostNotificationsForUserTile extends StatefulWidget { final User user; - final VoidCallback onSubscribed; - final VoidCallback onUnsubscribed; + final VoidCallback? onSubscribed; + final VoidCallback? onUnsubscribed; const OBNewPostNotificationsForUserTile({ - Key key, - @required this.user, + Key? key, + required this.user, this.onSubscribed, this.onUnsubscribed, }) : super(key: key); @@ -28,10 +28,10 @@ class OBNewPostNotificationsForUserTile extends StatefulWidget { } class OBNewPostNotificationsForUserTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -50,7 +50,7 @@ class OBNewPostNotificationsForUserTileState extends State snapshot) { - var user = snapshot.data; + var user = snapshot.data!; bool areNotificationsEnabled = user.areNewPostNotificationsEnabled ?? false; @@ -70,7 +70,7 @@ class OBNewPostNotificationsForUserTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; @override Widget build(BuildContext context) { @@ -43,10 +43,10 @@ class OBRemoveAccountFromListsState extends State { Future _removeAccountFromLists() async { try { await _userService - .updateFollowWithUsername(widget.user.username, followsLists: []); + .updateFollowWithUsername(widget.user.username!, followsLists: []); _toastService.success(message: _localizationService.trans('user__remove_account_from_list_success'), context: context); if (widget.onRemovedAccountFromLists != null) - widget.onRemovedAccountFromLists(); + widget.onRemovedAccountFromLists!(); } catch (error) { _onError(error); } @@ -57,8 +57,8 @@ class OBRemoveAccountFromListsState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/bottom_sheets/user_actions/widgets/update_connection_with_user_tile.dart b/lib/pages/home/bottom_sheets/user_actions/widgets/update_connection_with_user_tile.dart index 546ace052..47c094e9d 100644 --- a/lib/pages/home/bottom_sheets/user_actions/widgets/update_connection_with_user_tile.dart +++ b/lib/pages/home/bottom_sheets/user_actions/widgets/update_connection_with_user_tile.dart @@ -14,7 +14,7 @@ class OBUpdateConnectionWithUserTile extends StatefulWidget { final User user; const OBUpdateConnectionWithUserTile(this.user, - {Key key}) + {Key? key}) : super(key: key); @override @@ -25,10 +25,10 @@ class OBUpdateConnectionWithUserTile extends StatefulWidget { class OBUpdateConnectionWithUserTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - BottomSheetService _bottomSheetService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late BottomSheetService _bottomSheetService; @override Widget build(BuildContext context) { @@ -45,7 +45,7 @@ class OBUpdateConnectionWithUserTileState } void _displayAddConnectionToCirclesBottomSheet() { - List connectedCircles = widget.user.connectedCircles.circles; + List connectedCircles = widget.user.connectedCircles!.circles!; _bottomSheetService.showConnectionsCirclesPicker( context: context, @@ -61,9 +61,9 @@ class OBUpdateConnectionWithUserTileState Future _updateConnectionWithUser(List circles) async { try { - await _userService.updateConnectionWithUsername(widget.user.username, + await _userService.updateConnectionWithUsername(widget.user.username!, circles: circles); - if (!widget.user.isFollowing) widget.user.incrementFollowersCount(); + if (!widget.user.isFollowing!) widget.user.incrementFollowersCount(); _toastService.success(message: _localizationService.trans('user__update_connection_circle_updated'), context: context); } catch (error) { _onError(error); @@ -75,8 +75,8 @@ class OBUpdateConnectionWithUserTileState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/bottom_sheets/user_visibility_picker.dart b/lib/pages/home/bottom_sheets/user_visibility_picker.dart index c3f333576..5013b982f 100644 --- a/lib/pages/home/bottom_sheets/user_visibility_picker.dart +++ b/lib/pages/home/bottom_sheets/user_visibility_picker.dart @@ -22,18 +22,18 @@ class OBUserVisibilityPickerBottomSheet extends StatefulWidget { class OBUserVisibilityPickerBottomSheetState extends State { - ToastService _toastService; - LocalizationService _localizationService; - UserService _userService; - bool _needsBootstrap; + late ToastService _toastService; + late LocalizationService _localizationService; + late UserService _userService; + late bool _needsBootstrap; - bool _isUserVisibilityPickerInProgress; - CancelableOperation _userVisibilityPickerOperation; + late bool _isUserVisibilityPickerInProgress; + CancelableOperation? _userVisibilityPickerOperation; - Map> _userVisibilitiesLocalizationMap; + late Map> _userVisibilitiesLocalizationMap; - UserVisibility _selectedUserVisibility; - UserVisibility _currentUserVisibility; + late UserVisibility _selectedUserVisibility; + late UserVisibility _currentUserVisibility; @override void initState() { @@ -54,7 +54,7 @@ class OBUserVisibilityPickerBottomSheetState var openbookProvider = OpenbookProvider.of(context); _userService = openbookProvider.userService; _currentUserVisibility = - openbookProvider.userService.getLoggedInUser().visibility; + openbookProvider.userService.getLoggedInUser()!.visibility!; _selectedUserVisibility = _currentUserVisibility; _toastService = openbookProvider.toastService; _localizationService = openbookProvider.localizationService; @@ -79,9 +79,9 @@ class OBUserVisibilityPickerBottomSheetState OBCheckboxField( leading: OBUserVisibilityIcon(visibility: UserVisibility.public,), value: _selectedUserVisibility == UserVisibility.public, - title: _userVisibilitiesLocalizationMap[UserVisibility.public]['title'], - subtitle: _userVisibilitiesLocalizationMap[UserVisibility.public] - ['description'], + title: _userVisibilitiesLocalizationMap[UserVisibility.public]!['title']!, + subtitle: _userVisibilitiesLocalizationMap[UserVisibility.public]! + ['description']!, onTap: () { _setSelectedVisibility(UserVisibility.public); }, @@ -90,9 +90,9 @@ class OBUserVisibilityPickerBottomSheetState OBCheckboxField( leading: OBUserVisibilityIcon(visibility: UserVisibility.okuna,), value: _selectedUserVisibility == UserVisibility.okuna, - title: _userVisibilitiesLocalizationMap[UserVisibility.okuna]['title'], - subtitle: _userVisibilitiesLocalizationMap[UserVisibility.okuna] - ['description'], + title: _userVisibilitiesLocalizationMap[UserVisibility.okuna]!['title']!, + subtitle: _userVisibilitiesLocalizationMap[UserVisibility.okuna]! + ['description']!, onTap: () { _setSelectedVisibility(UserVisibility.okuna); }, @@ -101,10 +101,10 @@ class OBUserVisibilityPickerBottomSheetState OBCheckboxField( leading: OBUserVisibilityIcon(visibility: UserVisibility.private,), value: _selectedUserVisibility == UserVisibility.private, - title: _userVisibilitiesLocalizationMap[UserVisibility.private] - ['title'], - subtitle: _userVisibilitiesLocalizationMap[UserVisibility.private] - ['description'], + title: _userVisibilitiesLocalizationMap[UserVisibility.private]! + ['title']!, + subtitle: _userVisibilitiesLocalizationMap[UserVisibility.private]! + ['description']!, onTap: () { _setSelectedVisibility(UserVisibility.private); }, @@ -146,7 +146,7 @@ class OBUserVisibilityPickerBottomSheetState try { _userVisibilityPickerOperation = CancelableOperation.fromFuture( _userService.updateUser(visibility: _selectedUserVisibility)); - await _userVisibilityPickerOperation.value; + await _userVisibilityPickerOperation?.value; Navigator.pop(context); } catch (error) { _onError(error); @@ -166,8 +166,8 @@ class OBUserVisibilityPickerBottomSheetState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/bottom_sheets/video_picker.dart b/lib/pages/home/bottom_sheets/video_picker.dart index 142d44a65..d160edcd1 100644 --- a/lib/pages/home/bottom_sheets/video_picker.dart +++ b/lib/pages/home/bottom_sheets/video_picker.dart @@ -9,11 +9,12 @@ import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; class OBVideoPickerBottomSheet extends StatelessWidget { - const OBVideoPickerBottomSheet({Key key}) : super(key: key); + const OBVideoPickerBottomSheet({Key? key}) : super(key: key); @override Widget build(BuildContext context) { var provider = OpenbookProvider.of(context); + var imagePicker = ImagePicker(); LocalizationService localizationService = provider.localizationService; @@ -27,11 +28,11 @@ class OBVideoPickerBottomSheet extends StatelessWidget { bool permissionGranted = await provider.permissionService .requestStoragePermissions(context: context); if (permissionGranted) { - FilePickerResult result = - await FilePicker.platform.pickFiles(type: FileType.video); + PickedFile? pickedFile = + await imagePicker.getVideo(source: ImageSource.gallery); - if (result != null) { - File file = File(result.files.single.path); + if (pickedFile != null) { + File file = File(pickedFile.path); Navigator.pop(context, file); } } @@ -46,8 +47,9 @@ class OBVideoPickerBottomSheet extends StatelessWidget { bool permissionGranted = await provider.permissionService .requestCameraPermissions(context: context); if (permissionGranted) { - File pickedVideo = - await ImagePicker.pickVideo(source: ImageSource.camera); + PickedFile? pickedFile = + await imagePicker.getVideo(source: ImageSource.camera); + File? pickedVideo = pickedFile != null ? File(pickedFile.path) : null; Navigator.pop(context, pickedVideo); } }, diff --git a/lib/pages/home/bottom_sheets/videos_autoplay_setting_picker.dart b/lib/pages/home/bottom_sheets/videos_autoplay_setting_picker.dart index 0fabbba7f..19339922d 100644 --- a/lib/pages/home/bottom_sheets/videos_autoplay_setting_picker.dart +++ b/lib/pages/home/bottom_sheets/videos_autoplay_setting_picker.dart @@ -8,10 +8,10 @@ import 'package:flutter/material.dart'; class OBVideosAutoPlaySettingPickerBottomSheet extends StatefulWidget { final ValueChanged onTypeChanged; - final VideosAutoPlaySetting initialValue; + final VideosAutoPlaySetting? initialValue; const OBVideosAutoPlaySettingPickerBottomSheet( - {Key key, @required this.onTypeChanged, this.initialValue}) + {Key? key, required this.onTypeChanged, this.initialValue}) : super(key: key); @override @@ -22,8 +22,8 @@ class OBVideosAutoPlaySettingPickerBottomSheet extends StatefulWidget { class OBVideosAutoPlaySettingPickerBottomSheetState extends State { - FixedExtentScrollController _cupertinoPickerController; - List allVideosAutoPlaySettings; + late FixedExtentScrollController _cupertinoPickerController; + late List allVideosAutoPlaySettings; @override void initState() { @@ -31,8 +31,8 @@ class OBVideosAutoPlaySettingPickerBottomSheetState allVideosAutoPlaySettings = VideosAutoPlaySetting.values(); _cupertinoPickerController = FixedExtentScrollController( initialItem: widget.initialValue != null - ? allVideosAutoPlaySettings.indexOf(widget.initialValue) - : null); + ? allVideosAutoPlaySettings.indexOf(widget.initialValue!) + : 0); } @override @@ -56,7 +56,7 @@ class OBVideosAutoPlaySettingPickerBottomSheetState itemExtent: 32, children: allVideosAutoPlaySettings.map((VideosAutoPlaySetting setting) { - return OBText(localizationMap[setting]); + return OBText(localizationMap[setting]!); }).toList(), ), ), diff --git a/lib/pages/home/bottom_sheets/videos_sound_setting_picker.dart b/lib/pages/home/bottom_sheets/videos_sound_setting_picker.dart index 3adb5ac03..ebf2f03c0 100644 --- a/lib/pages/home/bottom_sheets/videos_sound_setting_picker.dart +++ b/lib/pages/home/bottom_sheets/videos_sound_setting_picker.dart @@ -9,10 +9,10 @@ import 'package:flutter/material.dart'; class OBVideosSoundSettingPickerBottomSheet extends StatefulWidget { final ValueChanged onTypeChanged; - final VideosSoundSetting initialValue; + final VideosSoundSetting? initialValue; const OBVideosSoundSettingPickerBottomSheet( - {Key key, @required this.onTypeChanged, this.initialValue}) + {Key? key, required this.onTypeChanged, this.initialValue}) : super(key: key); @override @@ -23,8 +23,8 @@ class OBVideosSoundSettingPickerBottomSheet extends StatefulWidget { class OBVideosSoundSettingPickerBottomSheetState extends State { - FixedExtentScrollController _cupertinoPickerController; - List allVideosSoundSettings; + late FixedExtentScrollController _cupertinoPickerController; + late List allVideosSoundSettings; @override void initState() { @@ -32,8 +32,8 @@ class OBVideosSoundSettingPickerBottomSheetState allVideosSoundSettings = VideosSoundSetting.values(); _cupertinoPickerController = FixedExtentScrollController( initialItem: widget.initialValue != null - ? allVideosSoundSettings.indexOf(widget.initialValue) - : null); + ? allVideosSoundSettings.indexOf(widget.initialValue!) + : 0); } @override @@ -58,7 +58,7 @@ class OBVideosSoundSettingPickerBottomSheetState itemExtent: 32, children: allVideosSoundSettings.map((VideosSoundSetting setting) { return Center( - child: OBText(localizationMap[setting]), + child: OBText(localizationMap[setting]!), ); }).toList(), ), diff --git a/lib/pages/home/dialogs/video_dialog.dart b/lib/pages/home/dialogs/video_dialog.dart index 75e6cf0b7..5e1d91c3d 100644 --- a/lib/pages/home/dialogs/video_dialog.dart +++ b/lib/pages/home/dialogs/video_dialog.dart @@ -7,14 +7,14 @@ import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; class OBVideoDialog extends StatelessWidget { - final File video; - final String videoUrl; - final ChewieController chewieController; - final VideoPlayerController videoPlayerController; + final File? video; + final String? videoUrl; + final ChewieController? chewieController; + final VideoPlayerController? videoPlayerController; final bool autoPlay; const OBVideoDialog( - {Key key, + {Key? key, this.video, this.videoUrl, this.autoPlay = false, diff --git a/lib/pages/home/home.dart b/lib/pages/home/home.dart index 91cc85244..af752cdf9 100644 --- a/lib/pages/home/home.dart +++ b/lib/pages/home/home.dart @@ -41,39 +41,39 @@ class OBHomePage extends StatefulWidget { class OBHomePageState extends State with WidgetsBindingObserver { static const String oneSignalAppId = '66074bf4-9943-4504-a011-531c2635698b'; - UserService _userService; - ToastService _toastService; - PushNotificationsService _pushNotificationsService; - IntercomService _intercomService; - ModalService _modalService; - UserPreferencesService _userPreferencesService; - ShareService _shareService; - MediaService _mediaService; - - int _currentIndex; - int _lastIndex; - bool _needsBootstrap; - - StreamSubscription _loggedInUserChangeSubscription; - StreamSubscription _loggedInUserUpdateSubscription; - StreamSubscription _pushNotificationOpenedSubscription; - StreamSubscription _pushNotificationSubscription; - - OBTimelinePageController _timelinePageController; - OBOwnProfilePageController _ownProfilePageController; - OBMainSearchPageController _searchPageController; - OBMainMenuPageController _mainMenuPageController; - OBCommunitiesPageController _communitiesPageController; - OBNotificationsPageController _notificationsPageController; - - int _loggedInUserUnreadNotifications; - String _loggedInUserAvatarUrl; + late UserService _userService; + late ToastService _toastService; + late PushNotificationsService _pushNotificationsService; + late IntercomService _intercomService; + late ModalService _modalService; + late UserPreferencesService _userPreferencesService; + late ShareService _shareService; + late MediaService _mediaService; + + late int _currentIndex; + late int _lastIndex; + late bool _needsBootstrap; + + late StreamSubscription _loggedInUserChangeSubscription; + StreamSubscription? _loggedInUserUpdateSubscription; + StreamSubscription? _pushNotificationOpenedSubscription; + StreamSubscription? _pushNotificationSubscription; + + late OBTimelinePageController _timelinePageController; + late OBOwnProfilePageController _ownProfilePageController; + late OBMainSearchPageController _searchPageController; + late OBMainMenuPageController _mainMenuPageController; + late OBCommunitiesPageController _communitiesPageController; + late OBNotificationsPageController _notificationsPageController; + + late int _loggedInUserUnreadNotifications; + String? _loggedInUserAvatarUrl; @override void initState() { super.initState(); BackButtonInterceptor.add(_backButtonInterceptor); - WidgetsBinding.instance.addObserver(this); + WidgetsBinding.instance?.addObserver(this); _needsBootstrap = true; _loggedInUserUnreadNotifications = 0; _lastIndex = 0; @@ -90,15 +90,15 @@ class OBHomePageState extends State void dispose() { super.dispose(); BackButtonInterceptor.remove(_backButtonInterceptor); - WidgetsBinding.instance.removeObserver(this); + WidgetsBinding.instance?.removeObserver(this); _loggedInUserChangeSubscription.cancel(); if (_loggedInUserUpdateSubscription != null) - _loggedInUserUpdateSubscription.cancel(); + _loggedInUserUpdateSubscription!.cancel(); if (_pushNotificationOpenedSubscription != null) { - _pushNotificationOpenedSubscription.cancel(); + _pushNotificationOpenedSubscription!.cancel(); } if (_pushNotificationSubscription != null) { - _pushNotificationSubscription.cancel(); + _pushNotificationSubscription!.cancel(); } } @@ -170,7 +170,7 @@ class OBHomePageState extends State return page; } - Widget _createTabBar() { + OBCupertinoTabBar _createTabBar() { return OBCupertinoTabBar( backgroundColor: Colors.white, currentIndex: _currentIndex, @@ -319,7 +319,7 @@ class OBHomePageState extends State if (error is AuthTokenMissingError) { _logout(); } else if (error is HttpieRequestError) { - HttpieResponse response = error.response; + HttpieResponse response = error.response as HttpieResponse; if (response.isForbidden() || response.isUnauthorized()) { _logout(unsubscribePushNotifications: true); } else { @@ -386,7 +386,7 @@ class OBHomePageState extends State return preventCloseApp; } - void _onLoggedInUserChange(User newUser) async { + void _onLoggedInUserChange(User? newUser) async { if (newUser == null) { Navigator.pushReplacementNamed(context, '/auth'); } else { @@ -404,11 +404,11 @@ class OBHomePageState extends State .listen(_onPushNotification); if (newUser.areGuidelinesAccepted != null && - !newUser.areGuidelinesAccepted) { + !(newUser.areGuidelinesAccepted!)) { _modalService.openAcceptGuidelines(context: context); } - if (newUser.language == null || !supportedLanguages.contains(newUser.language.code)) { + if (newUser.language == null || !supportedLanguages.contains(newUser.language!.code)) { _userService.setLanguageFromDefaults(); } _userService.checkAndClearTempDirectories(); @@ -421,7 +421,7 @@ class OBHomePageState extends State if (currentTab != OBHomePageTabs.notifications) { // When a user taps in notifications, notifications count should be removed // Therefore if the user is already there, dont increment. - User loggedInUser = _userService.getLoggedInUser(); + User? loggedInUser = _userService.getLoggedInUser(); if (loggedInUser != null) { loggedInUser.incrementUnreadNotificationsCount(); } @@ -433,7 +433,7 @@ class OBHomePageState extends State //_navigateToTab(OBHomePageTabs.notifications); } - Future _onShare({String text, File image, File video}) async { + Future _onShare({String? text, File? image, File? video}) async { bool postCreated = await _timelinePageController.createPost( text: text, image: image, video: video); @@ -470,11 +470,11 @@ class OBHomePageState extends State _setAvatarUrl(user.getProfileAvatar()); OBHomePageTabs currentTab = _getCurrentTab(); if (currentTab != OBHomePageTabs.notifications) { - _setUnreadNotifications(user.unreadNotificationsCount); + _setUnreadNotifications(user.unreadNotificationsCount ?? 0); } } - void _setAvatarUrl(String avatarUrl) { + void _setAvatarUrl(String? avatarUrl) { setState(() { _loggedInUserAvatarUrl = avatarUrl; }); @@ -491,7 +491,7 @@ class OBHomePageState extends State } void _resetLoggedInUserUnreadNotificationsCount() { - User loggedInUser = _userService.getLoggedInUser(); + User? loggedInUser = _userService.getLoggedInUser(); if (loggedInUser != null) { loggedInUser.resetUnreadNotificationsCount(); } @@ -502,8 +502,8 @@ class OBHomePageState extends State _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/home/lib/draft_editing_controller.dart b/lib/pages/home/lib/draft_editing_controller.dart index 785aaf117..fce003438 100644 --- a/lib/pages/home/lib/draft_editing_controller.dart +++ b/lib/pages/home/lib/draft_editing_controller.dart @@ -3,20 +3,20 @@ import 'package:flutter/material.dart'; abstract class DraftTextEditingController extends TextEditingController { final DraftService _draftService; - String _previousText; + String? _previousText; DraftTextEditingController(this._draftService) { addListener(_onChanged); } factory DraftTextEditingController.comment(int postId, - {int commentId, String text, @required DraftService draftService}) { + {required int? commentId, String? text, required DraftService draftService}) { return _CommentDraftEditingController( postId, commentId, text, draftService); } factory DraftTextEditingController.post( - {int communityId, String text, @required DraftService draftService}) { + {int? communityId, String? text, required DraftService draftService}) { return _PostDraftEditingController(communityId, text, draftService); } @@ -35,10 +35,10 @@ abstract class DraftTextEditingController extends TextEditingController { class _CommentDraftEditingController extends DraftTextEditingController { final int postId; - final int commentId; + final int? commentId; _CommentDraftEditingController( - this.postId, this.commentId, String text, DraftService draftService) + this.postId, this.commentId, String? text, DraftService draftService) : super(draftService) { if (text == null) { this.text = _draftService.getCommentDraft(postId, commentId); @@ -57,10 +57,10 @@ class _CommentDraftEditingController extends DraftTextEditingController { } class _PostDraftEditingController extends DraftTextEditingController { - final int communityId; + final int? communityId; _PostDraftEditingController( - this.communityId, String text, DraftService draftService) + this.communityId, String? text, DraftService draftService) : super(draftService) { if (text == null) { this.text = _draftService.getPostDraft(communityId); diff --git a/lib/pages/home/lib/poppable_page_controller.dart b/lib/pages/home/lib/poppable_page_controller.dart index 75f86c85e..64b1d02e2 100644 --- a/lib/pages/home/lib/poppable_page_controller.dart +++ b/lib/pages/home/lib/poppable_page_controller.dart @@ -1,9 +1,9 @@ import 'package:flutter/material.dart'; class PoppablePageController { - BuildContext _context; + late BuildContext _context; - void attach({@required BuildContext context}) { + void attach({required BuildContext context}) { _context = context; } @@ -12,12 +12,12 @@ class PoppablePageController { } bool isFirstRoute() { - Route currentRoute; + Route? currentRoute; Navigator.popUntil(_context, (route) { currentRoute = route; return true; }); - return currentRoute.isFirst; + return currentRoute?.isFirst ?? false; } bool canPop() { diff --git a/lib/pages/home/modals/accept_guidelines/accept_guidelines.dart b/lib/pages/home/modals/accept_guidelines/accept_guidelines.dart index 1aeecc329..4b17ad58a 100644 --- a/lib/pages/home/modals/accept_guidelines/accept_guidelines.dart +++ b/lib/pages/home/modals/accept_guidelines/accept_guidelines.dart @@ -22,18 +22,18 @@ class OBAcceptGuidelinesModal extends StatefulWidget { } class OBAcceptGuidelinesModalState extends State { - NavigationService _navigationService; - ToastService _toastService; - LocalizationService _localizationService; - UserService _userService; - String _guidelinesText; - bool _needsBootstrap; - bool _acceptButtonEnabled; - bool _acceptGuidelinesInProgress; - bool _refreshGuidelinesInProgress; - ScrollController _guidelinesScrollController; - - CancelableOperation _getGuidelinesOperation; + late NavigationService _navigationService; + late ToastService _toastService; + late LocalizationService _localizationService; + late UserService _userService; + late String _guidelinesText; + late bool _needsBootstrap; + late bool _acceptButtonEnabled; + late bool _acceptGuidelinesInProgress; + late bool _refreshGuidelinesInProgress; + late ScrollController _guidelinesScrollController; + + CancelableOperation? _getGuidelinesOperation; @override void initState() { @@ -50,7 +50,7 @@ class OBAcceptGuidelinesModalState extends State { @override void dispose() { super.dispose(); - if (_getGuidelinesOperation != null) _getGuidelinesOperation.cancel(); + if (_getGuidelinesOperation != null) _getGuidelinesOperation!.cancel(); } void _bootstrap() async { @@ -150,7 +150,7 @@ class OBAcceptGuidelinesModalState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { return OBButton( type: OBButtonType.danger, minWidth: double.infinity, @@ -177,8 +177,10 @@ class OBAcceptGuidelinesModalState extends State { _getGuidelinesOperation = CancelableOperation.fromFuture( openbookProvider.documentsService.getCommunityGuidelines()); - String guidelines = await _getGuidelinesOperation.value; - _setGuidelinesText(guidelines); + String? guidelines = await _getGuidelinesOperation?.value; + if (guidelines != null) { + _setGuidelinesText(guidelines); + } } catch (error) { _onError(error); } finally { @@ -204,8 +206,8 @@ class OBAcceptGuidelinesModalState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/modals/accept_guidelines/pages/confirm_reject_guidelines.dart b/lib/pages/home/modals/accept_guidelines/pages/confirm_reject_guidelines.dart index dc7d3ba5e..f70cd17f2 100644 --- a/lib/pages/home/modals/accept_guidelines/pages/confirm_reject_guidelines.dart +++ b/lib/pages/home/modals/accept_guidelines/pages/confirm_reject_guidelines.dart @@ -19,10 +19,10 @@ class OBConfirmRejectGuidelines extends StatefulWidget { } class OBConfirmRejectGuidelinesState extends State { - bool _confirmationInProgress; - UserService _userService; - ToastService _toastService; - bool _needsBootstrap; + late bool _confirmationInProgress; + late UserService _userService; + late ToastService _toastService; + late bool _needsBootstrap; @override void initState() { diff --git a/lib/pages/home/modals/confirm_block_user.dart b/lib/pages/home/modals/confirm_block_user.dart index ac75d2709..75dc7c575 100644 --- a/lib/pages/home/modals/confirm_block_user.dart +++ b/lib/pages/home/modals/confirm_block_user.dart @@ -14,7 +14,7 @@ import 'package:flutter/cupertino.dart'; class OBConfirmBlockUserModal extends StatefulWidget { final User user; - const OBConfirmBlockUserModal({Key key, @required this.user}) : super(key: key); + const OBConfirmBlockUserModal({Key? key, required this.user}) : super(key: key); @override OBConfirmBlockUserModalState createState() { @@ -23,11 +23,11 @@ class OBConfirmBlockUserModal extends StatefulWidget { } class OBConfirmBlockUserModalState extends State { - bool _confirmationInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late bool _confirmationInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; @override void initState() { @@ -38,7 +38,7 @@ class OBConfirmBlockUserModalState extends State { @override Widget build(BuildContext context) { - String username = widget.user.username; + String username = widget.user.username!; if (_needsBootstrap) { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); @@ -132,8 +132,8 @@ class OBConfirmBlockUserModalState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/modals/invite_to_community.dart b/lib/pages/home/modals/invite_to_community.dart index 2248c86c2..9d6160b23 100644 --- a/lib/pages/home/modals/invite_to_community.dart +++ b/lib/pages/home/modals/invite_to_community.dart @@ -18,7 +18,7 @@ import 'package:flutter/material.dart'; class OBInviteToCommunityModal extends StatefulWidget { final Community community; - const OBInviteToCommunityModal({Key key, @required this.community}) + const OBInviteToCommunityModal({Key? key, required this.community}) : super(key: key); @override @@ -28,10 +28,10 @@ class OBInviteToCommunityModal extends StatefulWidget { } class OBInviteToCommunityModalState extends State { - UserService _userService; - LocalizationService _localizationService; + late UserService _userService; + late LocalizationService _localizationService; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -88,7 +88,7 @@ class OBInviteToCommunityModalState extends State { Future> _refreshLinkedUsers() async { UsersList linkedUsers = await _userService.getLinkedUsers(withCommunity: widget.community); - return linkedUsers.users; + return linkedUsers.users!; } Future> _loadMoreLinkedUsers(List linkedUsersList) async { @@ -99,13 +99,13 @@ class OBInviteToCommunityModalState extends State { count: 10, withCommunity: widget.community)) .users; - return moreLinkedUsers; + return moreLinkedUsers!; } Future> _searchLinkedUsers(String query) async { UsersList results = await _userService.searchLinkedUsers( query: query, withCommunity: widget.community); - return results.users; + return results.users!; } } diff --git a/lib/pages/home/modals/post_comment/post_comment_reply_expanded.dart b/lib/pages/home/modals/post_comment/post_comment_reply_expanded.dart index d56a6fca2..890b6af56 100644 --- a/lib/pages/home/modals/post_comment/post_comment_reply_expanded.dart +++ b/lib/pages/home/modals/post_comment/post_comment_reply_expanded.dart @@ -24,13 +24,13 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBPostCommentReplyExpandedModal extends StatefulWidget { - final Post post; - final PostComment postComment; - final Function(PostComment) onReplyAdded; - final Function(PostComment) onReplyDeleted; + final Post? post; + final PostComment? postComment; + final Function(PostComment)? onReplyAdded; + final Function(PostComment)? onReplyDeleted; const OBPostCommentReplyExpandedModal( - {Key key, + {Key? key, this.post, this.postComment, this.onReplyAdded, @@ -45,21 +45,21 @@ class OBPostCommentReplyExpandedModal extends StatefulWidget { class OBPostCommentReplyExpandedModalState extends OBContextualSearchBoxState { - ValidationService _validationService; - ToastService _toastService; - LocalizationService _localizationService; - UserService _userService; - DraftService _draftService; + late ValidationService _validationService; + late ToastService _toastService; + late LocalizationService _localizationService; + late UserService _userService; + late DraftService _draftService; - DraftTextEditingController _textController; - int _charactersCount; - bool _isPostCommentTextAllowedLength; - List _postCommentItemsWidgets; - ScrollController _scrollController; + late DraftTextEditingController _textController; + late int _charactersCount; + late bool _isPostCommentTextAllowedLength; + late List _postCommentItemsWidgets; + late ScrollController _scrollController; - CancelableOperation _postCommentReplyOperation; - bool _requestInProgress; - bool _needsBootstrap; + CancelableOperation? _postCommentReplyOperation; + late bool _requestInProgress; + late bool _needsBootstrap; @override void initState() { @@ -74,7 +74,7 @@ class OBPostCommentReplyExpandedModalState @override void dispose() { super.dispose(); - if (_postCommentReplyOperation != null) _postCommentReplyOperation.cancel(); + if (_postCommentReplyOperation != null) _postCommentReplyOperation!.cancel(); _textController.removeListener(_onPostCommentTextChanged); } @@ -82,8 +82,8 @@ class OBPostCommentReplyExpandedModalState void bootstrap() { super.bootstrap(); - _textController = DraftTextEditingController.comment(widget.post.id, - commentId: widget.postComment != null ? widget.postComment.id : null, + _textController = DraftTextEditingController.comment(widget.post!.id!, + commentId: widget.postComment != null ? widget.postComment!.id : null, draftService: _draftService); _textController.addListener(_onPostCommentTextChanged); setAutocompleteTextController(_textController); @@ -138,7 +138,7 @@ class OBPostCommentReplyExpandedModalState Column(mainAxisSize: MainAxisSize.max, children: bodyItems))); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { bool isPrimaryActionButtonIsEnabled = (_isPostCommentTextAllowedLength && _charactersCount > 0); @@ -155,9 +155,9 @@ class OBPostCommentReplyExpandedModalState ); } - Widget _buildPrimaryActionButton({bool isEnabled}) { + Widget _buildPrimaryActionButton({bool? isEnabled}) { return OBButton( - isDisabled: !isEnabled, + isDisabled: !(isEnabled ?? false), isLoading: _requestInProgress, size: OBButtonSize.small, onPressed: _onWantsToReplyComment, @@ -171,12 +171,12 @@ class OBPostCommentReplyExpandedModalState try { _postCommentReplyOperation = CancelableOperation.fromFuture( _userService.replyPostComment( - post: widget.post, - postComment: widget.postComment, + post: widget.post!, + postComment: widget.postComment!, text: _textController.text)); - PostComment comment = await _postCommentReplyOperation.value; - if (widget.onReplyAdded != null) widget.onReplyAdded(comment); + PostComment comment = await _postCommentReplyOperation?.value; + if (widget.onReplyAdded != null) widget.onReplyAdded!(comment); Navigator.pop(context, comment); } catch (error) { _onError(error); @@ -253,8 +253,8 @@ class OBPostCommentReplyExpandedModalState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/modals/post_comment/post_commenter_expanded.dart b/lib/pages/home/modals/post_comment/post_commenter_expanded.dart index 9359828aa..dc16398a4 100644 --- a/lib/pages/home/modals/post_comment/post_commenter_expanded.dart +++ b/lib/pages/home/modals/post_comment/post_commenter_expanded.dart @@ -21,9 +21,9 @@ import 'package:flutter/material.dart'; class OBPostCommenterExpandedModal extends StatefulWidget { final Post post; - final PostComment postComment; + final PostComment? postComment; - const OBPostCommenterExpandedModal({Key key, this.post, this.postComment}) + const OBPostCommenterExpandedModal({Key? key, required this.post, this.postComment}) : super(key: key); @override @@ -34,33 +34,33 @@ class OBPostCommenterExpandedModal extends StatefulWidget { class OBPostCommenterExpandedModalState extends OBContextualSearchBoxState { - ValidationService _validationService; - ToastService _toastService; - UserService _userService; - LocalizationService _localizationService; - - TextEditingController _textController; - int _charactersCount; - bool _isPostCommentTextAllowedLength; - bool _isPostCommentTextOriginal; - List _postCommentItemsWidgets; - String _originalText; - bool _requestInProgress; - bool _needsBootstrap; - - CancelableOperation _postCommentOperation; + late ValidationService _validationService; + late ToastService _toastService; + late UserService _userService; + late LocalizationService _localizationService; + + late TextEditingController _textController; + late int _charactersCount; + late bool _isPostCommentTextAllowedLength; + late bool _isPostCommentTextOriginal; + late List _postCommentItemsWidgets; + late String _originalText; + late bool _requestInProgress; + late bool _needsBootstrap; + + CancelableOperation? _postCommentOperation; @override void initState() { super.initState(); _textController = TextEditingController( - text: widget.postComment != null ? widget.postComment.text : ''); + text: widget.postComment?.text ?? ''); _textController.addListener(_onPostCommentTextChanged); setAutocompleteTextController(_textController); _charactersCount = 0; _isPostCommentTextAllowedLength = false; _isPostCommentTextOriginal = false; - _originalText = widget.postComment.text; + _originalText = widget.postComment?.text ?? ''; _requestInProgress = false; _needsBootstrap = true; } @@ -69,13 +69,13 @@ class OBPostCommenterExpandedModalState void dispose() { super.dispose(); _textController.removeListener(_onPostCommentTextChanged); - if (_postCommentOperation != null) _postCommentOperation.cancel(); + if (_postCommentOperation != null) _postCommentOperation!.cancel(); } @override void bootstrap() { super.bootstrap(); - String hintText = widget.post.commentsCount > 0 + String hintText = widget.post.commentsCount! > 0 ? _localizationService.post__commenter_expanded_join_conversation : _localizationService.post__commenter_expanded_start_conversation; _postCommentItemsWidgets = [ @@ -109,7 +109,7 @@ class OBPostCommenterExpandedModalState ))); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { bool isPrimaryActionButtonIsEnabled = (_isPostCommentTextAllowedLength && _charactersCount > 0 && !_isPostCommentTextOriginal); @@ -127,7 +127,7 @@ class OBPostCommenterExpandedModalState ); } - Widget _buildPrimaryActionButton({bool isEnabled}) { + Widget _buildPrimaryActionButton({bool isEnabled = false}) { return OBButton( isDisabled: !isEnabled, isLoading: _requestInProgress, @@ -192,10 +192,10 @@ class OBPostCommenterExpandedModalState _postCommentOperation = CancelableOperation.fromFuture( _userService.editPostComment( post: widget.post, - postComment: widget.postComment, + postComment: widget.postComment!, text: _textController.text)); - PostComment comment = await _postCommentOperation.value; + PostComment? comment = await _postCommentOperation?.value; Navigator.pop(context, comment); } catch (error) { _onError(error); @@ -210,8 +210,8 @@ class OBPostCommenterExpandedModalState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/modals/post_comment_reactions/post_comment_reactions.dart b/lib/pages/home/modals/post_comment_reactions/post_comment_reactions.dart index 0e09b7122..90f73a0bb 100644 --- a/lib/pages/home/modals/post_comment_reactions/post_comment_reactions.dart +++ b/lib/pages/home/modals/post_comment_reactions/post_comment_reactions.dart @@ -20,17 +20,17 @@ class OBPostCommentReactionsModal extends StatefulWidget { final Post post; // The optional emoji to show first - final Emoji reactionEmoji; + final Emoji? reactionEmoji; // The post comment reaction emoji counts - final List reactionsEmojiCounts; + final List reactionsEmojiCounts; const OBPostCommentReactionsModal( - {Key key, - @required this.postComment, + {Key? key, + required this.postComment, this.reactionEmoji, - @required this.reactionsEmojiCounts, - @required this.post}) + required this.reactionsEmojiCounts, + required this.post}) : super(key: key); @override @@ -41,11 +41,11 @@ class OBPostCommentReactionsModal extends StatefulWidget { class OBPostCommentReactionsModalState extends State with TickerProviderStateMixin { - ThemeService _themeService; - ThemeValueParserService _themeValueParserService; - bool _needsBootstrap; + late ThemeService _themeService; + late ThemeValueParserService _themeValueParserService; + late bool _needsBootstrap; - TabController _tabController; + late TabController _tabController; @override void initState() { @@ -95,24 +95,32 @@ class OBPostCommentReactionsModalState List _buildPostCommentReactionsTabs() { return widget.reactionsEmojiCounts.map((reactionsEmojiCount) { + if (reactionsEmojiCount == null) { + return SizedBox(); + } + return OBPostCommentReactionList( postComment: widget.postComment, post: widget.post, - emoji: reactionsEmojiCount.emoji, + emoji: reactionsEmojiCount.emoji!, ); }).toList(); } List _buildPostCommentReactionsIcons() { return widget.reactionsEmojiCounts.map((reactionsEmojiCount) { + if (reactionsEmojiCount == null) { + return SizedBox(); + } + return Padding( padding: EdgeInsets.symmetric(vertical: 5), - child: Tab(icon: OBEmoji(reactionsEmojiCount.emoji)), + child: Tab(icon: OBEmoji(reactionsEmojiCount.emoji!)), ); }).toList(); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar(title: 'Post comment reactions'); } @@ -121,7 +129,7 @@ class OBPostCommentReactionsModalState if (widget.reactionEmoji != null) { tabIndex = widget.reactionsEmojiCounts.indexWhere((reactionEmojiCount) { - return reactionEmojiCount.emoji.id == widget.reactionEmoji.id; + return reactionEmojiCount?.emoji?.id == widget.reactionEmoji!.id; }); } diff --git a/lib/pages/home/modals/post_comment_reactions/widgets/post_comment_reaction_list.dart b/lib/pages/home/modals/post_comment_reactions/widgets/post_comment_reaction_list.dart index f6266f1fe..061a33a07 100644 --- a/lib/pages/home/modals/post_comment_reactions/widgets/post_comment_reaction_list.dart +++ b/lib/pages/home/modals/post_comment_reactions/widgets/post_comment_reaction_list.dart @@ -21,10 +21,10 @@ class OBPostCommentReactionList extends StatefulWidget { final Post post; const OBPostCommentReactionList( - {Key key, - @required this.emoji, - @required this.postComment, - @required this.post}) + {Key? key, + required this.emoji, + required this.postComment, + required this.post}) : super(key: key); @override @@ -34,12 +34,12 @@ class OBPostCommentReactionList extends StatefulWidget { } class OBPostCommentReactionListState extends State { - UserService _userService; - NavigationService _navigationService; + late UserService _userService; + late NavigationService _navigationService; - bool _needsBootstrap; + late bool _needsBootstrap; - OBHttpListController _httpListController; + late OBHttpListController _httpListController; @override void initState() { @@ -79,7 +79,7 @@ class OBPostCommentReactionListState extends State { void _onPostCommentReactionListItemPressed( PostCommentReaction postCommentReaction) { _navigationService.navigateToUserProfile( - user: postCommentReaction.reactor, context: context); + user: postCommentReaction.reactor!, context: context); } Future> _refreshPostCommentReactions() async { @@ -88,13 +88,13 @@ class OBPostCommentReactionListState extends State { post: widget.post, postComment: widget.postComment, emoji: widget.emoji); - return postCommentReactions.reactions; + return postCommentReactions.reactions!; } Future> _loadMorePostCommentReactions( List postCommentReactionsList) async { PostCommentReaction lastPostCommentReaction = postCommentReactionsList.last; - int lastPostCommentReactionId = lastPostCommentReaction.id; + int? lastPostCommentReactionId = lastPostCommentReaction.id; List morePostCommentReactions = (await _userService.getReactionsForPostComment( post: widget.post, @@ -103,7 +103,7 @@ class OBPostCommentReactionListState extends State { emoji: widget.emoji, count: 20, )) - .reactions; + .reactions!; return morePostCommentReactions; } } diff --git a/lib/pages/home/modals/post_reactions/post_reactions.dart b/lib/pages/home/modals/post_reactions/post_reactions.dart index 561a23a4b..5d5771020 100644 --- a/lib/pages/home/modals/post_reactions/post_reactions.dart +++ b/lib/pages/home/modals/post_reactions/post_reactions.dart @@ -19,16 +19,16 @@ class OBPostReactionsModal extends StatefulWidget { final Post post; // The optional emoji to show first - final Emoji reactionEmoji; + final Emoji? reactionEmoji; // The post reactiosn emoji counts - final List reactionsEmojiCounts; + final List reactionsEmojiCounts; const OBPostReactionsModal( - {Key key, - @required this.post, + {Key? key, + required this.post, this.reactionEmoji, - @required this.reactionsEmojiCounts}) + required this.reactionsEmojiCounts}) : super(key: key); @override @@ -39,12 +39,12 @@ class OBPostReactionsModal extends StatefulWidget { class OBPostReactionsModalState extends State with TickerProviderStateMixin { - ThemeService _themeService; - LocalizationService _localizationService; - ThemeValueParserService _themeValueParserService; - bool _needsBootstrap; + late ThemeService _themeService; + late LocalizationService _localizationService; + late ThemeValueParserService _themeValueParserService; + late bool _needsBootstrap; - TabController _tabController; + late TabController _tabController; @override void initState() { @@ -97,21 +97,25 @@ class OBPostReactionsModalState extends State return widget.reactionsEmojiCounts.map((reactionsEmojiCount) { return OBPostReactionList( post: widget.post, - emoji: reactionsEmojiCount.emoji, + emoji: reactionsEmojiCount?.emoji, ); }).toList(); } List _buildPostReactionsIcons() { return widget.reactionsEmojiCounts.map((reactionsEmojiCount) { + if (reactionsEmojiCount == null) { + return SizedBox(); + } + return Padding( padding: EdgeInsets.symmetric(vertical: 5), - child: Tab(icon: OBEmoji(reactionsEmojiCount.emoji)), + child: Tab(icon: OBEmoji(reactionsEmojiCount.emoji!)), ); }).toList(); } - Widget _buildNavigationBar(LocalizationService localizationService) { + ObstructingPreferredSizeWidget _buildNavigationBar(LocalizationService localizationService) { return OBThemedNavigationBar( title: localizationService.post__post_reactions_title); } @@ -121,7 +125,7 @@ class OBPostReactionsModalState extends State if (widget.reactionEmoji != null) { tabIndex = widget.reactionsEmojiCounts.indexWhere((reactionEmojiCount) { - return reactionEmojiCount.emoji.id == widget.reactionEmoji.id; + return reactionEmojiCount?.emoji?.id == widget.reactionEmoji!.id; }); } diff --git a/lib/pages/home/modals/post_reactions/widgets/post_reaction_list.dart b/lib/pages/home/modals/post_reactions/widgets/post_reaction_list.dart index 19e1b9e7a..381ff5850 100644 --- a/lib/pages/home/modals/post_reactions/widgets/post_reaction_list.dart +++ b/lib/pages/home/modals/post_reactions/widgets/post_reaction_list.dart @@ -14,12 +14,12 @@ import 'package:Okuna/widgets/load_more.dart'; class OBPostReactionList extends StatefulWidget { // The emoji to show reactions of - final Emoji emoji; + final Emoji? emoji; // The post to show reactions of - final Post post; + final Post? post; - const OBPostReactionList({Key key, this.emoji, this.post}) : super(key: key); + const OBPostReactionList({Key? key, this.emoji, this.post}) : super(key: key); @override OBPostReactionListState createState() { @@ -28,15 +28,15 @@ class OBPostReactionList extends StatefulWidget { } class OBPostReactionListState extends State { - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - List _postReactions; + late List _postReactions; - bool _needsBootstrap; - bool _loadMoreFinished; + late bool _needsBootstrap; + late bool _loadMoreFinished; final GlobalKey _refreshIndicatorKey = GlobalKey(); @@ -89,7 +89,7 @@ class OBPostReactionListState extends State { } Future _refreshPostReactions() async { - var reactionsList = await _userService.getReactionsForPost(widget.post, + var reactionsList = await _userService.getReactionsForPost(widget.post!, emoji: widget.emoji); _setPostReactions(reactionsList.reactions); @@ -99,14 +99,14 @@ class OBPostReactionListState extends State { var lastReaction = _postReactions.last; var lastReactionId = lastReaction.id; try { - var moreReactions = (await _userService.getReactionsForPost(widget.post, + var moreReactions = (await _userService.getReactionsForPost(widget.post!, maxId: lastReactionId, emoji: widget.emoji)) .reactions; - if (moreReactions.length == 0) { + if (moreReactions != null && moreReactions.length == 0) { _setLoadMoreFinished(true); } else { - _addPostReactions(moreReactions); + _addPostReactions(moreReactions ?? []); } return true; } catch (error) { @@ -121,20 +121,28 @@ class OBPostReactionListState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; } } - void _onPostReactionTilePressed(PostReaction postReaction) { + void _onPostReactionTilePressed(PostReaction? postReaction) { + if (postReaction == null) { + return; + } + _navigationService.navigateToUserProfile( - user: postReaction.reactor, context: context); + user: postReaction.reactor!, context: context); } - void _setPostReactions(List reactions) { + void _setPostReactions(List? reactions) { + if (reactions == null) { + return; + } + setState(() { _postReactions = reactions; }); diff --git a/lib/pages/home/modals/save_community.dart b/lib/pages/home/modals/save_community.dart index cef6516b0..2df4fe0ab 100644 --- a/lib/pages/home/modals/save_community.dart +++ b/lib/pages/home/modals/save_community.dart @@ -29,7 +29,7 @@ import 'package:flutter/material.dart'; import 'package:pigment/pigment.dart'; class OBSaveCommunityModal extends StatefulWidget { - final Community community; + final Community? community; const OBSaveCommunityModal({this.community}); @@ -40,38 +40,38 @@ class OBSaveCommunityModal extends StatefulWidget { } class OBSaveCommunityModalState extends State { - UserService _userService; - ToastService _toastService; - ValidationService _validationService; - MediaService _imagePickerService; - LocalizationService _localizationService; - ThemeValueParserService _themeValueParserService; - - bool _requestInProgress; - bool _formWasSubmitted; - bool _formValid; - bool _isEditingExistingCommunity; - String _takenName; - - GlobalKey _formKey; - - TextEditingController _nameController; - TextEditingController _titleController; - TextEditingController _descriptionController; - TextEditingController _userAdjectiveController; - TextEditingController _usersAdjectiveController; - TextEditingController _rulesController; - OBCategoriesFieldController _categoriesFieldController; - - String _color; - CommunityType _type; - String _avatarUrl; - String _coverUrl; - File _avatarFile; - File _coverFile; - bool _invitesEnabled; - - List _categories; + late UserService _userService; + late ToastService _toastService; + late ValidationService _validationService; + late MediaService _imagePickerService; + late LocalizationService _localizationService; + late ThemeValueParserService _themeValueParserService; + + late bool _requestInProgress; + late bool _formWasSubmitted; + late bool _formValid; + late bool _isEditingExistingCommunity; + String? _takenName; + + late GlobalKey _formKey; + + late TextEditingController _nameController; + late TextEditingController _titleController; + late TextEditingController _descriptionController; + late TextEditingController _userAdjectiveController; + late TextEditingController _usersAdjectiveController; + late TextEditingController _rulesController; + late OBCategoriesFieldController _categoriesFieldController; + + String? _color; + CommunityType? _type; + String? _avatarUrl; + String? _coverUrl; + File? _avatarFile; + File? _coverFile; + bool? _invitesEnabled; + + late List _categories; @override void initState() { @@ -94,18 +94,18 @@ class OBSaveCommunityModalState extends State { _isEditingExistingCommunity = widget.community != null; if (_isEditingExistingCommunity) { - _nameController.text = widget.community.name; - _titleController.text = widget.community.title; - _descriptionController.text = widget.community.description; - _userAdjectiveController.text = widget.community.userAdjective; - _usersAdjectiveController.text = widget.community.usersAdjective; - _rulesController.text = widget.community.rules; - _color = widget.community.color; - _categories = widget.community.categories.categories.toList(); - _type = widget.community.type; - _avatarUrl = widget.community.avatar; - _coverUrl = widget.community.cover; - _invitesEnabled = widget.community.invitesEnabled; + _nameController.text = widget.community!.name ?? ''; + _titleController.text = widget.community!.title ?? ''; + _descriptionController.text = widget.community!.description ?? ''; + _userAdjectiveController.text = widget.community!.userAdjective ?? ''; + _usersAdjectiveController.text = widget.community!.usersAdjective ?? ''; + _rulesController.text = widget.community!.rules ?? ''; + _color = widget.community!.color; + _categories = widget.community!.categories?.categories?.toList() ?? []; + _type = widget.community!.type; + _avatarUrl = widget.community!.avatar; + _coverUrl = widget.community!.cover; + _invitesEnabled = widget.community!.invitesEnabled; } _nameController.addListener(_updateFormValid); @@ -177,7 +177,7 @@ class OBSaveCommunityModalState extends State { hintText: _localizationService.community__save_community_label_title_hint_text, prefixIcon: const OBIcon(OBIcons.communities), ), - validator: (String communityTitle) { + validator: (String? communityTitle) { return _validationService .validateCommunityTitle(communityTitle); }), @@ -192,10 +192,10 @@ class OBSaveCommunityModalState extends State { prefixText: 'c/', hintText: _localizationService.community__save_community_name_title_hint_text), - validator: (String communityName) { + validator: (String? communityName) { if (_takenName != null && _takenName == communityName) { - return _localizationService.community__save_community_name_taken(_takenName); + return _localizationService.community__save_community_name_taken(_takenName!); } return _validationService @@ -208,7 +208,7 @@ class OBSaveCommunityModalState extends State { hintText: _localizationService.community__save_community_name_label_color_hint_text, ), OBCommunityTypeField( - value: _type, + value: _type!, title: _localizationService.community__save_community_name_label_type, hintText: _localizationService.community__save_community_name_label_type_hint_text, onChanged: (CommunityType type) { @@ -219,7 +219,7 @@ class OBSaveCommunityModalState extends State { ), _type == CommunityType.private ? OBToggleField( - value: _invitesEnabled, + value: _invitesEnabled ?? false, title: _localizationService.community__save_community_name_member_invites, subtitle: OBText( _localizationService.community__save_community_name_member_invites_subtitle), @@ -230,7 +230,7 @@ class OBSaveCommunityModalState extends State { }, onTap: () { setState(() { - _invitesEnabled = !_invitesEnabled; + _invitesEnabled = !(_invitesEnabled ?? false); }); }, ) @@ -256,7 +256,7 @@ class OBSaveCommunityModalState extends State { OBIcons.communityDescription), labelText: _localizationService.community__save_community_name_label_desc_optional, hintText: _localizationService.community__save_community_name_label_desc_optional_hint_text), - validator: (String communityDescription) { + validator: (String? communityDescription) { return _validationService .validateCommunityDescription( communityDescription); @@ -271,7 +271,7 @@ class OBSaveCommunityModalState extends State { labelText: _localizationService.community__save_community_name_label_rules_optional, hintText: _localizationService.community__save_community_name_label_rules_optional_hint_text), - validator: (String communityRules) { + validator: (String? communityRules) { return _validationService .validateCommunityRules(communityRules); }, @@ -290,7 +290,7 @@ class OBSaveCommunityModalState extends State { labelText: _localizationService.community__save_community_name_label_member_adjective, hintText: _localizationService.community__save_community_name_label_member_adjective_hint_text), - validator: (String communityUserAdjective) { + validator: (String? communityUserAdjective) { return _validationService .validateCommunityUserAdjective( communityUserAdjective); @@ -306,7 +306,7 @@ class OBSaveCommunityModalState extends State { labelText: _localizationService.community__save_community_name_label_members_adjective, hintText: _localizationService.community__save_community_name_label_members_adjective_hint_text), - validator: (String communityUsersAdjective) { + validator: (String? communityUsersAdjective) { return _validationService .validateCommunityUserAdjective( communityUsersAdjective); @@ -319,8 +319,8 @@ class OBSaveCommunityModalState extends State { )); } - Widget _buildNavigationBar() { - Color color = _themeValueParserService.parseColor(_color); + ObstructingPreferredSizeWidget _buildNavigationBar() { + Color color = _themeValueParserService.parseColor(_color!); bool isDarkColor = _themeValueParserService.isDarkColor(color); Color actionsColor = isDarkColor ? Colors.white : Colors.black; @@ -354,7 +354,7 @@ class OBSaveCommunityModalState extends State { bool hasAvatar = hasAvatarFile || hasAvatarUrl; - Function _onPressed = hasAvatar ? _clearAvatar : _pickNewAvatar; + VoidCallback _onPressed = hasAvatar ? _clearAvatar : _pickNewAvatar; Widget icon = Icon( hasAvatar ? Icons.clear : Icons.edit, @@ -373,7 +373,7 @@ class OBSaveCommunityModalState extends State { } else { avatar = OBLetterAvatar( size: OBAvatarSize.large, - color: Pigment.fromString(_color), + color: Pigment.fromString(_color!), letter: _nameController.text.isEmpty ? 'C' : _nameController.text[0]); } @@ -400,7 +400,7 @@ class OBSaveCommunityModalState extends State { } void _pickNewAvatar() async { - File newAvatar = + File? newAvatar = await _imagePickerService.pickImage(imageType: OBImageType.avatar, context: context); if (newAvatar != null) _setAvatarFile(newAvatar); } @@ -410,7 +410,7 @@ class OBSaveCommunityModalState extends State { bool hasCoverUrl = _coverUrl != null; bool hasCover = hasCoverFile || hasCoverUrl; - Function _onPressed = hasCover ? _clearCover : _pickNewCover; + VoidCallback _onPressed = hasCover ? _clearCover : _pickNewCover; Widget icon = Icon( hasCover ? Icons.clear : Icons.edit, @@ -444,7 +444,7 @@ class OBSaveCommunityModalState extends State { } void _pickNewCover() async { - File newCover = + File? newCover = await _imagePickerService.pickImage(imageType: OBImageType.cover, context: context); if (newCover != null) _setCoverFile(newCover); } @@ -465,7 +465,7 @@ class OBSaveCommunityModalState extends State { _setAvatarFile(null); } - void _setAvatarFile(File avatarFile) { + void _setAvatarFile(File? avatarFile) { setState(() { _avatarFile = avatarFile; }); @@ -480,14 +480,14 @@ class OBSaveCommunityModalState extends State { _setCoverFile(null); } - void _setCoverFile(File coverFile) { + void _setCoverFile(File? coverFile) { setState(() { _coverFile = coverFile; }); } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { @@ -532,8 +532,8 @@ class OBSaveCommunityModalState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -544,8 +544,8 @@ class OBSaveCommunityModalState extends State { await _updateCommunityAvatar(); await _updateCommunityCover(); - return _userService.updateCommunity(widget.community, - name: _nameController.text != widget.community.name + return _userService.updateCommunity(widget.community!, + name: _nameController.text != widget.community!.name ? _nameController.text : null, title: _titleController.text, @@ -564,22 +564,22 @@ class OBSaveCommunityModalState extends State { bool hasCoverUrl = _coverUrl != null; bool hasCover = hasCoverFile || hasCoverUrl; - Future updateFuture; + Future? updateFuture; if (!hasCover) { - if (widget.community.cover != null) { + if (widget.community?.cover != null) { // Remove cover! - updateFuture = _userService.deleteCoverForCommunity(widget.community); + updateFuture = _userService.deleteCoverForCommunity(widget.community!); } } else if (hasCoverFile) { // New cover - updateFuture = _userService.updateCoverForCommunity(widget.community, - cover: _coverFile); + updateFuture = _userService.updateCoverForCommunity(widget.community!, + cover: _coverFile!); } else { updateFuture = Future.value(); } - return updateFuture; + return updateFuture ?? Future.value(); } Future _updateCommunityAvatar() { @@ -587,27 +587,27 @@ class OBSaveCommunityModalState extends State { bool hasAvatarUrl = _avatarUrl != null; bool hasAvatar = hasAvatarFile || hasAvatarUrl; - Future updateFuture; + Future? updateFuture; if (!hasAvatar) { - if (widget.community.avatar != null) { + if (widget.community!.avatar != null) { // Remove avatar! - updateFuture = _userService.deleteAvatarForCommunity(widget.community); + updateFuture = _userService.deleteAvatarForCommunity(widget.community!); } } else if (hasAvatarFile) { // New avatar - updateFuture = _userService.updateAvatarForCommunity(widget.community, - avatar: _avatarFile); + updateFuture = _userService.updateAvatarForCommunity(widget.community!, + avatar: _avatarFile!); } else { updateFuture = Future.value(); } - return updateFuture; + return updateFuture ?? Future.value(); } Future _createCommunity() { return _userService.createCommunity( - type: _type, + type: _type ?? CommunityType.public, name: _nameController.text, title: _titleController.text, description: _descriptionController.text, @@ -623,7 +623,7 @@ class OBSaveCommunityModalState extends State { Future _isNameTaken(String communityName) async { if (_isEditingExistingCommunity && - widget.community.name == _nameController.text) { + widget.community?.name == _nameController.text) { return false; } return _validationService.isCommunityNameTaken(communityName); diff --git a/lib/pages/home/modals/save_connections_circle.dart b/lib/pages/home/modals/save_connections_circle.dart index 3dd795ce4..600e1c761 100644 --- a/lib/pages/home/modals/save_connections_circle.dart +++ b/lib/pages/home/modals/save_connections_circle.dart @@ -19,7 +19,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBSaveConnectionsCircleModal extends StatefulWidget { - final Circle connectionsCircle; + final Circle? connectionsCircle; final bool autofocusNameTextField; OBSaveConnectionsCircleModal( @@ -35,22 +35,22 @@ class OBSaveConnectionsCircleModalState extends State { static const double INPUT_COLORS_SIZE = 16; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - ValidationService _validationService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late ValidationService _validationService; - bool _requestInProgress; - bool _formWasSubmitted; - bool _formValid; - bool _hasExistingCircle; - String _takenConnectionsCircleName; - List _users; + late bool _requestInProgress; + late bool _formWasSubmitted; + late bool _formValid; + late bool _hasExistingCircle; + String? _takenConnectionsCircleName; + late List _users; - GlobalKey _formKey; + late GlobalKey _formKey; - TextEditingController _nameController; - String _color; + late TextEditingController _nameController; + String? _color; @override void initState() { @@ -61,13 +61,13 @@ class OBSaveConnectionsCircleModalState _nameController = TextEditingController(); _formKey = GlobalKey(); _hasExistingCircle = widget.connectionsCircle != null; - _users = _hasExistingCircle && widget.connectionsCircle.hasUsers() - ? widget.connectionsCircle.users.users.toList() + _users = _hasExistingCircle && widget.connectionsCircle!.hasUsers() + ? widget.connectionsCircle!.users!.users!.toList() : []; if (_hasExistingCircle) { - _nameController.text = widget.connectionsCircle.name; - _color = widget.connectionsCircle.color; + _nameController.text = widget.connectionsCircle!.name ?? ''; + _color = widget.connectionsCircle!.color; } _nameController.addListener(_updateFormValid); @@ -107,13 +107,13 @@ class OBSaveConnectionsCircleModalState decoration: InputDecoration( labelText: _localizationService.trans('user__save_connection_circle_name'), hintText: _localizationService.trans('user__save_connection_circle_hint')), - validator: (String connectionsCircleName) { + validator: (String? connectionsCircleName) { if (!_formWasSubmitted) return null; if (_takenConnectionsCircleName != null && _takenConnectionsCircleName == connectionsCircleName) { - return _localizationService.user__save_connection_circle_name_taken(_takenConnectionsCircleName); + return _localizationService.user__save_connection_circle_name_taken(_takenConnectionsCircleName!); } return _validationService @@ -157,7 +157,7 @@ class OBSaveConnectionsCircleModalState )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( leading: GestureDetector( child: const OBIcon(OBIcons.close), @@ -177,7 +177,7 @@ class OBSaveConnectionsCircleModalState } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { @@ -206,8 +206,8 @@ class OBSaveConnectionsCircleModalState } Circle connectionsCircle = await (_hasExistingCircle - ? _userService.updateConnectionsCircle(widget.connectionsCircle, - name: _nameController.text != widget.connectionsCircle.name + ? _userService.updateConnectionsCircle(widget.connectionsCircle!, + name: _nameController.text != widget.connectionsCircle!.name ? _nameController.text : null, users: _users, @@ -228,8 +228,8 @@ class OBSaveConnectionsCircleModalState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; @@ -239,7 +239,7 @@ class OBSaveConnectionsCircleModalState Future _isConnectionsCircleNameTaken( String connectionsCircleName) async { if (_hasExistingCircle && - widget.connectionsCircle.name == _nameController.text) { + widget.connectionsCircle?.name == _nameController.text) { return false; } return _validationService diff --git a/lib/pages/home/modals/save_follows_list/pages/pick_follows_list_emoji.dart b/lib/pages/home/modals/save_follows_list/pages/pick_follows_list_emoji.dart index 2b93386d6..cf47f0d11 100644 --- a/lib/pages/home/modals/save_follows_list/pages/pick_follows_list_emoji.dart +++ b/lib/pages/home/modals/save_follows_list/pages/pick_follows_list_emoji.dart @@ -15,7 +15,7 @@ class OBPickFollowsListEmojiPage extends StatelessWidget { ), child: OBPrimaryColorContainer( child: OBEmojiPicker( - onEmojiPicked: (Emoji pickedEmoji, EmojiGroup emojiGroup) { + onEmojiPicked: (Emoji? pickedEmoji, EmojiGroup? emojiGroup) { Navigator.pop(context, pickedEmoji); }, ), diff --git a/lib/pages/home/modals/save_follows_list/save_follows_list.dart b/lib/pages/home/modals/save_follows_list/save_follows_list.dart index c08647f13..9cc8a6e27 100644 --- a/lib/pages/home/modals/save_follows_list/save_follows_list.dart +++ b/lib/pages/home/modals/save_follows_list/save_follows_list.dart @@ -21,7 +21,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBSaveFollowsListModal extends StatefulWidget { - final FollowsList followsList; + final FollowsList? followsList; final bool autofocusNameTextField; OBSaveFollowsListModal( @@ -36,22 +36,22 @@ class OBSaveFollowsListModal extends StatefulWidget { class OBSaveFollowsListModalState extends State { static const double INPUT_EMOJIS_SIZE = 16; - UserService _userService; - ToastService _toastService; - ValidationService _validationService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ValidationService _validationService; + late LocalizationService _localizationService; - bool _requestInProgress; - bool _formWasSubmitted; - bool _formValid; - bool _hasExistingList; - String _takenFollowsListName; - List _users; + late bool _requestInProgress; + late bool _formWasSubmitted; + late bool _formValid; + late bool _hasExistingList; + String? _takenFollowsListName; + late List _users; - GlobalKey _formKey; + late GlobalKey _formKey; - TextEditingController _nameController; - Emoji _emoji; + late TextEditingController _nameController; + Emoji? _emoji; @override void initState() { @@ -62,13 +62,13 @@ class OBSaveFollowsListModalState extends State { _nameController = TextEditingController(); _formKey = GlobalKey(); _hasExistingList = widget.followsList != null; - _users = _hasExistingList && widget.followsList.hasUsers() - ? widget.followsList.users.users.toList() + _users = _hasExistingList && widget.followsList!.hasUsers() + ? widget.followsList!.users!.users!.toList() : []; if (_hasExistingList) { - _nameController.text = widget.followsList.name; - _emoji = widget.followsList.emoji; + _nameController.text = widget.followsList!.name!; + _emoji = widget.followsList!.emoji; } _nameController.addListener(_updateFormValid); @@ -105,13 +105,13 @@ class OBSaveFollowsListModalState extends State { decoration: InputDecoration( labelText: _localizationService.user__save_follows_list_name, hintText: _localizationService.user__save_follows_list_hint_text), - validator: (String followsListName) { + validator: (String? followsListName) { if (!_formWasSubmitted) return null; if (_takenFollowsListName != null && _takenFollowsListName == followsListName) { - return _localizationService.user__save_follows_list_name_taken(_takenFollowsListName); + return _localizationService.user__save_follows_list_name_taken(_takenFollowsListName!); } return _validationService @@ -119,7 +119,7 @@ class OBSaveFollowsListModalState extends State { }), OBEmojiField( emoji: _emoji, - onEmojiFieldTapped: (Emoji emoji) => + onEmojiFieldTapped: (Emoji? emoji) => _onWantsToPickEmoji(), labelText: _localizationService.user__save_follows_list_emoji, errorText: _formWasSubmitted && _emoji == null @@ -156,7 +156,7 @@ class OBSaveFollowsListModalState extends State { )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( leading: GestureDetector( child: const OBIcon(OBIcons.close), @@ -176,7 +176,7 @@ class OBSaveFollowsListModalState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { @@ -205,8 +205,8 @@ class OBSaveFollowsListModalState extends State { } FollowsList followsList = await (_hasExistingList - ? _userService.updateFollowsList(widget.followsList, - name: _nameController.text != widget.followsList.name + ? _userService.updateFollowsList(widget.followsList!, + name: _nameController.text != widget.followsList!.name ? _nameController.text : null, users: _users, @@ -227,8 +227,8 @@ class OBSaveFollowsListModalState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -236,14 +236,14 @@ class OBSaveFollowsListModalState extends State { } Future _isFollowsListNameTaken(String followsListName) async { - if (_hasExistingList && widget.followsList.name == _nameController.text) { + if (_hasExistingList && widget.followsList!.name == _nameController.text) { return false; } return _validationService.isFollowsListNameTaken(followsListName); } void _onWantsToPickEmoji() async { - Emoji pickedEmoji = await Navigator.push( + Emoji? pickedEmoji = await Navigator.push( context, OBSlideRightRoute(builder: (BuildContext context) { return OBPickFollowsListEmojiPage(); diff --git a/lib/pages/home/modals/save_post/create_post.dart b/lib/pages/home/modals/save_post/create_post.dart index 38b7b0031..571b07abf 100644 --- a/lib/pages/home/modals/save_post/create_post.dart +++ b/lib/pages/home/modals/save_post/create_post.dart @@ -42,14 +42,14 @@ import 'package:flutter/material.dart'; import 'package:pigment/pigment.dart'; class OBSavePostModal extends StatefulWidget { - final Community community; - final String text; - final File image; - final File video; - final Post post; + final Community? community; + final String? text; + final File? image; + final File? video; + final Post? post; const OBSavePostModal( - {Key key, this.community, this.text, this.image, this.video, this.post}) + {Key? key, this.community, this.text, this.image, this.video, this.post}) : super(key: key); @override @@ -59,50 +59,50 @@ class OBSavePostModal extends StatefulWidget { } class OBSavePostModalState extends OBContextualSearchBoxState { - ValidationService _validationService; - UserService _userService; - NavigationService _navigationService; - MediaService _mediaService; - ToastService _toastService; - LocalizationService _localizationService; - DraftService _draftService; - ShareService _shareService; - UtilsService _utilsService; - - TextEditingController _textController; - FocusNode _focusNode; - int _charactersCount; - LinkPreview _linkPreview; - - bool _isPostTextAllowedLength; - bool _isPostTextContainingValidHashtags; - - bool _hasFocus; - bool _hasImage; - bool _hasVideo; + late ValidationService _validationService; + late UserService _userService; + late NavigationService _navigationService; + late MediaService _mediaService; + late ToastService _toastService; + late LocalizationService _localizationService; + late DraftService _draftService; + late ShareService _shareService; + late UtilsService _utilsService; + + late TextEditingController _textController; + late FocusNode _focusNode; + late int _charactersCount; + LinkPreview? _linkPreview; + + late bool _isPostTextAllowedLength; + late bool _isPostTextContainingValidHashtags; + + late bool _hasFocus; + late bool _hasImage; + late bool _hasVideo; // When creating a post - File _postImageFile; - File _postVideoFile; + File? _postImageFile; + File? _postVideoFile; // When editing a post - PostImage _postImage; - PostVideo _postVideo; + PostImage? _postImage; + PostVideo? _postVideo; - VoidCallback _postImageWidgetRemover; - VoidCallback _postVideoWidgetRemover; - VoidCallback _linkPreviewWidgetRemover; + VoidCallback? _postImageWidgetRemover; + VoidCallback? _postVideoWidgetRemover; + VoidCallback? _linkPreviewWidgetRemover; - List _postItemsWidgets; + late List _postItemsWidgets; - bool _needsBootstrap; - bool _isCreateCommunityPostInProgress; + late bool _needsBootstrap; + late bool _isCreateCommunityPostInProgress; - bool _isEditingPost; + late bool _isEditingPost; - bool _saveInProgress; - CancelableOperation _saveOperation; - CancelableOperation _linkPreviewCheckOperation; + late bool _saveInProgress; + CancelableOperation? _saveOperation; + CancelableOperation? _linkPreviewCheckOperation; @override void initState() { @@ -129,8 +129,8 @@ class OBSavePostModalState extends OBContextualSearchBoxState { _postItemsWidgets = [ OBCreatePostText(controller: _textController, focusNode: _focusNode) ]; - if (widget.post.hasMedia()) { - PostMedia postMedia = widget.post.getFirstMedia(); + if (widget.post!.hasMedia()) { + PostMedia postMedia = widget.post!.getFirstMedia()!; if (postMedia.type == PostMediaType.video) { _setPostVideo(postMedia.contentObject as PostVideo); _hasImage = false; @@ -145,7 +145,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { } else { _textController = DraftTextEditingController.post( text: widget.text, - communityId: widget.community != null ? widget.community.id : null, + communityId: widget.community != null ? widget.community!.id : null, draftService: _draftService); _postItemsWidgets = [ OBCreatePostText(controller: _textController, focusNode: _focusNode) @@ -153,10 +153,10 @@ class OBSavePostModalState extends OBContextualSearchBoxState { _hasImage = false; _hasVideo = false; if (widget.image != null) { - _setPostImageFile(widget.image); + _setPostImageFile(widget.image!); } if (widget.video != null) { - _setPostVideoFile(widget.video); + _setPostVideoFile(widget.video!); } } @@ -164,7 +164,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { if (!_isEditingPost && widget.community != null) _postItemsWidgets.add(OBPostCommunityPreviewer( - community: widget.community, + community: widget.community!, )); _textController.addListener(_onPostTextChanged); @@ -235,7 +235,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { ))); } - Widget _buildNavigationBar(LocalizationService _localizationService) { + ObstructingPreferredSizeWidget _buildNavigationBar(LocalizationService _localizationService) { bool isPrimaryActionButtonIsEnabled = (_isPostTextAllowedLength && _charactersCount > 0) || _hasImage || @@ -246,10 +246,10 @@ class OBSavePostModalState extends OBContextualSearchBoxState { child: OBIcon(OBIcons.close, semanticLabel: _localizationService.post__close_create_post_label), onTap: () { - if (this._postImageFile != null) this._postImageFile.delete(); + if (this._postImageFile != null) this._postImageFile!.delete(); if (this._postVideoFile != null) - _mediaService.clearThumbnailForFile(this._postVideoFile); - if (this._postVideoFile != null) this._postVideoFile.delete(); + _mediaService.clearThumbnailForFile(this._postVideoFile!); + if (this._postVideoFile != null) this._postVideoFile!.delete(); Navigator.pop(context); }, ), @@ -261,7 +261,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { ); } - Widget _buildPrimaryActionButton({bool isEnabled}) { + Widget _buildPrimaryActionButton({bool isEnabled = false}) { Widget nextButton; if (_isEditingPost) { @@ -297,7 +297,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { return nextButton; } - Future _onWantsToCreateCommunityPost() { + Future? _onWantsToCreateCommunityPost() { if (!_isPostTextContainingValidHashtags) { _toastService.error( message: _localizationService.post__create_hashtags_invalid( @@ -319,13 +319,13 @@ class OBSavePostModalState extends OBContextualSearchBoxState { return; } - OBNewPostData createPostData = await _navigationService.navigateToSharePost( + OBNewPostData? createPostData = await _navigationService.navigateToSharePost( context: context, createPostData: _makeNewPostData()); if (createPostData != null) { // Remove modal if (this._postVideoFile != null) - _mediaService.clearThumbnailForFile(this._postVideoFile); + _mediaService.clearThumbnailForFile(this._postVideoFile!); Navigator.pop(context, createPostData); _clearDraft(); } @@ -475,7 +475,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { _hasImage = true; var postImageWidget = OBPostImagePreviewer( - key: Key(_postImageFile.path), + key: Key(_postImageFile!.path), postImageFile: _postImageFile, onRemove: () { _removePostImageFile(); @@ -505,7 +505,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { _hasVideo = true; var postVideoWidget = OBPostVideoPreview( - key: Key(_postVideoFile.path), + key: Key(_postVideoFile!.path), postVideoFile: _postVideoFile, onRemove: () { _removePostVideoFile(); @@ -542,7 +542,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { _addPostItemWidget(postImageWidget); } - Future _onShare({String text, File image, File video}) async { + Future _onShare({String? text, File? image, File? video}) async { if (image != null || video != null) { if (_hasImage) { _removePostImageFile(); @@ -572,19 +572,19 @@ class OBSavePostModalState extends OBContextualSearchBoxState { Future _createCommunityPost() async { OBNewPostData newPostData = _makeNewPostData(); if (this._postVideoFile != null) - _mediaService.clearThumbnailForFile(this._postVideoFile); + _mediaService.clearThumbnailForFile(this._postVideoFile!); Navigator.pop(context, newPostData); _clearDraft(); } void _savePost() async { _setSaveInProgress(true); - Post editedPost; + Post? editedPost; try { _saveOperation = CancelableOperation.fromFuture(_userService.editPost( - postUuid: widget.post.uuid, text: _textController.text)); + postUuid: widget.post!.uuid!, text: _textController.text)); - editedPost = await _saveOperation.value; + editedPost = await _saveOperation?.value; Navigator.pop(context, editedPost); } catch (error) { _onError(error); @@ -602,13 +602,13 @@ class OBSavePostModalState extends OBContextualSearchBoxState { void _checkForLinkPreview() async { if (_linkPreviewCheckOperation != null) { - _linkPreviewCheckOperation.cancel(); + _linkPreviewCheckOperation!.cancel(); _linkPreviewCheckOperation = null; } String text = _textController.text; - String linkPreviewUrl = _utilsService.getLinkToPreviewFromText(text); + String? linkPreviewUrl = _utilsService.getLinkToPreviewFromText(text); if (_hasImage || _hasVideo || linkPreviewUrl == null) { _clearLinkPreview(); @@ -616,13 +616,13 @@ class OBSavePostModalState extends OBContextualSearchBoxState { } bool isNewLinkPreview = - _linkPreview == null || _linkPreview.url != linkPreviewUrl; + _linkPreview == null || _linkPreview!.url != linkPreviewUrl; if (isNewLinkPreview) { try { _linkPreviewCheckOperation = CancelableOperation.fromFuture( _userService.previewLink(link: linkPreviewUrl)); - LinkPreview linkPreview = await _linkPreviewCheckOperation.value; + LinkPreview linkPreview = await _linkPreviewCheckOperation!.value; _setLinkPreview(linkPreview); } catch (error) { debugLog('Could not check whether link was previewable'); @@ -634,7 +634,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { } void _setLinkPreview(LinkPreview linkPreview) { - if (_linkPreviewWidgetRemover != null) _linkPreviewWidgetRemover(); + if (_linkPreviewWidgetRemover != null) _linkPreviewWidgetRemover!(); setState(() { _linkPreview = linkPreview; @@ -647,7 +647,7 @@ class OBSavePostModalState extends OBContextualSearchBoxState { void _clearLinkPreview() { setState(() { _linkPreview = null; - if (_linkPreviewWidgetRemover != null) _linkPreviewWidgetRemover(); + if (_linkPreviewWidgetRemover != null) _linkPreviewWidgetRemover!(); }); } @@ -656,8 +656,8 @@ class OBSavePostModalState extends OBContextualSearchBoxState { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else if (error is FileTooLargeException) { int limit = error.getLimitInMB(); _toastService.error( @@ -673,27 +673,37 @@ class OBSavePostModalState extends OBContextualSearchBoxState { void _removePostImageFile() { setState(() { - if (this._postImageFile != null) this._postImageFile.deleteSync(); + if (this._postImageFile != null) this._postImageFile!.deleteSync(); this._postImage = null; _hasImage = false; - _postImageWidgetRemover(); + + if (_postImageWidgetRemover != null) { + _postImageWidgetRemover!(); + } }); } void _removePostVideoFile() { + if (this._postVideoFile == null) { + return; + } + setState(() { - _mediaService.clearThumbnailForFile(this._postVideoFile); - if (this._postVideoFile != null) this._postVideoFile.deleteSync(); + _mediaService.clearThumbnailForFile(this._postVideoFile!); + if (this._postVideoFile != null) this._postVideoFile!.deleteSync(); this._postVideoFile = null; _hasVideo = false; - _postVideoWidgetRemover(); + + if (_postVideoWidgetRemover != null) { + _postVideoWidgetRemover!(); + } }); } OBNewPostData _makeNewPostData() { List media = []; - if (_postImageFile != null) media.add(_postImageFile); - if (_postVideoFile != null) media.add(_postVideoFile); + if (_postImageFile != null) media.add(_postImageFile!); + if (_postVideoFile != null) media.add(_postVideoFile!); return OBNewPostData( text: _textController.text, media: media, community: widget.community); diff --git a/lib/pages/home/modals/save_post/pages/share_post/pages/share_post_with_circles.dart b/lib/pages/home/modals/save_post/pages/share_post/pages/share_post_with_circles.dart index 68dd80296..432694bd3 100644 --- a/lib/pages/home/modals/save_post/pages/share_post/pages/share_post_with_circles.dart +++ b/lib/pages/home/modals/save_post/pages/share_post/pages/share_post_with_circles.dart @@ -18,7 +18,7 @@ import 'package:flutter/material.dart'; class OBSharePostWithCirclesPage extends StatefulWidget { final OBNewPostData createPostData; - const OBSharePostWithCirclesPage({Key key, @required this.createPostData}) + const OBSharePostWithCirclesPage({Key? key, required this.createPostData}) : super(key: key); @override @@ -29,20 +29,20 @@ class OBSharePostWithCirclesPage extends StatefulWidget { class OBSharePostWithCirclesPageState extends State { - UserService _userService; - LocalizationService _localizationService; + late UserService _userService; + late LocalizationService _localizationService; - bool _needsBootstrap; + late bool _needsBootstrap; - List _circles; - List _circleSearchResults; - List _selectedCircles; - List _disabledCircles; - Circle _fakeWorldCircle; - Circle _connectionsCircle; - bool _fakeWorldCircleSelected; + late List _circles; + late List _circleSearchResults; + late List _selectedCircles; + late List _disabledCircles; + late Circle _fakeWorldCircle; + Circle? _connectionsCircle; + late bool _fakeWorldCircleSelected; - String _circleSearchQuery; + late String _circleSearchQuery; @override void initState() { @@ -94,7 +94,7 @@ class OBSharePostWithCirclesPageState ); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: _localizationService.trans('post__share_to_circles'), trailing: OBButton( @@ -157,7 +157,7 @@ class OBSharePostWithCirclesPageState if (_fakeWorldCircleSelected) { selectedCircles = []; } else if (_selectedCircles.contains(_connectionsCircle)) { - selectedCircles = [ _connectionsCircle ]; + selectedCircles = [ _connectionsCircle! ]; } else { selectedCircles = _selectedCircles; } @@ -212,7 +212,7 @@ class OBSharePostWithCirclesPageState String standarisedSearchStr = searchString.toLowerCase(); List results = _circles.where((Circle circle) { - return circle.name.toLowerCase().contains(standarisedSearchStr); + return circle.name!.toLowerCase().contains(standarisedSearchStr); }).toList(); _setCircleSearchResults(results); @@ -221,7 +221,7 @@ class OBSharePostWithCirclesPageState void _bootstrap() async { CirclesList circleList = await _userService.getConnectionsCircles(); - this._setCircles(circleList.circles); + this._setCircles(circleList.circles!); } void _resetCircleSearchResults() { @@ -236,9 +236,9 @@ class OBSharePostWithCirclesPageState _circles = circles; // Move connections circle to top _connectionsCircle = _circles - .firstWhere((circle) => circle.id == user.connectionsCircleId); + .firstWhere((circle) => circle.id == user!.connectionsCircleId); _circles.remove(_connectionsCircle); - _circles.insert(0, _connectionsCircle); + _circles.insert(0, _connectionsCircle!); // Add fake world circle _circles.insert(0, _fakeWorldCircle); _selectedCircles = []; diff --git a/lib/pages/home/modals/save_post/pages/share_post/pages/share_post_with_community.dart b/lib/pages/home/modals/save_post/pages/share_post/pages/share_post_with_community.dart index c20994467..7cf698b48 100644 --- a/lib/pages/home/modals/save_post/pages/share_post/pages/share_post_with_community.dart +++ b/lib/pages/home/modals/save_post/pages/share_post/pages/share_post_with_community.dart @@ -19,7 +19,7 @@ import 'package:flutter/material.dart'; class OBSharePostWithCommunityPage extends StatefulWidget { final OBNewPostData createPostData; - const OBSharePostWithCommunityPage({Key key, @required this.createPostData}) + const OBSharePostWithCommunityPage({Key? key, required this.createPostData}) : super(key: key); @override @@ -30,10 +30,10 @@ class OBSharePostWithCommunityPage extends StatefulWidget { class OBSharePostWithCommunityPageState extends State { - UserService _userService; - LocalizationService _localizationService; + late UserService _userService; + late LocalizationService _localizationService; - Community _chosenCommunity; + Community? _chosenCommunity; @override void initState() { @@ -74,7 +74,7 @@ class OBSharePostWithCommunityPageState ); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: _localizationService.trans('post__share_to_community'), trailing: OBButton( @@ -102,14 +102,14 @@ class OBSharePostWithCommunityPageState } Future createPost() async { - widget.createPostData.setCommunity(_chosenCommunity); + widget.createPostData.setCommunity(_chosenCommunity!); Navigator.pop(context, widget.createPostData); } Future> _refreshCommunities() async { CommunitiesList communities = await _userService.getJoinedCommunities(); - return communities.communities; + return communities.communities!; } Future> _loadMoreCommunities( @@ -119,7 +119,7 @@ class OBSharePostWithCommunityPageState List moreCommunities = (await _userService.getJoinedCommunities( offset: offset, )) - .communities; + .communities!; return moreCommunities; } @@ -127,7 +127,7 @@ class OBSharePostWithCommunityPageState CommunitiesList results = await _userService.searchJoinedCommunities(query: query); - return results.communities; + return results.communities!; } void _onCommunityPressed(Community pressedCommunity) { @@ -142,7 +142,7 @@ class OBSharePostWithCommunityPageState _setChosenCommunity(null); } - void _setChosenCommunity(Community chosenCommunity) { + void _setChosenCommunity(Community? chosenCommunity) { setState(() { _chosenCommunity = chosenCommunity; }); diff --git a/lib/pages/home/modals/save_post/pages/share_post/share_post.dart b/lib/pages/home/modals/save_post/pages/share_post/share_post.dart index 3c8f46757..42e3c838c 100644 --- a/lib/pages/home/modals/save_post/pages/share_post/share_post.dart +++ b/lib/pages/home/modals/save_post/pages/share_post/share_post.dart @@ -10,12 +10,13 @@ import 'package:Okuna/widgets/new_post_data_uploader.dart'; import 'package:Okuna/widgets/progress_indicator.dart'; import 'package:Okuna/widgets/theming/primary_color_container.dart'; import 'package:Okuna/widgets/theming/text.dart'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBSharePostPage extends StatefulWidget { final OBNewPostData createPostData; - const OBSharePostPage({Key key, @required this.createPostData}) + const OBSharePostPage({Key? key, required this.createPostData}) : super(key: key); @override @@ -25,11 +26,11 @@ class OBSharePostPage extends StatefulWidget { } class OBSharePostPageState extends State { - bool _loggedInUserRefreshInProgress; - bool _needsBootstrap; - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; + late bool _loggedInUserRefreshInProgress; + late bool _needsBootstrap; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; @override void initState() { @@ -49,7 +50,7 @@ class OBSharePostPageState extends State { _needsBootstrap = false; } - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; return OBCupertinoPageScaffold( navigationBar: _buildNavigationBar(), @@ -58,7 +59,7 @@ class OBSharePostPageState extends State { initialData: loggedInUser, stream: loggedInUser.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot) { - User latestUser = snapshot.data; + User latestUser = snapshot.data!; if (_loggedInUserRefreshInProgress) return const Center( @@ -83,7 +84,7 @@ class OBSharePostPageState extends State { ) ]; - if (latestUser.isMemberOfCommunities) { + if (latestUser.isMemberOfCommunities ?? false) { shareToTiles.add(ListTile( leading: const OBIcon(OBIcons.communities), title: OBText(_localizationService @@ -109,7 +110,7 @@ class OBSharePostPageState extends State { )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: _localizationService.trans('post__share_to'), ); @@ -121,21 +122,21 @@ class OBSharePostPageState extends State { Future _refreshLoggedInUser() async { User refreshedUser = await _userService.refreshUser(); - if (!refreshedUser.isMemberOfCommunities) { + if (!(refreshedUser.isMemberOfCommunities ?? false)) { // Only possibility _onWantsToSharePostToCircles(); } } void _onWantsToSharePostToCircles() async { - OBNewPostData createPostData = + OBNewPostData? createPostData = await _navigationService.navigateToSharePostWithCircles( context: context, createPostData: widget.createPostData); if (createPostData != null) Navigator.pop(context, createPostData); } void _onWantsToSharePostToCommunity() async { - OBNewPostData createPostData = + OBNewPostData? createPostData = await _navigationService.navigateToSharePostWithCommunity( context: context, createPostData: widget.createPostData); if (createPostData != null) Navigator.pop(context, createPostData); diff --git a/lib/pages/home/modals/save_post/widgets/create_post_text.dart b/lib/pages/home/modals/save_post/widgets/create_post_text.dart index 5de907edb..1f9e71f27 100644 --- a/lib/pages/home/modals/save_post/widgets/create_post_text.dart +++ b/lib/pages/home/modals/save_post/widgets/create_post_text.dart @@ -5,9 +5,9 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBCreatePostText extends StatelessWidget { - final TextEditingController controller; - final FocusNode focusNode; - final String hintText; + final TextEditingController? controller; + final FocusNode? focusNode; + final String? hintText; OBCreatePostText({this.controller, this.focusNode, this.hintText}); diff --git a/lib/pages/home/modals/save_post/widgets/post_community_previewer.dart b/lib/pages/home/modals/save_post/widgets/post_community_previewer.dart index 4d4ddb3e2..e65070b51 100644 --- a/lib/pages/home/modals/save_post/widgets/post_community_previewer.dart +++ b/lib/pages/home/modals/save_post/widgets/post_community_previewer.dart @@ -14,7 +14,7 @@ import '../../../../../provider.dart'; class OBPostCommunityPreviewer extends StatelessWidget { final Community community; - const OBPostCommunityPreviewer({Key key, @required this.community}) + const OBPostCommunityPreviewer({Key? key, required this.community}) : super(key: key); @override diff --git a/lib/pages/home/modals/save_post/widgets/post_image_previewer.dart b/lib/pages/home/modals/save_post/widgets/post_image_previewer.dart index 1bb40f0e0..43ad3d7ac 100644 --- a/lib/pages/home/modals/save_post/widgets/post_image_previewer.dart +++ b/lib/pages/home/modals/save_post/widgets/post_image_previewer.dart @@ -6,17 +6,17 @@ import 'package:flutter/material.dart'; import 'package:flutter_advanced_networkimage/provider.dart'; class OBPostImagePreviewer extends StatelessWidget { - final PostImage postImage; - final File postImageFile; - final VoidCallback onRemove; - final VoidCallback onWillEditImage; + final PostImage? postImage; + final File? postImageFile; + final VoidCallback? onRemove; + final VoidCallback? onWillEditImage; - final ValueChanged onPostImageEdited; + final ValueChanged? onPostImageEdited; final double buttonSize = 30.0; const OBPostImagePreviewer( - {Key key, + {Key? key, this.postImage, this.postImageFile, this.onRemove, @@ -37,12 +37,12 @@ class OBPostImagePreviewer extends StatelessWidget { borderRadius: new BorderRadius.circular(avatarBorderRadius), child: isFileImage ? Image.file( - postImageFile, + postImageFile!, fit: BoxFit.cover, ) : Image( fit: BoxFit.cover, - image: AdvancedNetworkImage(postImage.image, + image: AdvancedNetworkImage(postImage!.image ?? '', useDiskCache: true, fallbackAssetImage: 'assets/images/fallbacks/post-fallback.png', @@ -91,7 +91,7 @@ class OBPostImagePreviewer extends StatelessWidget { } Widget _buildEditButton(BuildContext context) { - Function onWantsToEditImage = () { + VoidCallback onWantsToEditImage = () { _onWantsToEditImage(context); }; @@ -115,12 +115,12 @@ class OBPostImagePreviewer extends StatelessWidget { } void _onWantsToEditImage(BuildContext context) async { - if (onWillEditImage != null) onWillEditImage(); + if (onWillEditImage != null) onWillEditImage!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - File croppedFile = - await openbookProvider.mediaService.cropImage(postImageFile); - if (croppedFile != null) onPostImageEdited(croppedFile); + File? croppedFile = + await openbookProvider.mediaService.cropImage(postImageFile!); + if (croppedFile != null) onPostImageEdited!(croppedFile); } } diff --git a/lib/pages/home/modals/save_post/widgets/post_video_previewer.dart b/lib/pages/home/modals/save_post/widgets/post_video_previewer.dart index 3ccdbb308..8b36733e8 100644 --- a/lib/pages/home/modals/save_post/widgets/post_video_previewer.dart +++ b/lib/pages/home/modals/save_post/widgets/post_video_previewer.dart @@ -7,15 +7,15 @@ import 'package:flutter/material.dart'; import 'package:flutter_advanced_networkimage/provider.dart'; class OBPostVideoPreview extends StatelessWidget { - final File postVideoFile; - final PostVideo postVideo; - final VoidCallback onRemove; + final File? postVideoFile; + final PostVideo? postVideo; + final VoidCallback? onRemove; final double buttonSize = 30.0; - final double playIconSize; + final double? playIconSize; static double avatarBorderRadius = 10.0; const OBPostVideoPreview( - {Key key, + {Key? key, this.postVideoFile, this.postVideo, this.onRemove, @@ -31,18 +31,18 @@ class OBPostVideoPreview extends StatelessWidget { Widget videoPreview = isFileVideo ? FutureBuilder( future: - openbookProvider.mediaService.getVideoThumbnail(postVideoFile), + openbookProvider.mediaService.getVideoThumbnail(postVideoFile!), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data == null) return const SizedBox(); return _wrapImageWidgetForThumbnail(Image.file( - snapshot.data, + snapshot.data!, fit: BoxFit.cover, )); }) : _wrapImageWidgetForThumbnail(Image( fit: BoxFit.cover, - image: AdvancedNetworkImage(postVideo.thumbnail, + image: AdvancedNetworkImage(postVideo!.thumbnail ?? '', useDiskCache: true, fallbackAssetImage: 'assets/images/fallbacks/post-fallback.png', retryLimit: 0), @@ -121,11 +121,11 @@ class OBPostVideoPreview extends StatelessWidget { void _onWantsToPlay(BuildContext context) { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - String postVideoUrl; + String? postVideoUrl; if (postVideo != null) postVideoUrl = - postVideo.getVideoFormatOfType(OBVideoFormatType.mp4SD).file; + postVideo!.getVideoFormatOfType(OBVideoFormatType.mp4SD)?.file; openbookProvider.dialogService.showVideo( context: context, diff --git a/lib/pages/home/modals/save_post/widgets/remaining_post_characters.dart b/lib/pages/home/modals/save_post/widgets/remaining_post_characters.dart index 616d394ba..00523d4ea 100644 --- a/lib/pages/home/modals/save_post/widgets/remaining_post_characters.dart +++ b/lib/pages/home/modals/save_post/widgets/remaining_post_characters.dart @@ -7,7 +7,7 @@ class OBRemainingPostCharacters extends StatelessWidget { final int currentCharacters; const OBRemainingPostCharacters( - {Key key, @required this.maxCharacters, @required this.currentCharacters}) + {Key? key, required this.maxCharacters, required this.currentCharacters}) : super(key: key); @override @@ -30,9 +30,9 @@ class OBRemainingPostCharacters extends StatelessWidget { style: TextStyle( fontSize: 12.0, color: exceededMaxCharacters - ? themeValueParserService.parseColor(theme.dangerColor) + ? themeValueParserService.parseColor(theme!.dangerColor) : themeValueParserService - .parseColor(theme.primaryTextColor), + .parseColor(theme!.primaryTextColor), fontWeight: exceededMaxCharacters ? FontWeight.bold : FontWeight.normal), diff --git a/lib/pages/home/modals/timeline_filters.dart b/lib/pages/home/modals/timeline_filters.dart index 2ba9fb6d1..6cc52de4f 100644 --- a/lib/pages/home/modals/timeline_filters.dart +++ b/lib/pages/home/modals/timeline_filters.dart @@ -21,7 +21,7 @@ import 'package:flutter/material.dart'; class OBTimelineFiltersModal extends StatefulWidget { final OBTimelinePageController timelinePageController; - const OBTimelineFiltersModal({Key key, @required this.timelinePageController}) + const OBTimelineFiltersModal({Key? key, required this.timelinePageController}) : super(key: key); @override @@ -31,23 +31,23 @@ class OBTimelineFiltersModal extends StatefulWidget { } class OBTimelineFiltersModalState extends State { - UserService _userService; - LocalizationService _localizationService; + late UserService _userService; + late LocalizationService _localizationService; - bool _requestInProgress; - bool _needsBootstrap; + late bool _requestInProgress; + late bool _needsBootstrap; - String _searchQuery; + String? _searchQuery; - List _circles; - List _selectedCircles; - List _disabledCircles; - List _circlesSearchResults; - Circle _connectionsCircle; + late List _circles; + late List _selectedCircles; + List? _disabledCircles; + late List _circlesSearchResults; + Circle? _connectionsCircle; - List _followsLists; - List _selectedFollowsLists; - List _followsListsSearchResults; + late List _followsLists; + late List _selectedFollowsLists; + late List _followsListsSearchResults; @override void initState() { @@ -138,7 +138,7 @@ class OBTimelineFiltersModalState extends State { if (isCircle) { Circle circle = _circlesSearchResults[index]; bool isSelected = _selectedCircles.contains(circle); - bool isDisabled = _disabledCircles.contains(circle); + bool isDisabled = _disabledCircles?.contains(circle) ?? false; Widget circleTile = OBCircleSelectableTile( circle, @@ -200,7 +200,7 @@ class OBTimelineFiltersModalState extends State { height: 20.0, ), OBText( - _localizationService.user__timeline_filters_no_match(_searchQuery), + _localizationService.user__timeline_filters_no_match(_searchQuery ?? ''), style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18.0, @@ -214,7 +214,7 @@ class OBTimelineFiltersModalState extends State { ); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( leading: GestureDetector( child: const OBIcon(OBIcons.close), @@ -254,7 +254,7 @@ class OBTimelineFiltersModalState extends State { void _searchCircles(String standarisedSearchStr) { List results = _circles.where((Circle circle) { - return circle.name.toLowerCase().contains(standarisedSearchStr); + return circle.name!.toLowerCase().contains(standarisedSearchStr); }).toList(); _setCirclesSearchResults(results); @@ -262,7 +262,7 @@ class OBTimelineFiltersModalState extends State { void _searchFollowsLists(String standarisedSearchStr) { List results = _followsLists.where((FollowsList followsList) { - return followsList.name.toLowerCase().contains(standarisedSearchStr); + return followsList.name!.toLowerCase().contains(standarisedSearchStr); }).toList(); _setFollowsListsSearchResults(results); } @@ -319,14 +319,14 @@ class OBTimelineFiltersModalState extends State { } void _setCircles(List circles) { - var user = _userService.getLoggedInUser(); + var user = _userService.getLoggedInUser()!; setState(() { _circles = circles; // Find connections circle and move it to the top _connectionsCircle = _circles .firstWhere((circle) => circle.id == user.connectionsCircleId); _circles.remove(_connectionsCircle); - _circles.insert(0, _connectionsCircle); + _circles.insert(0, _connectionsCircle!); }); } @@ -399,14 +399,14 @@ class OBTimelineFiltersModalState extends State { var results = await Future.wait( [_userService.getConnectionsCircles(), _userService.getFollowsLists()]); - CirclesList circlesList = results[0]; - FollowsListsList followsList = results[1]; + CirclesList circlesList = results[0] as CirclesList; + FollowsListsList followsList = results[1] as FollowsListsList; - _setCircles(circlesList.circles); - _setCirclesSearchResults(circlesList.circles); + _setCircles(circlesList.circles!); + _setCirclesSearchResults(circlesList.circles!); _updateDisabledCircles(); - _setFollowsLists(followsList.lists); - _setFollowsListsSearchResults(followsList.lists); + _setFollowsLists(followsList.lists!); + _setFollowsListsSearchResults(followsList.lists!); _setRequestInProgress(false); } } diff --git a/lib/pages/home/modals/user_invites/create_user_invite.dart b/lib/pages/home/modals/user_invites/create_user_invite.dart index 49d4f4245..a5ab10a20 100644 --- a/lib/pages/home/modals/user_invites/create_user_invite.dart +++ b/lib/pages/home/modals/user_invites/create_user_invite.dart @@ -17,7 +17,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBCreateUserInviteModal extends StatefulWidget { - final UserInvite userInvite; + final UserInvite? userInvite; final bool autofocusNameTextField; OBCreateUserInviteModal( @@ -30,22 +30,22 @@ class OBCreateUserInviteModal extends StatefulWidget { } class OBCreateUserInviteModalState extends State { - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; - ValidationService _validationService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; + late ValidationService _validationService; + late LocalizationService _localizationService; - bool _requestInProgress; - bool _formWasSubmitted; - bool _formValid; - bool _hasExistingUserInvite; + late bool _requestInProgress; + late bool _formWasSubmitted; + late bool _formValid; + late bool _hasExistingUserInvite; - GlobalKey _formKey; + late GlobalKey _formKey; - TextEditingController _nicknameController; + late TextEditingController _nicknameController; - CancelableOperation _createUpdateOperation; + CancelableOperation? _createUpdateOperation; @override void initState() { @@ -57,7 +57,7 @@ class OBCreateUserInviteModalState extends State { _formKey = GlobalKey(); _hasExistingUserInvite = widget.userInvite != null; if (_hasExistingUserInvite) { - _nicknameController.text = widget.userInvite.nickname; + _nicknameController.text = widget.userInvite!.nickname ?? ''; } _nicknameController.addListener(_updateFormValid); @@ -66,7 +66,7 @@ class OBCreateUserInviteModalState extends State { @override void dispose() { super.dispose(); - if (_createUpdateOperation != null) _createUpdateOperation.cancel(); + if (_createUpdateOperation != null) _createUpdateOperation?.cancel(); } @override @@ -101,7 +101,7 @@ class OBCreateUserInviteModalState extends State { decoration: InputDecoration( labelText: _localizationService.user__invites_create_name_title, hintText: _localizationService.user__invites_create_name_hint), - validator: (String userInviteNickname) { + validator: (String? userInviteNickname) { if (!_formWasSubmitted) return null; return _validationService .validateUserProfileName( @@ -115,7 +115,7 @@ class OBCreateUserInviteModalState extends State { )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( leading: GestureDetector( child: const OBIcon(OBIcons.close), @@ -136,7 +136,7 @@ class OBCreateUserInviteModalState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { @@ -155,15 +155,15 @@ class OBCreateUserInviteModalState extends State { _createUpdateOperation = CancelableOperation.fromFuture( _hasExistingUserInvite ? _userService.updateUserInvite( - userInvite: widget.userInvite, + userInvite: widget.userInvite!, nickname: - _nicknameController.text != widget.userInvite.nickname + _nicknameController.text != widget.userInvite!.nickname ? _nicknameController.text : null) : _userService.createUserInvite( nickname: _nicknameController.text)); - UserInvite userInvite = await _createUpdateOperation.value; + UserInvite userInvite = await _createUpdateOperation?.value; if (!_hasExistingUserInvite) { _navigateToShareInvite(userInvite); } else { @@ -188,8 +188,8 @@ class OBCreateUserInviteModalState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/modals/user_invites/send_invite_email.dart b/lib/pages/home/modals/user_invites/send_invite_email.dart index 93af1e817..eac629b04 100644 --- a/lib/pages/home/modals/user_invites/send_invite_email.dart +++ b/lib/pages/home/modals/user_invites/send_invite_email.dart @@ -17,7 +17,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBSendUserInviteEmailModal extends StatefulWidget { - final UserInvite userInvite; + final UserInvite? userInvite; final bool autofocusEmailTextField; OBSendUserInviteEmailModal( @@ -32,25 +32,25 @@ class OBSendUserInviteEmailModal extends StatefulWidget { class OBSendUserInviteEmailModalState extends State { - UserService _userService; - ToastService _toastService; - ValidationService _validationService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ValidationService _validationService; + late LocalizationService _localizationService; - CancelableOperation _emailOperation; + CancelableOperation? _emailOperation; - bool _requestInProgress; - bool _formWasSubmitted; - bool _formValid; + late bool _requestInProgress; + late bool _formWasSubmitted; + late bool _formValid; - GlobalKey _formKey; + late GlobalKey _formKey; - TextEditingController _emailController; + late TextEditingController _emailController; @override void dispose() { super.dispose(); - if (_emailOperation != null) _emailOperation.cancel(); + if (_emailOperation != null) _emailOperation!.cancel(); } @override @@ -61,8 +61,8 @@ class OBSendUserInviteEmailModalState _formWasSubmitted = false; _emailController = TextEditingController(); _formKey = GlobalKey(); - if (widget.userInvite.email != null) { - _emailController.text = widget.userInvite.email; + if (widget.userInvite?.email != null) { + _emailController.text = widget.userInvite!.email!; } _emailController.addListener(_updateFormValid); @@ -99,7 +99,7 @@ class OBSendUserInviteEmailModalState decoration: InputDecoration( labelText: _localizationService.user__invites_email_text, hintText: _localizationService.user__invites_email_hint), - validator: (String email) { + validator: (String? email) { if (!_formWasSubmitted) return null; return _validationService.validateUserEmail(email); }), @@ -111,7 +111,7 @@ class OBSendUserInviteEmailModalState )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( leading: GestureDetector( child: const OBIcon(OBIcons.close), @@ -130,7 +130,7 @@ class OBSendUserInviteEmailModalState } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { @@ -148,9 +148,9 @@ class OBSendUserInviteEmailModalState try { _emailOperation = CancelableOperation.fromFuture( _userService.sendUserInviteEmail( - widget.userInvite, _emailController.text) + widget.userInvite!, _emailController.text) ); - await _emailOperation.value; + await _emailOperation?.value; _showUserInviteSent(); Navigator.of(context).pop(widget.userInvite); } catch (error) { @@ -170,8 +170,8 @@ class OBSendUserInviteEmailModalState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/modals/zoomable_photo.dart b/lib/pages/home/modals/zoomable_photo.dart index 7695c44aa..edee925e8 100644 --- a/lib/pages/home/modals/zoomable_photo.dart +++ b/lib/pages/home/modals/zoomable_photo.dart @@ -20,18 +20,18 @@ class OBZoomablePhotoModal extends StatefulWidget { class OBZoomablePhotoModalState extends State with SingleTickerProviderStateMixin { - bool _isDismissible; - AnimationController _controller; - Animation _offset; - Animation _rotationAnimation; - double _rotationAngle; - double _rotationDirection; - double _posX; - double _posY; - double _velocityX; - double _velocityY; - PointerDownEvent startDragDetails; - PointerMoveEvent updateDragDetails; + late bool _isDismissible; + late AnimationController _controller; + Animation? _offset; + Animation? _rotationAnimation; + late double _rotationAngle; + late double _rotationDirection; + late double _posX; + late double _posY; + late double _velocityX; + late double _velocityY; + PointerDownEvent? startDragDetails; + PointerMoveEvent? updateDragDetails; static const VELOCITY_THRESHOLD = 10.0; // THRESHOLD_SECOND_POINTER_EVENT: @@ -85,14 +85,14 @@ class OBZoomablePhotoModalState extends State double deltaX = 0.0; if (updateDragDetails == null && startDragDetails != null) { deltaY = updatedDetails.position.dy - - startDragDetails.position.dy; + startDragDetails!.position.dy; deltaX = updatedDetails.position.dx - - startDragDetails.position.dx; + startDragDetails!.position.dx; } else if (updateDragDetails != null) { deltaY = updatedDetails.position.dy - - updateDragDetails.position.dy; + updateDragDetails!.position.dy; deltaX = updatedDetails.position.dx - - updateDragDetails.position.dx; + updateDragDetails!.position.dx; } _updateDragValues(deltaX, deltaY, updatedDetails); }, @@ -173,8 +173,8 @@ class OBZoomablePhotoModalState extends State .chain(CurveTween(curve: Curves.easeInOutSine)) .animate(_controller) ..addListener(() { - _posX = _offset.value.dx; - _posY = _offset.value.dy; + _posX = _offset!.value.dx; + _posY = _offset!.value.dy; setState(() {}); }); startDragDetails = null; @@ -184,7 +184,7 @@ class OBZoomablePhotoModalState extends State .chain(CurveTween(curve: Curves.easeInOutCubic)) .animate(_controller) ..addListener(() { - _rotationAngle = _rotationAnimation.value; + _rotationAngle = _rotationAnimation!.value; setState(() {}); }); _controller.reset(); @@ -209,9 +209,9 @@ class OBZoomablePhotoModalState extends State double maxRotationAngle = pi / 2; // Rotation increases proportional to distance from mid of screen double rotationRatio = - (startDragDetails.position.dx - screenMid).abs() / screenMid; + (startDragDetails!.position.dx - screenMid).abs() / screenMid; - if (startDragDetails.position.dx < screenMid) { + if (startDragDetails!.position.dx < screenMid) { maxRotationAngle = -pi / 2; } // Rotation increases proportional to drag in Y direction @@ -239,8 +239,8 @@ class OBZoomablePhotoModalState extends State .chain(CurveTween(curve: Curves.easeInOutSine)) .animate(_controller) ..addListener(() { - _posX = _offset.value.dx + _velocityX / 2; - _posY = _offset.value.dy + _velocityY / 2; + _posX = _offset!.value.dx + _velocityX / 2; + _posY = _offset!.value.dy + _velocityY / 2; setState(() {}); }); @@ -249,7 +249,7 @@ class OBZoomablePhotoModalState extends State .chain(CurveTween(curve: Curves.easeInOutCubic)) .animate(_controller) ..addListener(() { - _rotationAngle = _rotationAnimation.value; + _rotationAngle = _rotationAnimation!.value; setState(() {}); }); diff --git a/lib/pages/home/pages/communities/communities.dart b/lib/pages/home/pages/communities/communities.dart index 0873a29fc..21006b6a0 100644 --- a/lib/pages/home/pages/communities/communities.dart +++ b/lib/pages/home/pages/communities/communities.dart @@ -29,9 +29,9 @@ import 'package:flutter/material.dart'; import 'package:pigment/pigment.dart'; class OBMainCommunitiesPage extends StatefulWidget { - final OBCommunitiesPageController controller; + final OBCommunitiesPageController? controller; - const OBMainCommunitiesPage({Key key, this.controller}) : super(key: key); + const OBMainCommunitiesPage({Key? key, this.controller}) : super(key: key); @override State createState() { @@ -41,31 +41,31 @@ class OBMainCommunitiesPage extends StatefulWidget { class OBMainCommunitiesPageState extends State with TickerProviderStateMixin { - UserService _userService; - ToastService _toastService; - ThemeService _themeService; - LocalizationService _localizationService; - ThemeValueParserService _themeValueParserService; - ModalService _modalService; - NavigationService _navigationService; + late UserService _userService; + late ToastService _toastService; + late ThemeService _themeService; + late LocalizationService _localizationService; + late ThemeValueParserService _themeValueParserService; + late ModalService _modalService; + late NavigationService _navigationService; - List _categories; - TabController _tabController; + late List _categories; + TabController? _tabController; - ScrollController _myCommunitiesScrollController; - ScrollController _allTrendingCommnunitiesScrollController; + late ScrollController _myCommunitiesScrollController; + late ScrollController _allTrendingCommnunitiesScrollController; - List _categoriesScrollControllers; + late List _categoriesScrollControllers; - bool _needsBootstrap; + late bool _needsBootstrap; - bool _refreshInProgress; + late bool _refreshInProgress; @override void initState() { super.initState(); if (widget.controller != null) - widget.controller.attach(context: context, state: this); + widget.controller!.attach(context: context, state: this); _needsBootstrap = true; _refreshInProgress = false; _categories = []; @@ -155,7 +155,7 @@ class OBMainCommunitiesPageState extends State } List _buildTabs() { - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; List tabs = [ OBUserAvatarTab( @@ -214,7 +214,7 @@ class OBMainCommunitiesPageState extends State _setRefreshInProgress(true); try { CategoriesList categoriesList = await _userService.getCategories(); - _setCategories(categoriesList.categories); + _setCategories(categoriesList.categories ?? []); } catch (error) { _onError(error); } finally { @@ -227,8 +227,8 @@ class OBMainCommunitiesPageState extends State _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -243,7 +243,7 @@ class OBMainCommunitiesPageState extends State } void scrollToTop() { - int currentIndex = _tabController.index; + int currentIndex = _tabController!.index; ScrollController currentTabScrollController; if (currentIndex == 0) { @@ -266,7 +266,7 @@ class OBMainCommunitiesPageState extends State } TabController _makeTabController() { - int initialIndex = _tabController != null ? _tabController.index : 0; + int initialIndex = _tabController != null ? _tabController!.index : 0; TabController controller = TabController( length: _categories.length + 2, @@ -276,7 +276,7 @@ class OBMainCommunitiesPageState extends State } void _onWantsToCreateCommunity() async { - Community createdCommunity = + Community? createdCommunity = await _modalService.openCreateCommunity(context: context); if (createdCommunity != null) { _navigationService.navigateToCommunity( @@ -292,15 +292,15 @@ class OBMainCommunitiesPageState extends State } class OBCommunitiesPageController extends PoppablePageController { - OBMainCommunitiesPageState _state; + OBMainCommunitiesPageState? _state; void attach( - {@required BuildContext context, OBMainCommunitiesPageState state}) { + {required BuildContext context, OBMainCommunitiesPageState? state}) { super.attach(context: context); _state = state; } void scrollToTop() { - _state.scrollToTop(); + _state?.scrollToTop(); } } diff --git a/lib/pages/home/pages/communities/widgets/category_tab.dart b/lib/pages/home/pages/communities/widgets/category_tab.dart index 0bcc826fb..eda2a59ef 100644 --- a/lib/pages/home/pages/communities/widgets/category_tab.dart +++ b/lib/pages/home/pages/communities/widgets/category_tab.dart @@ -8,22 +8,22 @@ import 'package:flutter_advanced_networkimage/provider.dart'; class OBCategoryTab extends StatelessWidget { final Category category; - const OBCategoryTab({Key key, @required this.category}) : super(key: key); + const OBCategoryTab({Key? key, required this.category}) : super(key: key); @override Widget build(BuildContext context) { ThemeValueParserService _themeValueParser = OpenbookProvider.of(context).themeValueParserService; - Color categoryColor = _themeValueParser.parseColor(category.color); + Color categoryColor = _themeValueParser.parseColor(category.color!); bool categoryColorIsDark = _themeValueParser.isDarkColor(categoryColor); return OBImageTab( - text: category.title, + text: category.title!, color: categoryColor, textColor: categoryColorIsDark ? Colors.white : Colors.black, imageProvider: - AdvancedNetworkImage(category.avatar, useDiskCache: true), + AdvancedNetworkImage(category.avatar ?? '', useDiskCache: true), ); } } diff --git a/lib/pages/home/pages/communities/widgets/my_communities/my_communities.dart b/lib/pages/home/pages/communities/widgets/my_communities/my_communities.dart index 2160f2d36..725d4517b 100644 --- a/lib/pages/home/pages/communities/widgets/my_communities/my_communities.dart +++ b/lib/pages/home/pages/communities/widgets/my_communities/my_communities.dart @@ -13,9 +13,9 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBMyCommunities extends StatefulWidget { - final ScrollController scrollController; + final ScrollController? scrollController; - const OBMyCommunities({Key key, this.scrollController}) : super(key: key); + const OBMyCommunities({Key? key, this.scrollController}) : super(key: key); @override OBMyCommunitiesState createState() { @@ -25,16 +25,16 @@ class OBMyCommunities extends StatefulWidget { class OBMyCommunitiesState extends State with AutomaticKeepAliveClientMixin { - OBMyCommunitiesGroupController _favoriteCommunitiesGroupController; - OBMyCommunitiesGroupController _joinedCommunitiesGroupController; - OBMyCommunitiesGroupController _moderatedCommunitiesGroupController; - OBMyCommunitiesGroupController _administratedCommunitiesGroupController; - NavigationService _navigationService; - LocalizationService _localizationService; - UserService _userService; - bool _needsBootstrap; - bool _refreshInProgress; - GlobalKey _refreshIndicatorKey; + late OBMyCommunitiesGroupController _favoriteCommunitiesGroupController; + late OBMyCommunitiesGroupController _joinedCommunitiesGroupController; + late OBMyCommunitiesGroupController _moderatedCommunitiesGroupController; + late OBMyCommunitiesGroupController _administratedCommunitiesGroupController; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late UserService _userService; + late bool _needsBootstrap; + late bool _refreshInProgress; + late GlobalKey _refreshIndicatorKey; @override void initState() { @@ -138,7 +138,7 @@ class OBMyCommunitiesState extends State Future> _refreshJoinedCommunities() async { CommunitiesList joinedCommunitiesList = await _userService.getJoinedCommunities(); - return joinedCommunitiesList.communities; + return joinedCommunitiesList.communities ?? []; } Future> _loadMoreJoinedCommunities( @@ -147,13 +147,13 @@ class OBMyCommunitiesState extends State CommunitiesList moreJoinedCommunitiesList = await _userService.getJoinedCommunities(offset: offset); - return moreJoinedCommunitiesList.communities; + return moreJoinedCommunitiesList.communities ?? []; } Future> _refreshFavoriteCommunities() async { CommunitiesList favoriteCommunitiesList = await _userService.getFavoriteCommunities(); - return favoriteCommunitiesList.communities; + return favoriteCommunitiesList.communities ?? []; } Future> _loadMoreFavoriteCommunities( @@ -162,13 +162,13 @@ class OBMyCommunitiesState extends State CommunitiesList moreFavoriteCommunitiesList = await _userService.getFavoriteCommunities(offset: offset); - return moreFavoriteCommunitiesList.communities; + return moreFavoriteCommunitiesList.communities ?? []; } Future> _refreshAdministratedCommunities() async { CommunitiesList administratedCommunitiesList = await _userService.getAdministratedCommunities(); - return administratedCommunitiesList.communities; + return administratedCommunitiesList.communities ?? []; } Future> _loadMoreAdministratedCommunities( @@ -177,13 +177,13 @@ class OBMyCommunitiesState extends State CommunitiesList moreAdministratedCommunitiesList = await _userService.getAdministratedCommunities(offset: offset); - return moreAdministratedCommunitiesList.communities; + return moreAdministratedCommunitiesList.communities ?? []; } Future> _refreshModeratedCommunities() async { CommunitiesList moderatedCommunitiesList = await _userService.getModeratedCommunities(); - return moderatedCommunitiesList.communities; + return moderatedCommunitiesList.communities ?? []; } Future> _loadMoreModeratedCommunities( @@ -192,7 +192,7 @@ class OBMyCommunitiesState extends State CommunitiesList moreModeratedCommunitiesList = await _userService.getModeratedCommunities(offset: offset); - return moreModeratedCommunitiesList.communities; + return moreModeratedCommunitiesList.communities ?? []; } Widget _buildNoJoinedCommunitiesFallback( @@ -214,9 +214,9 @@ class OBMyCommunitiesState extends State stream: community.updateSubject, initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community latestCommunity = snapshot.data; + Community latestCommunity = snapshot.data!; - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; return latestCommunity.isMember(loggedInUser) ? _buildCommunityListItem(community) : const SizedBox(); @@ -230,9 +230,9 @@ class OBMyCommunitiesState extends State stream: community.updateSubject, initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community latestCommunity = snapshot.data; + Community latestCommunity = snapshot.data!; - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; return latestCommunity.isModerator(loggedInUser) ? _buildCommunityListItem(community) : const SizedBox(); @@ -246,9 +246,9 @@ class OBMyCommunitiesState extends State stream: community.updateSubject, initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community latestCommunity = snapshot.data; + Community latestCommunity = snapshot.data!; - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; return latestCommunity.isAdministrator(loggedInUser) ? _buildCommunityListItem(community) : const SizedBox(); @@ -262,9 +262,9 @@ class OBMyCommunitiesState extends State initialData: community, stream: community.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community latestCommunity = snapshot.data; + Community latestCommunity = snapshot.data!; - return latestCommunity.isFavorite + return latestCommunity.isFavorite == true ? _buildCommunityListItem(community) : const SizedBox(); }, @@ -274,25 +274,25 @@ class OBMyCommunitiesState extends State Future> _searchFavoriteCommunities(String query) async { CommunitiesList results = await _userService.searchFavoriteCommunities(query: query); - return results.communities; + return results.communities ?? []; } Future> _searchAdministratedCommunities(String query) async { CommunitiesList results = await _userService.searchAdministratedCommunities(query: query); - return results.communities; + return results.communities ?? []; } Future> _searchModeratedCommunities(String query) async { CommunitiesList results = await _userService.searchModeratedCommunities(query: query); - return results.communities; + return results.communities ?? []; } Future> _searchJoinedCommunities(String query) async { CommunitiesList results = await _userService.searchJoinedCommunities(query: query); - return results.communities; + return results.communities ?? []; } Widget _buildCommunityListItem(Community community) { diff --git a/lib/pages/home/pages/communities/widgets/my_communities/widgets/my_communities_group.dart b/lib/pages/home/pages/communities/widgets/my_communities/widgets/my_communities_group.dart index 02de03ea1..fa9450988 100644 --- a/lib/pages/home/pages/communities/widgets/my_communities/widgets/my_communities_group.dart +++ b/lib/pages/home/pages/communities/widgets/my_communities/widgets/my_communities_group.dart @@ -15,26 +15,26 @@ import 'package:flutter/material.dart'; class OBMyCommunitiesGroup extends StatefulWidget { final OBHttpListRefresher communityGroupListRefresher; - final OBHttpListSearcher communityGroupListSearcher; + final OBHttpListSearcher? communityGroupListSearcher; final OBHttpListItemBuilder communityGroupListItemBuilder; - final OBHttpListItemBuilder communitySearchResultListItemBuilder; + final OBHttpListItemBuilder? communitySearchResultListItemBuilder; final OBHttpListOnScrollLoader communityGroupListOnScrollLoader; - final OBMyCommunitiesGroupFallbackBuilder noGroupItemsFallbackBuilder; - final OBMyCommunitiesGroupController controller; + final OBMyCommunitiesGroupFallbackBuilder? noGroupItemsFallbackBuilder; + final OBMyCommunitiesGroupController? controller; final String groupItemName; final String groupName; final int maxGroupListPreviewItems; final String title; const OBMyCommunitiesGroup({ - Key key, - @required this.communityGroupListRefresher, - @required this.communityGroupListOnScrollLoader, - @required this.groupItemName, - @required this.groupName, - @required this.title, - @required this.maxGroupListPreviewItems, - @required this.communityGroupListItemBuilder, + Key? key, + required this.communityGroupListRefresher, + required this.communityGroupListOnScrollLoader, + required this.groupItemName, + required this.groupName, + required this.title, + required this.maxGroupListPreviewItems, + required this.communityGroupListItemBuilder, this.communityGroupListSearcher, this.communitySearchResultListItemBuilder, this.noGroupItemsFallbackBuilder, @@ -48,18 +48,18 @@ class OBMyCommunitiesGroup extends StatefulWidget { } class OBMyCommunitiesGroupState extends State { - bool _needsBootstrap; - ToastService _toastService; - NavigationService _navigationService; - LocalizationService _localizationService; - List _communityGroupList; - bool _refreshInProgress; - CancelableOperation _refreshOperation; + late bool _needsBootstrap; + late ToastService _toastService; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late List _communityGroupList; + late bool _refreshInProgress; + CancelableOperation? _refreshOperation; @override void initState() { super.initState(); - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); _needsBootstrap = true; _communityGroupList = []; _refreshInProgress = false; @@ -83,7 +83,7 @@ class OBMyCommunitiesGroupState extends State { if (listItemCount == 0) { if (widget.noGroupItemsFallbackBuilder != null && !_refreshInProgress) { - return widget.noGroupItemsFallbackBuilder( + return widget.noGroupItemsFallbackBuilder!( context, _refreshJoinedCommunities); } return const SizedBox(); @@ -121,8 +121,8 @@ class OBMyCommunitiesGroupState extends State { @override void dispose() { super.dispose(); - if (widget.controller != null) widget.controller.detach(); - if (_refreshOperation != null) _refreshOperation.cancel(); + if (widget.controller != null) widget.controller!.detach(); + if (_refreshOperation != null) _refreshOperation!.cancel(); } Widget _buildSeeAllButton() { @@ -162,13 +162,13 @@ class OBMyCommunitiesGroupState extends State { } Future _refreshJoinedCommunities() async { - if (_refreshOperation != null) _refreshOperation.cancel(); + if (_refreshOperation != null) _refreshOperation!.cancel(); _setRefreshInProgress(true); try { _refreshOperation = CancelableOperation.fromFuture(widget.communityGroupListRefresher()); - List groupCommunities = await _refreshOperation.value; + List groupCommunities = await _refreshOperation!.value; _setCommunityGroupList(groupCommunities); } catch (error) { @@ -184,8 +184,8 @@ class OBMyCommunitiesGroupState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -234,7 +234,7 @@ class OBMyCommunitiesGroupState extends State { } class OBMyCommunitiesGroupController { - OBMyCommunitiesGroupState _state; + OBMyCommunitiesGroupState? _state; void attach(OBMyCommunitiesGroupState state) { this._state = state; @@ -246,7 +246,7 @@ class OBMyCommunitiesGroupController { Future refresh() { if (_state == null) return Future.value(); - return _state._refreshJoinedCommunities(); + return _state!._refreshJoinedCommunities(); } } diff --git a/lib/pages/home/pages/communities/widgets/trending_communities.dart b/lib/pages/home/pages/communities/widgets/trending_communities.dart index ddc6e3454..8a336f50d 100644 --- a/lib/pages/home/pages/communities/widgets/trending_communities.dart +++ b/lib/pages/home/pages/communities/widgets/trending_communities.dart @@ -14,10 +14,10 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBTrendingCommunities extends StatefulWidget { - final Category category; - final ScrollController scrollController; + final Category? category; + final ScrollController? scrollController; - const OBTrendingCommunities({Key key, this.category, this.scrollController}) + const OBTrendingCommunities({Key? key, this.category, this.scrollController}) : super(key: key); @override @@ -28,14 +28,14 @@ class OBTrendingCommunities extends StatefulWidget { class OBTrendingCommunitiesState extends State with AutomaticKeepAliveClientMixin { - bool _needsBootstrap; - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; - LocalizationService _localizationService; - List _trendingCommunities; - bool _refreshInProgress; - GlobalKey _refreshIndicatorKey; + late bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late List _trendingCommunities; + late bool _refreshInProgress; + late GlobalKey _refreshIndicatorKey; @override void initState() { @@ -98,7 +98,7 @@ class OBTrendingCommunitiesState extends State child: OBText( hasCategory ? _localizationService - .community__trending_in_category(widget.category.title) + .community__trending_in_category(widget.category?.title ?? '') : _localizationService.community__trending_in_all, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24), ), @@ -119,7 +119,7 @@ class OBTrendingCommunitiesState extends State Community community = _trendingCommunities[index]; return OBCommunityTile( community, - key: Key(community.name), + key: Key(community.name!), onCommunityTilePressed: _onTrendingCommunityPressed, ); } @@ -136,7 +136,7 @@ class OBTrendingCommunitiesState extends State milliseconds: 0, ), () { if (_refreshIndicatorKey.currentState != null) { - _refreshIndicatorKey.currentState.show(); + _refreshIndicatorKey.currentState!.show(); } }); } @@ -147,7 +147,7 @@ class OBTrendingCommunitiesState extends State try { CommunitiesList trendingCommunitiesList = await _userService.getTrendingCommunities(category: widget.category); - _setTrendingCommunities(trendingCommunitiesList.communities); + _setTrendingCommunities(trendingCommunitiesList.communities ?? []); } catch (error) { _onError(error); } finally { @@ -160,8 +160,8 @@ class OBTrendingCommunitiesState extends State _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/pages/communities/widgets/user_avatar_tab.dart b/lib/pages/home/pages/communities/widgets/user_avatar_tab.dart index 0e203a9c6..80860ca45 100644 --- a/lib/pages/home/pages/communities/widgets/user_avatar_tab.dart +++ b/lib/pages/home/pages/communities/widgets/user_avatar_tab.dart @@ -11,7 +11,7 @@ import 'package:flutter/material.dart'; class OBUserAvatarTab extends StatelessWidget { final User user; - const OBUserAvatarTab({Key key, @required this.user}) : super(key: key); + const OBUserAvatarTab({Key? key, required this.user}) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/pages/home/pages/community/community.dart b/lib/pages/home/pages/community/community.dart index a73c4c1f4..3367f9e93 100644 --- a/lib/pages/home/pages/community/community.dart +++ b/lib/pages/home/pages/community/community.dart @@ -37,21 +37,21 @@ class OBCommunityPage extends StatefulWidget { class OBCommunityPageState extends State with TickerProviderStateMixin { - Community _community; - OBPostsStreamController _obPostsStreamController; - ScrollController _obPostsStreamScrollController; - UserService _userService; - LocalizationService _localizationService; + late Community _community; + late OBPostsStreamController _obPostsStreamController; + late ScrollController _obPostsStreamScrollController; + late UserService _userService; + late LocalizationService _localizationService; - bool _needsBootstrap; + late bool _needsBootstrap; - CancelableOperation _refreshCommunityOperation; + CancelableOperation? _refreshCommunityOperation; - List _newPostsData; + late List _newPostsData; double _hideFloatingButtonTolerance = 10; - AnimationController _hideFloatingButtonAnimation; - double _previousScrollPixels; + late AnimationController _hideFloatingButtonAnimation; + late double _previousScrollPixels; @override void initState() { @@ -97,7 +97,7 @@ class OBCommunityPageState extends State void dispose() { _hideFloatingButtonAnimation.dispose(); super.dispose(); - if (_refreshCommunityOperation != null) _refreshCommunityOperation.cancel(); + if (_refreshCommunityOperation != null) _refreshCommunityOperation!.cancel(); } @override @@ -134,7 +134,7 @@ class OBCommunityPageState extends State initialData: _community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community latestCommunity = snapshot.data; + Community latestCommunity = snapshot.data!; return _userCanSeeCommunityContent(latestCommunity) ? _buildCommunityContent() @@ -149,7 +149,7 @@ class OBCommunityPageState extends State bool _userCanSeeCommunityContent(Community community) { bool communityIsPrivate = community.isPrivate(); - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; bool userIsMember = community.isMember(loggedInUser); return !communityIsPrivate || userIsMember; @@ -177,14 +177,14 @@ class OBCommunityPageState extends State controller: _obPostsStreamController, prependedItems: prependedItems, displayContext: OBPostDisplayContext.communityPosts, - streamIdentifier: 'community_' + widget.community.name, + streamIdentifier: 'community_' + widget.community.name!, secondaryRefresher: _refreshCommunity, statusIndicatorBuilder: _buildPostsStreamStatusIndicator, ), ]; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - User loggedInUser = openbookProvider.userService.getLoggedInUser(); + User loggedInUser = openbookProvider.userService.getLoggedInUser()!; bool isMemberOfCommunity = _community.isMember(loggedInUser); if (isMemberOfCommunity) { @@ -206,12 +206,12 @@ class OBCommunityPageState extends State } Widget _buildPostsStreamStatusIndicator( - {BuildContext context, - OBPostsStreamStatus streamStatus, - List streamPrependedItems, - Function streamRefresher}) { + {required BuildContext context, + required OBPostsStreamStatus streamStatus, + required List streamPrependedItems, + required Function streamRefresher}) { return OBCommunityPostsStreamStatusIndicator( - streamRefresher: streamRefresher, + streamRefresher: streamRefresher as VoidCallback, streamPrependedItems: streamPrependedItems, streamStatus: streamStatus); } @@ -236,7 +236,7 @@ class OBCommunityPageState extends State } Widget _buildPrivateCommunityContent() { - bool communityHasInvitesEnabled = _community.invitesEnabled; + bool communityHasInvitesEnabled = _community.invitesEnabled ?? false; return ListView( padding: EdgeInsets.all(0), children: [ @@ -274,11 +274,11 @@ class OBCommunityPageState extends State } Future _refreshCommunity() async { - if (_refreshCommunityOperation != null) _refreshCommunityOperation.cancel(); + if (_refreshCommunityOperation != null) _refreshCommunityOperation!.cancel(); _refreshCommunityOperation = CancelableOperation.fromFuture( - _userService.getCommunityWithName(_community.name)); + _userService.getCommunityWithName(_community.name!)); debugPrint(_localizationService.trans('community__refreshing')); - var community = await _refreshCommunityOperation.value; + var community = await _refreshCommunityOperation?.value; _setCommunity(community); } @@ -286,7 +286,7 @@ class OBCommunityPageState extends State debugPrint('Refreshing community posts'); PostsList communityPosts = await _userService.getPostsForCommunity(widget.community); - return communityPosts.posts; + return communityPosts.posts ?? []; } Future> _loadMoreCommunityPosts( @@ -300,7 +300,7 @@ class OBCommunityPageState extends State count: 10, )) .posts; - return moreCommunityPosts; + return moreCommunityPosts ?? []; } void _setCommunity(Community community) { @@ -329,9 +329,9 @@ class CommunityTabBarDelegate extends SliverPersistentHeaderDelegate { this.community, }); - final TabController controller; - final Community community; - final PageStorageKey pageStorageKey; + final TabController? controller; + final Community? community; + final PageStorageKey? pageStorageKey; @override double get minExtent => kToolbarHeight; @@ -354,7 +354,7 @@ class CommunityTabBarDelegate extends SliverPersistentHeaderDelegate { var theme = snapshot.data; Color themePrimaryTextColor = - themeValueParserService.parseColor(theme.primaryTextColor); + themeValueParserService.parseColor(theme!.primaryTextColor); return new SizedBox( height: kToolbarHeight, diff --git a/lib/pages/home/pages/community/pages/community_members.dart b/lib/pages/home/pages/community/pages/community_members.dart index 211a3f03a..55249b273 100644 --- a/lib/pages/home/pages/community/pages/community_members.dart +++ b/lib/pages/home/pages/community/pages/community_members.dart @@ -19,7 +19,7 @@ import 'package:flutter/material.dart'; class OBCommunityMembersPage extends StatefulWidget { final Community community; - const OBCommunityMembersPage({Key key, @required this.community}) + const OBCommunityMembersPage({Key? key, required this.community}) : super(key: key); @override @@ -29,12 +29,12 @@ class OBCommunityMembersPage extends StatefulWidget { } class OBCommunityMembersPageState extends State { - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -98,7 +98,7 @@ class OBCommunityMembersPageState extends State { Future> _refreshCommunityMembers() async { UsersList communityMembers = await _userService.getMembersForCommunity(widget.community); - return communityMembers.users; + return communityMembers.users ?? []; } Future> _loadMoreCommunityMembers( @@ -111,13 +111,13 @@ class OBCommunityMembersPageState extends State { count: 20, )) .users; - return moreCommunityMembers; + return moreCommunityMembers ?? []; } Future> _searchCommunityMembers(String query) async { UsersList results = await _userService.searchCommunityMembers( query: query, community: widget.community); - return results.users; + return results.users ?? []; } } diff --git a/lib/pages/home/pages/community/pages/community_rules.dart b/lib/pages/home/pages/community/pages/community_rules.dart index f15a1bbf7..cb37c7e94 100644 --- a/lib/pages/home/pages/community/pages/community_rules.dart +++ b/lib/pages/home/pages/community/pages/community_rules.dart @@ -13,7 +13,7 @@ import '../../../../../provider.dart'; class OBCommunityRulesPage extends StatelessWidget { final Community community; - const OBCommunityRulesPage({Key key, @required this.community}) + const OBCommunityRulesPage({Key? key, required this.community}) : super(key: key); @override @@ -31,8 +31,8 @@ class OBCommunityRulesPage extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - String communityRules = community?.rules; - String communityColor = community?.color; + String? communityRules = community?.rules; + String? communityColor = community?.color; if (communityRules == null || communityRules.isEmpty || @@ -66,7 +66,7 @@ class OBCommunityRulesPage extends StatelessWidget { const SizedBox( height: 10, ), - OBActionableSmartText(text: community.rules) + OBActionableSmartText(text: community!.rules) ], ), ), diff --git a/lib/pages/home/pages/community/pages/community_staff/community_staff.dart b/lib/pages/home/pages/community/pages/community_staff/community_staff.dart index 5272ad99e..3466d27ab 100644 --- a/lib/pages/home/pages/community/pages/community_staff/community_staff.dart +++ b/lib/pages/home/pages/community/pages/community_staff/community_staff.dart @@ -12,7 +12,7 @@ import '../../../../../../provider.dart'; class OBCommunityStaffPage extends StatelessWidget { final Community community; - const OBCommunityStaffPage({Key key, @required this.community}) + const OBCommunityStaffPage({Key? key, required this.community}) : super(key: key); @override diff --git a/lib/pages/home/pages/community/pages/community_staff/widgets/community_administrators.dart b/lib/pages/home/pages/community/pages/community_staff/widgets/community_administrators.dart index c471bca61..f8024f6f8 100644 --- a/lib/pages/home/pages/community/pages/community_staff/widgets/community_administrators.dart +++ b/lib/pages/home/pages/community/pages/community_staff/widgets/community_administrators.dart @@ -20,7 +20,7 @@ class OBCommunityAdministrators extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - List communityAdministrators = community?.administrators?.users; + List? communityAdministrators = community?.administrators?.users; if (communityAdministrators == null || communityAdministrators.isEmpty) return const SizedBox(); diff --git a/lib/pages/home/pages/community/pages/community_staff/widgets/community_moderators.dart b/lib/pages/home/pages/community/pages/community_staff/widgets/community_moderators.dart index 32d6f1e13..c1eb186a1 100644 --- a/lib/pages/home/pages/community/pages/community_staff/widgets/community_moderators.dart +++ b/lib/pages/home/pages/community/pages/community_staff/widgets/community_moderators.dart @@ -20,7 +20,7 @@ class OBCommunityModerators extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - List communityModerators = community?.moderators?.users; + List? communityModerators = community?.moderators?.users; if (communityModerators == null || communityModerators.isEmpty) return const SizedBox(); diff --git a/lib/pages/home/pages/community/pages/manage_community/manage_community.dart b/lib/pages/home/pages/community/pages/manage_community/manage_community.dart index db7f29816..7c0ca58b5 100644 --- a/lib/pages/home/pages/community/pages/manage_community/manage_community.dart +++ b/lib/pages/home/pages/community/pages/manage_community/manage_community.dart @@ -17,7 +17,7 @@ import 'package:flutter/material.dart'; class OBManageCommunityPage extends StatelessWidget { final Community community; - const OBManageCommunityPage({@required this.community}); + const OBManageCommunityPage({required this.community}); @override Widget build(BuildContext context) { @@ -27,7 +27,7 @@ class OBManageCommunityPage extends StatelessWidget { UserService userService = openbookProvider.userService; LocalizationService _localizationService = openbookProvider.localizationService; - User loggedInUser = userService.getLoggedInUser(); + User loggedInUser = userService.getLoggedInUser()!; List menuListTiles = []; const TextStyle listItemSubtitleStyle = TextStyle(fontSize: 14); diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/community_administrators.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/community_administrators.dart index 10cd5f79c..7917d1dd1 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/community_administrators.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/community_administrators.dart @@ -23,7 +23,7 @@ import 'package:flutter/material.dart'; class OBCommunityAdministratorsPage extends StatefulWidget { final Community community; - const OBCommunityAdministratorsPage({Key key, @required this.community}) + const OBCommunityAdministratorsPage({Key? key, required this.community}) : super(key: key); @override @@ -34,14 +34,14 @@ class OBCommunityAdministratorsPage extends StatefulWidget { class OBCommunityAdministratorsPageState extends State { - UserService _userService; - ModalService _modalService; - NavigationService _navigationService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ModalService _modalService; + late NavigationService _navigationService; + late ToastService _toastService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -124,8 +124,8 @@ class OBCommunityAdministratorsPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -135,7 +135,7 @@ class OBCommunityAdministratorsPageState Future> _refreshCommunityAdministrators() async { UsersList communityAdministrators = await _userService.getAdministratorsForCommunity(widget.community); - return communityAdministrators.users; + return communityAdministrators.users ?? []; } Future> _loadMoreCommunityAdministrators( @@ -149,18 +149,18 @@ class OBCommunityAdministratorsPageState count: 20, )) .users; - return moreCommunityAdministrators; + return moreCommunityAdministrators ?? []; } Future> _searchCommunityAdministrators(String query) async { UsersList results = await _userService.searchCommunityAdministrators( query: query, community: widget.community); - return results.users; + return results.users ?? []; } void _onWantsToAddNewAdministrator() async { - User addedCommunityAdministrator = + User? addedCommunityAdministrator = await _modalService.openAddCommunityAdministrator( context: context, community: widget.community); diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/modals/add_community_administrator/add_community_administrator.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/modals/add_community_administrator/add_community_administrator.dart index cc1083d41..87b6c7cd0 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/modals/add_community_administrator/add_community_administrator.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/modals/add_community_administrator/add_community_administrator.dart @@ -18,7 +18,7 @@ import 'package:flutter/material.dart'; class OBAddCommunityAdministratorModal extends StatefulWidget { final Community community; - const OBAddCommunityAdministratorModal({Key key, @required this.community}) + const OBAddCommunityAdministratorModal({Key? key, required this.community}) : super(key: key); @override @@ -29,11 +29,11 @@ class OBAddCommunityAdministratorModal extends StatefulWidget { class OBAddCommunityAdministratorModalState extends State { - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -80,7 +80,7 @@ class OBAddCommunityAdministratorModalState UsersList communityMembers = await _userService.getMembersForCommunity( widget.community, exclude: [CommunityMembersExclusion.administrators]); - return communityMembers.users; + return communityMembers.users ?? []; } Future> _loadMoreCommunityMembers( @@ -93,7 +93,7 @@ class OBAddCommunityAdministratorModalState count: 20, exclude: [CommunityMembersExclusion.administrators])) .users; - return moreCommunityMembers; + return moreCommunityMembers ?? []; } Future> _searchCommunityMembers(String query) async { @@ -102,7 +102,7 @@ class OBAddCommunityAdministratorModalState community: widget.community, exclude: [CommunityMembersExclusion.administrators]); - return results.users; + return results.users ?? []; } void _onWantsToAddNewAdministrator(User user) async { diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/modals/add_community_administrator/pages/confirm_add_community_administrator.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/modals/add_community_administrator/pages/confirm_add_community_administrator.dart index 6aad13a47..45199cd6c 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/modals/add_community_administrator/pages/confirm_add_community_administrator.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_administrators/modals/add_community_administrator/pages/confirm_add_community_administrator.dart @@ -16,7 +16,7 @@ class OBConfirmAddCommunityAdministrator extends StatefulWidget { final Community community; const OBConfirmAddCommunityAdministrator( - {Key key, @required this.user, @required this.community}) + {Key? key, required this.user, required this.community}) : super(key: key); @override @@ -27,11 +27,11 @@ class OBConfirmAddCommunityAdministrator extends StatefulWidget { class OBConfirmAddCommunityAdministratorState extends State { - bool _confirmationInProgress; - UserService _userService; - LocalizationService _localizationService; - ToastService _toastService; - bool _needsBootstrap; + late bool _confirmationInProgress; + late UserService _userService; + late LocalizationService _localizationService; + late ToastService _toastService; + late bool _needsBootstrap; @override void initState() { @@ -42,7 +42,7 @@ class OBConfirmAddCommunityAdministratorState @override Widget build(BuildContext context) { - String username = widget.user.username; + String username = widget.user.username!; if (_needsBootstrap) { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); @@ -136,8 +136,8 @@ class OBConfirmAddCommunityAdministratorState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/community_banned_users.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/community_banned_users.dart index b6496b6f6..e322b8925 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/community_banned_users.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/community_banned_users.dart @@ -23,7 +23,7 @@ import 'package:flutter/material.dart'; class OBCommunityBannedUsersPage extends StatefulWidget { final Community community; - const OBCommunityBannedUsersPage({Key key, @required this.community}) + const OBCommunityBannedUsersPage({Key? key, required this.community}) : super(key: key); @override @@ -34,14 +34,14 @@ class OBCommunityBannedUsersPage extends StatefulWidget { class OBCommunityBannedUsersPageState extends State { - UserService _userService; - ModalService _modalService; - NavigationService _navigationService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ModalService _modalService; + late NavigationService _navigationService; + late ToastService _toastService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -123,8 +123,8 @@ class OBCommunityBannedUsersPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -134,7 +134,7 @@ class OBCommunityBannedUsersPageState Future> _refreshCommunityBannedUsers() async { UsersList communityBannedUsers = await _userService.getBannedUsersForCommunity(widget.community); - return communityBannedUsers.users; + return communityBannedUsers.users ?? []; } Future> _loadMoreCommunityBannedUsers( @@ -148,18 +148,18 @@ class OBCommunityBannedUsersPageState count: 20, )) .users; - return moreCommunityBannedUsers; + return moreCommunityBannedUsers ?? []; } Future> _searchCommunityBannedUsers(String query) async { UsersList results = await _userService.searchCommunityBannedUsers( query: query, community: widget.community); - return results.users; + return results.users ?? []; } void _onWantsToAddNewBannedUser() async { - User addedCommunityBannedUser = await _modalService.openBanCommunityUser( + User? addedCommunityBannedUser = await _modalService.openBanCommunityUser( context: context, community: widget.community); if (addedCommunityBannedUser != null) { diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/modals/ban_community_user/ban_community_user.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/modals/ban_community_user/ban_community_user.dart index 81ffea16f..ab55cf608 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/modals/ban_community_user/ban_community_user.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/modals/ban_community_user/ban_community_user.dart @@ -18,7 +18,7 @@ import 'package:flutter/material.dart'; class OBBanCommunityUserModal extends StatefulWidget { final Community community; - const OBBanCommunityUserModal({Key key, @required this.community}) + const OBBanCommunityUserModal({Key? key, required this.community}) : super(key: key); @override @@ -29,11 +29,11 @@ class OBBanCommunityUserModal extends StatefulWidget { class OBBanCommunityUserModalState extends State { - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -82,7 +82,7 @@ class OBBanCommunityUserModalState CommunityMembersExclusion.administrators, CommunityMembersExclusion.moderators ]); - return communityMembers.users; + return communityMembers.users ?? []; } Future> _loadMoreCommunityMembers( @@ -98,7 +98,7 @@ class OBBanCommunityUserModalState CommunityMembersExclusion.moderators ])) .users; - return moreCommunityMembers; + return moreCommunityMembers ?? []; } Future> _searchCommunityMembers(String query) async { @@ -110,7 +110,7 @@ class OBBanCommunityUserModalState CommunityMembersExclusion.moderators ]); - return results.users; + return results.users ?? []; } void _onWantsToAddNewBannedUser(User user) async { diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/modals/ban_community_user/pages/confirm_ban_community_user.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/modals/ban_community_user/pages/confirm_ban_community_user.dart index 944ccb527..61adcf194 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/modals/ban_community_user/pages/confirm_ban_community_user.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_banned_users/modals/ban_community_user/pages/confirm_ban_community_user.dart @@ -16,7 +16,7 @@ class OBConfirmBanCommunityUser extends StatefulWidget { final Community community; const OBConfirmBanCommunityUser( - {Key key, @required this.user, @required this.community}) + {Key? key, required this.user, required this.community}) : super(key: key); @override @@ -26,11 +26,11 @@ class OBConfirmBanCommunityUser extends StatefulWidget { } class OBConfirmBanCommunityUserState extends State { - bool _confirmationInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late bool _confirmationInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; @override void initState() { @@ -41,7 +41,7 @@ class OBConfirmBanCommunityUserState extends State { @override Widget build(BuildContext context) { - String username = widget.user.username; + String username = widget.user.username!; if (_needsBootstrap) { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); @@ -134,8 +134,8 @@ class OBConfirmBanCommunityUserState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_closed_posts/widgets/closed_posts.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_closed_posts/widgets/closed_posts.dart index e31006c37..2b68aba4e 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_closed_posts/widgets/closed_posts.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_closed_posts/widgets/closed_posts.dart @@ -18,7 +18,7 @@ import 'package:flutter/material.dart'; class OBCommunityClosedPosts extends StatefulWidget { final Community community; - const OBCommunityClosedPosts({this.community}); + const OBCommunityClosedPosts({required this.community}); @override OBCommunityClosedPostsState createState() { @@ -27,18 +27,18 @@ class OBCommunityClosedPosts extends StatefulWidget { } class OBCommunityClosedPostsState extends State { - List _posts; - bool _needsBootstrap; - bool _isFirstLoad; - UserService _userService; - ToastService _toastService; - ScrollController _postsScrollController; + late List _posts; + late bool _needsBootstrap; + late bool _isFirstLoad; + late UserService _userService; + late ToastService _toastService; + late ScrollController _postsScrollController; final GlobalKey _refreshIndicatorKey = GlobalKey(); - OBCommunityClosedPostsStatus _status; - CancelableOperation _postsRequest; + late OBCommunityClosedPostsStatus _status; + CancelableOperation? _postsRequest; @override void initState() { @@ -191,7 +191,7 @@ class OBCommunityClosedPostsState extends State { void scrollToTop() { if (_postsScrollController.hasClients) { if (_postsScrollController.offset == 0) { - _refreshIndicatorKey.currentState.show(); + _refreshIndicatorKey.currentState?.show(); } _postsScrollController.animateTo( @@ -213,7 +213,7 @@ class OBCommunityClosedPostsState extends State { void _cancelPreviousPostsRequest() { if (_postsRequest != null) { - _postsRequest.cancel(); + _postsRequest!.cancel(); _postsRequest = null; } } @@ -221,8 +221,8 @@ class OBCommunityClosedPostsState extends State { Future _bootstrap() async { PostsList closedPosts = await _userService.getClosedPostsForCommunity(widget.community); - if (closedPosts.posts != null) _setPosts(closedPosts.posts); - _refreshIndicatorKey.currentState.show(); + if (closedPosts.posts != null) _setPosts(closedPosts.posts!); + _refreshIndicatorKey.currentState?.show(); } Future _refreshPosts() async { @@ -234,16 +234,16 @@ class OBCommunityClosedPostsState extends State { _postsRequest = CancelableOperation.fromFuture(postsListFuture); - List posts = (await postsListFuture).posts; + List? posts = (await postsListFuture).posts; if (_isFirstLoad) _isFirstLoad = false; - if (posts.length == 0) { + if (posts?.length == 0) { _setStatus(OBCommunityClosedPostsStatus.noMorePostsToLoad); } else { _setStatus(OBCommunityClosedPostsStatus.idle); } - _setPosts(posts); + _setPosts(posts ?? []); } catch (error) { _setStatus(OBCommunityClosedPostsStatus.loadingMorePostsFailed); _onError(error); @@ -267,13 +267,13 @@ class OBCommunityClosedPostsState extends State { _postsRequest = CancelableOperation.fromFuture(morePostsListFuture); - List morePosts = (await morePostsListFuture).posts; + List? morePosts = (await morePostsListFuture).posts; - if (morePosts.length == 0) { + if (morePosts?.length == 0) { _setStatus(OBCommunityClosedPostsStatus.noMorePostsToLoad); } else { _setStatus(OBCommunityClosedPostsStatus.idle); - _addPosts(morePosts); + _addPosts(morePosts ?? []); } } catch (error) { _setStatus(OBCommunityClosedPostsStatus.loadingMorePostsFailed); @@ -294,8 +294,8 @@ class OBCommunityClosedPostsState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/community_moderators.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/community_moderators.dart index a77c8e93e..e15713421 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/community_moderators.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/community_moderators.dart @@ -23,7 +23,7 @@ import 'package:flutter/material.dart'; class OBCommunityModeratorsPage extends StatefulWidget { final Community community; - const OBCommunityModeratorsPage({Key key, @required this.community}) + const OBCommunityModeratorsPage({Key? key, required this.community}) : super(key: key); @override @@ -34,14 +34,14 @@ class OBCommunityModeratorsPage extends StatefulWidget { class OBCommunityModeratorsPageState extends State { - UserService _userService; - ModalService _modalService; - NavigationService _navigationService; - LocalizationService _localizationService; - ToastService _toastService; + late UserService _userService; + late ModalService _modalService; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late ToastService _toastService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -120,8 +120,8 @@ class OBCommunityModeratorsPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; @@ -131,7 +131,7 @@ class OBCommunityModeratorsPageState Future> _refreshCommunityModerators() async { UsersList communityModerators = await _userService.getModeratorsForCommunity(widget.community); - return communityModerators.users; + return communityModerators.users ?? []; } Future> _loadMoreCommunityModerators( @@ -145,18 +145,18 @@ class OBCommunityModeratorsPageState count: 20, )) .users; - return moreCommunityModerators; + return moreCommunityModerators ?? []; } Future> _searchCommunityModerators(String query) async { UsersList results = await _userService.searchCommunityModerators( query: query, community: widget.community); - return results.users; + return results.users ?? []; } void _onWantsToAddNewModerator() async { - User addedCommunityModerator = + User? addedCommunityModerator = await _modalService.openAddCommunityModerator( context: context, community: widget.community); diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/modals/add_community_moderator/add_community_moderator.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/modals/add_community_moderator/add_community_moderator.dart index 2ba251e18..76237c781 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/modals/add_community_moderator/add_community_moderator.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/modals/add_community_moderator/add_community_moderator.dart @@ -18,7 +18,7 @@ import 'package:flutter/material.dart'; class OBAddCommunityModeratorModal extends StatefulWidget { final Community community; - const OBAddCommunityModeratorModal({Key key, @required this.community}) + const OBAddCommunityModeratorModal({Key? key, required this.community}) : super(key: key); @override @@ -29,11 +29,11 @@ class OBAddCommunityModeratorModal extends StatefulWidget { class OBAddCommunityModeratorModalState extends State { - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -82,7 +82,7 @@ class OBAddCommunityModeratorModalState CommunityMembersExclusion.administrators, CommunityMembersExclusion.moderators ]); - return communityMembers.users; + return communityMembers.users ?? []; } Future> _loadMoreCommunityMembers( @@ -98,7 +98,7 @@ class OBAddCommunityModeratorModalState CommunityMembersExclusion.moderators ])) .users; - return moreCommunityMembers; + return moreCommunityMembers ?? []; } Future> _searchCommunityMembers(String query) async { @@ -110,7 +110,7 @@ class OBAddCommunityModeratorModalState CommunityMembersExclusion.moderators ]); - return results.users; + return results.users ?? []; } void _onWantsToAddNewModerator(User user) async { diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/modals/add_community_moderator/pages/confirm_add_community_moderator.dart b/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/modals/add_community_moderator/pages/confirm_add_community_moderator.dart index ff0264555..cff9a965c 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/modals/add_community_moderator/pages/confirm_add_community_moderator.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/community_moderators/modals/add_community_moderator/pages/confirm_add_community_moderator.dart @@ -16,7 +16,7 @@ class OBConfirmAddCommunityModerator extends StatefulWidget { final Community community; const OBConfirmAddCommunityModerator( - {Key key, @required this.user, @required this.community}) + {Key? key, required this.user, required this.community}) : super(key: key); @override @@ -27,11 +27,11 @@ class OBConfirmAddCommunityModerator extends StatefulWidget { class OBConfirmAddCommunityModeratorState extends State { - bool _confirmationInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late bool _confirmationInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; @override void initState() { @@ -42,7 +42,7 @@ class OBConfirmAddCommunityModeratorState @override Widget build(BuildContext context) { - String username = widget.user.username; + String username = widget.user.username!; if (_needsBootstrap) { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); @@ -135,8 +135,8 @@ class OBConfirmAddCommunityModeratorState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/delete_community.dart b/lib/pages/home/pages/community/pages/manage_community/pages/delete_community.dart index a25b0311c..b170bf54a 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/delete_community.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/delete_community.dart @@ -13,7 +13,7 @@ import 'package:flutter/cupertino.dart'; class OBDeleteCommunityPage extends StatefulWidget { final Community community; - const OBDeleteCommunityPage({Key key, @required this.community}) + const OBDeleteCommunityPage({Key? key, required this.community}) : super(key: key); @override @@ -23,11 +23,11 @@ class OBDeleteCommunityPage extends StatefulWidget { } class OBDeleteCommunityPageState extends State { - bool _confirmationInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late bool _confirmationInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; @override void initState() { @@ -134,8 +134,8 @@ class OBDeleteCommunityPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/pages/community/pages/manage_community/pages/leave_community.dart b/lib/pages/home/pages/community/pages/manage_community/pages/leave_community.dart index d14c01d6f..180c7169a 100644 --- a/lib/pages/home/pages/community/pages/manage_community/pages/leave_community.dart +++ b/lib/pages/home/pages/community/pages/manage_community/pages/leave_community.dart @@ -13,7 +13,7 @@ import 'package:flutter/cupertino.dart'; class OBLeaveCommunityPage extends StatefulWidget { final Community community; - const OBLeaveCommunityPage({Key key, @required this.community}) + const OBLeaveCommunityPage({Key? key, required this.community}) : super(key: key); @override @@ -23,11 +23,11 @@ class OBLeaveCommunityPage extends StatefulWidget { } class OBLeaveCommunityPageState extends State { - bool _confirmationInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late bool _confirmationInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; @override void initState() { @@ -130,8 +130,8 @@ class OBLeaveCommunityPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_actions/community_actions.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_actions/community_actions.dart index 7f3b9dae3..a75761d44 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_actions/community_actions.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_actions/community_actions.dart @@ -10,7 +10,7 @@ import 'package:Okuna/widgets/buttons/community_button.dart'; import 'package:flutter/material.dart'; class OBCommunityActions extends StatelessWidget { - final Community community; + final Community? community; OBCommunityActions(this.community); @@ -21,7 +21,7 @@ class OBCommunityActions extends StatelessWidget { UserService userService = openbookProvider.userService; LocalizationService localizationService = openbookProvider.localizationService; - User loggedInUser = userService.getLoggedInUser(); + User loggedInUser = userService.getLoggedInUser()!; bool isCommunityAdmin = community?.isAdministrator(loggedInUser) ?? false; bool isCommunityModerator = community?.isModerator(loggedInUser) ?? false; @@ -32,11 +32,11 @@ class OBCommunityActions extends StatelessWidget { actions.add(_buildManageButton(navigationService, context, localizationService)); } else { actions.addAll([ - OBJoinCommunityButton(community), + OBJoinCommunityButton(community!), const SizedBox( width: 10, ), - OBCommunityActionMore(community) + OBCommunityActionMore(community!) ]); } @@ -48,12 +48,12 @@ class OBCommunityActions extends StatelessWidget { _buildManageButton(NavigationService navigationService, context, LocalizationService localizationService) { return OBCommunityButton( - community: community, + community: community!, isLoading: false, text: localizationService.community__actions_manage_text, onPressed: () { navigationService.navigateToManageCommunity( - community: community, context: context); + community: community!, context: context); }); } } diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_buttons.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_buttons.dart index 75b6f96b2..4926a47b2 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_buttons.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_buttons.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; class OBCommunityButtons extends StatelessWidget { final Community community; - const OBCommunityButtons({Key key, this.community}) : super(key: key); + const OBCommunityButtons({Key? key, required this.community}) : super(key: key); @override Widget build(BuildContext context) { @@ -34,7 +34,7 @@ class OBCommunityButtons extends StatelessWidget { ), ); - if (community.rules != null && community.rules.isNotEmpty) { + if (community.rules != null && community.rules!.isNotEmpty) { communityButtons.add( OBButton( child: Row( diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_categories.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_categories.dart index da950b183..bcad04aff 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_categories.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_categories.dart @@ -16,9 +16,9 @@ class OBCommunityCategories extends StatelessWidget { initialData: community, stream: community.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community community = snapshot.data; + Community community = snapshot.data!; if (community.categories == null) return const SizedBox(); - List categories = community.categories.categories; + List categories = community.categories!.categories!; List connectionItems = []; diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/community_details.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/community_details.dart index e3b42d44e..a5f62c741 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/community_details.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/community_details.dart @@ -16,7 +16,7 @@ class OBCommunityDetails extends StatelessWidget { stream: community.updateSubject, initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community community = snapshot.data; + Community community = snapshot.data!; return Row( mainAxisSize: MainAxisSize.min, diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_favorite.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_favorite.dart index c9a00d4a9..69c925a42 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_favorite.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_favorite.dart @@ -19,8 +19,8 @@ class OBCommunityFavorite extends StatelessWidget { stream: community.updateSubject, initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community community = snapshot.data; - if (community.isFavorite == null || !community.isFavorite) + Community community = snapshot.data!; + if (community.isFavorite == null || !community.isFavorite!) return const SizedBox(); return Row( diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_members_count.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_members_count.dart index 7e6ffc86d..751fc6aaa 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_members_count.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_members_count.dart @@ -12,7 +12,7 @@ class OBCommunityMembersCount extends StatelessWidget { @override Widget build(BuildContext context) { - int membersCount = community.membersCount; + int? membersCount = community.membersCount; LocalizationService localizationService = OpenbookProvider.of(context).localizationService; if (membersCount == null || membersCount == 0) return const SizedBox(); @@ -38,7 +38,7 @@ class OBCommunityMembersCount extends StatelessWidget { onTap: () { bool isPublicCommunity = community.isPublic(); bool isLoggedInUserMember = - community.isMember(userService.getLoggedInUser()); + community.isMember(userService.getLoggedInUser()!); if (isPublicCommunity || isLoggedInUserMember) { navigationService.navigateToCommunityMembers( @@ -57,7 +57,7 @@ class OBCommunityMembersCount extends StatelessWidget { fontSize: 16, fontWeight: FontWeight.bold, color: themeValueParserService - .parseColor(theme.primaryTextColor))), + .parseColor(theme!.primaryTextColor))), TextSpan(text: ' '), TextSpan( text: diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_posts_count.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_posts_count.dart index 45f29cc09..c362ddb2f 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_posts_count.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_posts_count.dart @@ -19,12 +19,12 @@ class OBCommunityPostsCount extends StatefulWidget { } class OBCommunityPostsCountState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; - bool _hasError; - bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; + late bool _hasError; + late bool _needsBootstrap; @override void initState() { @@ -49,7 +49,7 @@ class OBCommunityPostsCountState extends State { stream: widget.community.updateSubject, initialData: widget.community, builder: (BuildContext context, AsyncSnapshot snapshot) { - var community = snapshot.data; + var community = snapshot.data!; return _hasError ? _buildErrorIcon() @@ -94,8 +94,8 @@ class OBCommunityPostsCountState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_type.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_type.dart index a1a490280..b2e2aac36 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_type.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_details/widgets/community_type.dart @@ -13,7 +13,7 @@ class OBCommunityType extends StatelessWidget { @override Widget build(BuildContext context) { - CommunityType type = community.type; + CommunityType? type = community.type; LocalizationService localizationService = OpenbookProvider.of(context).localizationService; if (type == null) { diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_invitation.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_invitation.dart index 1b450be58..f6c6d43ce 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_invitation.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_invitation.dart @@ -15,8 +15,8 @@ class OBCommunityInvitation extends StatelessWidget { stream: community.updateSubject, initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community community = snapshot.data; - bool isInvited = community?.isInvited; + Community? community = snapshot.data; + bool? isInvited = community?.isInvited; if (isInvited == null) return const SizedBox(); @@ -40,7 +40,7 @@ class OBCommunityInvitation extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.end, children: [ - OBJoinCommunityButton(community), + OBJoinCommunityButton(community!), ], ) ], diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_name.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_name.dart index 20f6aeb69..716c3e602 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_name.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_name.dart @@ -14,7 +14,7 @@ class OBCommunityName extends StatelessWidget { initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - String communityName = community?.name; + String? communityName = community?.name; if (communityName == null) return const SizedBox( diff --git a/lib/pages/home/pages/community/widgets/community_card/widgets/community_title.dart b/lib/pages/home/pages/community/widgets/community_card/widgets/community_title.dart index b8b9e88e1..dde7654b8 100644 --- a/lib/pages/home/pages/community/widgets/community_card/widgets/community_title.dart +++ b/lib/pages/home/pages/community/widgets/community_card/widgets/community_title.dart @@ -14,7 +14,7 @@ class OBCommunityTitle extends StatelessWidget { initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - String title = community?.title; + String? title = community?.title; if (title == null) return const SizedBox( diff --git a/lib/pages/home/pages/community/widgets/community_cover.dart b/lib/pages/home/pages/community/widgets/community_cover.dart index 41913f00f..696412c39 100644 --- a/lib/pages/home/pages/community/widgets/community_cover.dart +++ b/lib/pages/home/pages/community/widgets/community_cover.dart @@ -14,7 +14,7 @@ class OBCommunityCover extends StatelessWidget { initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - String communityCover = community?.cover; + String? communityCover = community?.cover; return OBCover( coverUrl: communityCover, diff --git a/lib/pages/home/pages/community/widgets/community_nav_bar.dart b/lib/pages/home/pages/community/widgets/community_nav_bar.dart index 079bf6623..b1843bfaf 100644 --- a/lib/pages/home/pages/community/widgets/community_nav_bar.dart +++ b/lib/pages/home/pages/community/widgets/community_nav_bar.dart @@ -19,7 +19,9 @@ class OBCommunityNavBar extends StatelessWidget builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - String communityColor = community.color; + if (community == null || community.color == null) return SizedBox(); + + String communityColor = community.color!; ThemeValueParserService themeValueParserService = OpenbookProvider.of(context).themeValueParserService; Color color = themeValueParserService.parseColor(communityColor); @@ -38,7 +40,7 @@ class OBCommunityNavBar extends StatelessWidget child: CupertinoNavigationBar( border: null, middle: OBText( - 'c/' + community.name, + 'c/' + (community.name ?? ''), style: TextStyle(color: actionsColor, fontWeight: FontWeight.bold), ), diff --git a/lib/pages/home/pages/community/widgets/community_posts_stream_status_indicator.dart b/lib/pages/home/pages/community/widgets/community_posts_stream_status_indicator.dart index e43aaeded..9c34f1022 100644 --- a/lib/pages/home/pages/community/widgets/community_posts_stream_status_indicator.dart +++ b/lib/pages/home/pages/community/widgets/community_posts_stream_status_indicator.dart @@ -11,11 +11,11 @@ import 'package:flutter/material.dart'; class OBCommunityPostsStreamStatusIndicator extends StatelessWidget { final VoidCallback streamRefresher; - final OBPostsStreamStatus streamStatus; - final List streamPrependedItems; + final OBPostsStreamStatus? streamStatus; + final List? streamPrependedItems; OBCommunityPostsStreamStatusIndicator({ - @required this.streamRefresher, + required this.streamRefresher, this.streamStatus, this.streamPrependedItems, }); diff --git a/lib/pages/home/pages/hashtag/hashtag.dart b/lib/pages/home/pages/hashtag/hashtag.dart index ae0b6aedf..f5ee66b39 100644 --- a/lib/pages/home/pages/hashtag/hashtag.dart +++ b/lib/pages/home/pages/hashtag/hashtag.dart @@ -9,12 +9,12 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBHashtagPage extends StatefulWidget { - final OBHashtagPageController controller; + final OBHashtagPageController? controller; final Hashtag hashtag; final String rawHashtagName; const OBHashtagPage( - {Key key, this.controller, this.hashtag, this.rawHashtagName}) + {Key? key, this.controller, required this.hashtag, required this.rawHashtagName}) : super(key: key); @override @@ -24,10 +24,10 @@ class OBHashtagPage extends StatefulWidget { } class OBHashtagPageState extends State { - Hashtag _hashtag; - bool _needsBootstrap; - UserService _userService; - OBPostsStreamController _obPostsStreamController; + late Hashtag _hashtag; + late bool _needsBootstrap; + late UserService _userService; + late OBPostsStreamController _obPostsStreamController; @override void initState() { @@ -35,7 +35,7 @@ class OBHashtagPageState extends State { _obPostsStreamController = OBPostsStreamController(); _needsBootstrap = true; _hashtag = widget.hashtag; - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); } @override @@ -74,19 +74,19 @@ class OBHashtagPageState extends State { } Future _refreshHashtag() async { - var hashtag = await _userService.getHashtagWithName(_hashtag.name); + var hashtag = await _userService.getHashtagWithName(_hashtag.name!); _setHashtag(hashtag); } Future> _refreshPosts() async { - return (await _userService.getPostsForHashtag(_hashtag)).posts; + return (await _userService.getPostsForHashtag(_hashtag)).posts ?? []; } Future> _loadMorePosts(List posts) async { Post lastPost = posts.last; return (await _userService.getPostsForHashtag(_hashtag, maxId: lastPost.id)) - .posts; + .posts ?? []; } void _setHashtag(Hashtag hashtag) { @@ -97,15 +97,15 @@ class OBHashtagPageState extends State { } class OBHashtagPageController { - OBHashtagPageState _timelinePageState; + OBHashtagPageState? _timelinePageState; - void attach(OBHashtagPageState hashtagPageState) { + void attach(OBHashtagPageState? hashtagPageState) { assert(hashtagPageState != null, 'Cannot attach to empty state'); _timelinePageState = hashtagPageState; } void scrollToTop() { - if (_timelinePageState != null) _timelinePageState.scrollToTop(); + if (_timelinePageState != null) _timelinePageState!.scrollToTop(); } } diff --git a/lib/pages/home/pages/hashtag/widgets/cupertino_nav_bar.dart b/lib/pages/home/pages/hashtag/widgets/cupertino_nav_bar.dart index 4e043a3ad..219f4e7ec 100644 --- a/lib/pages/home/pages/hashtag/widgets/cupertino_nav_bar.dart +++ b/lib/pages/home/pages/hashtag/widgets/cupertino_nav_bar.dart @@ -47,7 +47,7 @@ const _HeroTag _defaultHeroTag = _HeroTag(null); class _HeroTag { const _HeroTag(this.navigator); - final NavigatorState navigator; + final NavigatorState? navigator; // Let the Hero tag be described in tree dumps. @override @@ -62,7 +62,8 @@ class _HeroTag { if (other.runtimeType != runtimeType) { return false; } - final _HeroTag otherTag = other; + // ignore: test_types_in_equals + final _HeroTag otherTag = other as _HeroTag; return navigator == otherTag.navigator; } @@ -78,20 +79,20 @@ class _HeroTag { /// When `updateSystemUiOverlay` is true, the nav bar will update the OS /// status bar's color theme based on the background color of the nav bar. Widget _wrapWithBackground({ - Border border, - Color backgroundColor, - Widget child, + Border? border, + Color? backgroundColor, + Widget? child, bool updateSystemUiOverlay = true, }) { - Widget result = child; + Widget? result = child; if (updateSystemUiOverlay) { - final bool darkBackground = backgroundColor.computeLuminance() < 0.179; + final bool darkBackground = backgroundColor != null && backgroundColor.computeLuminance() < 0.179; final SystemUiOverlayStyle overlayStyle = darkBackground ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark; result = AnnotatedRegion( value: overlayStyle, sized: true, - child: result, + child: result!, ); } final DecoratedBox childWithBackground = DecoratedBox( @@ -109,7 +110,7 @@ Widget _wrapWithBackground({ // `actionsForegroundColor`. CupertinoThemes can be used to support these // scenarios now. To support `actionsForegroundColor`, the nav bar rewraps // its children with a CupertinoTheme. -Widget _wrapActiveColor(Color color, BuildContext context, Widget child) { +Widget _wrapActiveColor(Color? color, BuildContext context, Widget child) { if (color == null) { return child; } @@ -122,7 +123,7 @@ Widget _wrapActiveColor(Color color, BuildContext context, Widget child) { // Whether the current route supports nav bar hero transitions from or to. bool _isTransitionable(BuildContext context) { - final ModalRoute route = ModalRoute.of(context); + final ModalRoute? route = ModalRoute.of(context); // Fullscreen dialogs never transitions their nav bar with other push-style // pages' nav bars or with other fullscreen dialog pages on the way in or on @@ -182,7 +183,7 @@ class OBCupertinoNavigationBar extends StatefulWidget implements ObstructingPreferredSizeWidget { /// Creates a navigation bar in the iOS style. const OBCupertinoNavigationBar({ - Key key, + Key? key, this.leading, this.automaticallyImplyLeading = true, this.automaticallyImplyMiddle = true, @@ -215,7 +216,7 @@ class OBCupertinoNavigationBar extends StatefulWidget /// If null and [automaticallyImplyLeading] is true, an appropriate button /// will be automatically created. /// {@endtemplate} - final Widget leading; + final Widget? leading; /// {@template flutter.cupertino.navBar.automaticallyImplyLeading} /// Controls whether we should try to imply the leading widget if null. @@ -256,7 +257,7 @@ class OBCupertinoNavigationBar extends StatefulWidget /// Has no effect when [leading] is not null or if [automaticallyImplyLeading] /// is false. /// {@endtemplate} - final String previousPageTitle; + final String? previousPageTitle; /// Widget to place in the middle of the navigation bar. Normally a title or /// a segmented control. @@ -264,13 +265,13 @@ class OBCupertinoNavigationBar extends StatefulWidget /// If null and [automaticallyImplyMiddle] is true, an appropriate [Text] /// title will be created if the current route is a [CupertinoPageRoute] and /// has a `title`. - final Widget middle; + final Widget? middle; /// {@template flutter.cupertino.navBar.trailing} /// Widget to place at the end of the navigation bar. Normally additional actions /// taken on the page such as a search or edit function. /// {@endtemplate} - final Widget trailing; + final Widget? trailing; // TODO(xster): https://github.com/flutter/flutter/issues/10469 implement // support for double row navigation bars. @@ -282,7 +283,7 @@ class OBCupertinoNavigationBar extends StatefulWidget /// /// Defaults to [CupertinoTheme]'s `barBackgroundColor` if null. /// {@endtemplate} - final Color backgroundColor; + final Color? backgroundColor; /// {@template flutter.cupertino.navBar.padding} /// Padding for the contents of the navigation bar. @@ -297,7 +298,7 @@ class OBCupertinoNavigationBar extends StatefulWidget /// /// Vertical padding won't change the height of the nav bar. /// {@endtemplate} - final EdgeInsetsDirectional padding; + final EdgeInsetsDirectional? padding; /// {@template flutter.cupertino.navBar.border} /// The border of the navigation bar. By default renders a single pixel bottom border side. @@ -316,7 +317,7 @@ class OBCupertinoNavigationBar extends StatefulWidget /// The default color for text in the [middle] slot is always black, as per /// iOS standard design. @Deprecated('Use CupertinoTheme and primaryColor to propagate color') - final Color actionsForegroundColor; + final Color? actionsForegroundColor; /// {@template flutter.cupertino.navBar.transitionBetweenRoutes} /// Whether to transition between navigation bars. @@ -358,7 +359,7 @@ class OBCupertinoNavigationBar extends StatefulWidget @override bool shouldFullyObstruct(BuildContext context) { final Color backgroundColor = - CupertinoDynamicColor.resolve(this.backgroundColor, context) ?? + CupertinoDynamicColor.maybeResolve(this.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor; return backgroundColor.alpha == 0xFF; } @@ -378,7 +379,7 @@ class OBCupertinoNavigationBar extends StatefulWidget // don't change when rebuilding the nav bar, causing the sub-components to // lose their own states. class _OBCupertinoNavigationBarState extends State { - _NavigationBarStaticComponentsKeys keys; + late _NavigationBarStaticComponentsKeys keys; @override void initState() { @@ -389,7 +390,7 @@ class _OBCupertinoNavigationBarState extends State { @override Widget build(BuildContext context) { final Color backgroundColor = - CupertinoDynamicColor.resolve(widget.backgroundColor, context) ?? + CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor; final _NavigationBarStaticComponents components = @@ -419,7 +420,7 @@ class _OBCupertinoNavigationBarState extends State { ), ); - final Color actionsForegroundColor = CupertinoDynamicColor.resolve( + final Color? actionsForegroundColor = CupertinoDynamicColor.maybeResolve( widget .actionsForegroundColor, // ignore: deprecated_member_use_from_same_package context, @@ -523,7 +524,7 @@ class CupertinoSliverNavigationBar extends StatefulWidget { /// /// The [largeTitle] argument is required and must not be null. const CupertinoSliverNavigationBar({ - Key key, + Key? key, this.largeTitle, this.leading, this.automaticallyImplyLeading = true, @@ -567,12 +568,12 @@ class CupertinoSliverNavigationBar extends StatefulWidget { /// /// This parameter must either be non-null or the route must have a title /// ([CupertinoPageRoute.title]) and [automaticallyImplyTitle] must be true. - final Widget largeTitle; + final Widget? largeTitle; /// {@macro flutter.cupertino.navBar.leading} /// /// This widget is visible in both collapsed and expanded states. - final Widget leading; + final Widget? leading; /// {@macro flutter.cupertino.navBar.automaticallyImplyLeading} final bool automaticallyImplyLeading; @@ -587,7 +588,7 @@ class CupertinoSliverNavigationBar extends StatefulWidget { final bool automaticallyImplyTitle; /// {@macro flutter.cupertino.navBar.previousPageTitle} - final String previousPageTitle; + final String? previousPageTitle; /// A widget to place in the middle of the static navigation bar instead of /// the [largeTitle]. @@ -595,18 +596,18 @@ class CupertinoSliverNavigationBar extends StatefulWidget { /// This widget is visible in both collapsed and expanded states. The text /// supplied in [largeTitle] will no longer appear in collapsed state if a /// [middle] widget is provided. - final Widget middle; + final Widget? middle; /// {@macro flutter.cupertino.navBar.trailing} /// /// This widget is visible in both collapsed and expanded states. - final Widget trailing; + final Widget? trailing; /// {@macro flutter.cupertino.navBar.backgroundColor} - final Color backgroundColor; + final Color? backgroundColor; /// {@macro flutter.cupertino.navBar.padding} - final EdgeInsetsDirectional padding; + final EdgeInsetsDirectional? padding; /// {@macro flutter.cupertino.navBar.border} final Border border; @@ -616,7 +617,7 @@ class CupertinoSliverNavigationBar extends StatefulWidget { /// The default color for text in the [largeTitle] slot is always black, as per /// iOS standard design. @Deprecated('Use CupertinoTheme and primaryColor to propagate color') - final Color actionsForegroundColor; + final Color? actionsForegroundColor; /// {@macro flutter.cupertino.navBar.transitionBetweenRoutes} final bool transitionBetweenRoutes; @@ -625,7 +626,7 @@ class CupertinoSliverNavigationBar extends StatefulWidget { final Object heroTag; /// True if the navigation bar's background color has no transparency. - bool get opaque => backgroundColor.alpha == 0xFF; + bool get opaque => backgroundColor?.alpha == 0xFF; @override _CupertinoSliverNavigationBarState createState() => @@ -637,7 +638,7 @@ class CupertinoSliverNavigationBar extends StatefulWidget { // lose their own states. class _CupertinoSliverNavigationBarState extends State { - _NavigationBarStaticComponentsKeys keys; + late _NavigationBarStaticComponentsKeys keys; @override void initState() { @@ -648,7 +649,7 @@ class _CupertinoSliverNavigationBarState @override Widget build(BuildContext context) { // Lint ignore to maintain backward compatibility. - final Color actionsForegroundColor = CupertinoDynamicColor.resolve( + final Color actionsForegroundColor = CupertinoDynamicColor.maybeResolve( widget.actionsForegroundColor, context) // ignore: deprecated_member_use_from_same_package ?? @@ -681,7 +682,7 @@ class _CupertinoSliverNavigationBarState keys: keys, components: components, userMiddle: widget.middle, - backgroundColor: CupertinoDynamicColor.resolve( + backgroundColor: CupertinoDynamicColor.maybeResolve( widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor, border: widget.border, @@ -702,27 +703,27 @@ class _CupertinoSliverNavigationBarState class _LargeTitleNavigationBarSliverDelegate extends SliverPersistentHeaderDelegate with DiagnosticableTreeMixin { _LargeTitleNavigationBarSliverDelegate({ - @required this.keys, - @required this.components, - @required this.userMiddle, - @required this.backgroundColor, - @required this.border, - @required this.padding, - @required this.actionsForegroundColor, - @required this.transitionBetweenRoutes, - @required this.heroTag, - @required this.persistentHeight, - @required this.alwaysShowMiddle, + required this.keys, + required this.components, + required this.userMiddle, + required this.backgroundColor, + required this.border, + required this.padding, + required this.actionsForegroundColor, + required this.transitionBetweenRoutes, + required this.heroTag, + required this.persistentHeight, + required this.alwaysShowMiddle, }) : assert(persistentHeight != null), assert(alwaysShowMiddle != null), assert(transitionBetweenRoutes != null); final _NavigationBarStaticComponentsKeys keys; final _NavigationBarStaticComponents components; - final Widget userMiddle; + final Widget? userMiddle; final Color backgroundColor; final Border border; - final EdgeInsetsDirectional padding; + final EdgeInsetsDirectional? padding; final Color actionsForegroundColor; final bool transitionBetweenRoutes; final Object heroTag; @@ -790,7 +791,7 @@ class _LargeTitleNavigationBarSliverDelegate .navLargeTitleTextStyle, maxLines: 1, overflow: TextOverflow.ellipsis, - child: components.largeTitle, + child: components.largeTitle ?? SizedBox(), ), ), ), @@ -864,23 +865,23 @@ class _LargeTitleNavigationBarSliverDelegate /// doesn't scroll. class _PersistentNavigationBar extends StatelessWidget { const _PersistentNavigationBar({ - Key key, - this.components, + Key? key, + required this.components, this.padding, this.middleVisible, }) : super(key: key); final _NavigationBarStaticComponents components; - final EdgeInsetsDirectional padding; + final EdgeInsetsDirectional? padding; /// Whether the middle widget has a visible animated opacity. A null value /// means the middle opacity will not be animated. - final bool middleVisible; + final bool? middleVisible; @override Widget build(BuildContext context) { - Widget middle = components.middle; + Widget? middle = components.middle; if (middle != null) { middle = DefaultTextStyle( @@ -892,15 +893,15 @@ class _PersistentNavigationBar extends StatelessWidget { middle = middleVisible == null ? middle : AnimatedOpacity( - opacity: middleVisible ? 1.0 : 0.0, + opacity: middleVisible! ? 1.0 : 0.0, duration: _kNavBarTitleFadeDuration, child: middle, ); } - Widget leading = components.leading; - final Widget backChevron = components.backChevron; - final Widget backLabel = components.backLabel; + Widget? leading = components.leading; + final Widget? backChevron = components.backChevron; + final Widget? backLabel = components.backLabel; if (leading == null && backChevron != null && backLabel != null) { leading = OBCupertinoNavigationBarBackButton._assemble( @@ -920,8 +921,8 @@ class _PersistentNavigationBar extends StatelessWidget { if (padding != null) { paddedToolbar = Padding( padding: EdgeInsets.only( - top: padding.top, - bottom: padding.bottom, + top: padding!.top, + bottom: padding!.bottom, ), child: paddedToolbar, ); @@ -970,17 +971,17 @@ class _NavigationBarStaticComponentsKeys { @immutable class _NavigationBarStaticComponents { _NavigationBarStaticComponents({ - @required _NavigationBarStaticComponentsKeys keys, - @required ModalRoute route, - @required Widget userLeading, - @required bool automaticallyImplyLeading, - @required bool automaticallyImplyTitle, - @required String previousPageTitle, - @required Widget userMiddle, - @required Widget userTrailing, - @required Widget userLargeTitle, - @required EdgeInsetsDirectional padding, - @required bool large, + required _NavigationBarStaticComponentsKeys keys, + required ModalRoute? route, + required Widget? userLeading, + required bool automaticallyImplyLeading, + required bool automaticallyImplyTitle, + required String? previousPageTitle, + required Widget? userMiddle, + required Widget? userTrailing, + required Widget? userLargeTitle, + required EdgeInsetsDirectional? padding, + required bool large, }) : leading = createLeading( leadingKey: keys.leadingKey, userLeading: userLeading, @@ -1022,29 +1023,29 @@ class _NavigationBarStaticComponents { large: large, ); - static Widget _derivedTitle({ - bool automaticallyImplyTitle, - ModalRoute currentRoute, + static Widget? _derivedTitle({ + bool? automaticallyImplyTitle, + ModalRoute? currentRoute, }) { // Auto use the CupertinoPageRoute's title if middle not provided. - if (automaticallyImplyTitle && + if (automaticallyImplyTitle == true && currentRoute is CupertinoPageRoute && currentRoute.title != null) { - return Text(currentRoute.title); + return Text(currentRoute.title!); } return null; } - final KeyedSubtree leading; - static KeyedSubtree createLeading({ - @required GlobalKey leadingKey, - @required Widget userLeading, - @required ModalRoute route, - @required bool automaticallyImplyLeading, - @required EdgeInsetsDirectional padding, + final KeyedSubtree? leading; + static KeyedSubtree? createLeading({ + required GlobalKey leadingKey, + required Widget? userLeading, + required ModalRoute? route, + required bool automaticallyImplyLeading, + required EdgeInsetsDirectional? padding, }) { - Widget leadingContent; + Widget? leadingContent; if (userLeading != null) { leadingContent = userLeading; @@ -1056,7 +1057,7 @@ class _NavigationBarStaticComponents { child: const Text('Close'), padding: EdgeInsets.zero, onPressed: () { - route.navigator.maybePop(); + route.navigator?.maybePop(); }, ); } @@ -1081,12 +1082,12 @@ class _NavigationBarStaticComponents { ); } - final KeyedSubtree backChevron; - static KeyedSubtree createBackChevron({ - @required GlobalKey backChevronKey, - @required Widget userLeading, - @required ModalRoute route, - @required bool automaticallyImplyLeading, + final KeyedSubtree? backChevron; + static KeyedSubtree? createBackChevron({ + required GlobalKey backChevronKey, + required Widget? userLeading, + required ModalRoute? route, + required bool automaticallyImplyLeading, }) { if (userLeading != null || !automaticallyImplyLeading || @@ -1101,13 +1102,13 @@ class _NavigationBarStaticComponents { /// This widget is not decorated with a font since the font style could /// animate during transitions. - final KeyedSubtree backLabel; - static KeyedSubtree createBackLabel({ - @required GlobalKey backLabelKey, - @required Widget userLeading, - @required ModalRoute route, - @required bool automaticallyImplyLeading, - @required String previousPageTitle, + final KeyedSubtree? backLabel; + static KeyedSubtree? createBackLabel({ + required GlobalKey backLabelKey, + required Widget? userLeading, + required ModalRoute? route, + required bool automaticallyImplyLeading, + required String? previousPageTitle, }) { if (userLeading != null || !automaticallyImplyLeading || @@ -1128,16 +1129,16 @@ class _NavigationBarStaticComponents { /// This widget is not decorated with a font since the font style could /// animate during transitions. - final KeyedSubtree middle; - static KeyedSubtree createMiddle({ - @required GlobalKey middleKey, - @required Widget userMiddle, - @required Widget userLargeTitle, - @required bool large, - @required bool automaticallyImplyTitle, - @required ModalRoute route, + final KeyedSubtree? middle; + static KeyedSubtree? createMiddle({ + required GlobalKey middleKey, + required Widget? userMiddle, + required Widget? userLargeTitle, + required bool large, + required bool automaticallyImplyTitle, + required ModalRoute? route, }) { - Widget middleContent = userMiddle; + Widget? middleContent = userMiddle; if (large) { middleContent ??= userLargeTitle; @@ -1158,11 +1159,11 @@ class _NavigationBarStaticComponents { ); } - final KeyedSubtree trailing; - static KeyedSubtree createTrailing({ - @required GlobalKey trailingKey, - @required Widget userTrailing, - @required EdgeInsetsDirectional padding, + final KeyedSubtree? trailing; + static KeyedSubtree? createTrailing({ + required GlobalKey trailingKey, + required Widget? userTrailing, + required EdgeInsetsDirectional? padding, }) { if (userTrailing == null) { return null; @@ -1186,19 +1187,19 @@ class _NavigationBarStaticComponents { /// This widget is not decorated with a font since the font style could /// animate during transitions. - final KeyedSubtree largeTitle; - static KeyedSubtree createLargeTitle({ - @required GlobalKey largeTitleKey, - @required Widget userLargeTitle, - @required bool large, - @required bool automaticImplyTitle, - @required ModalRoute route, + final KeyedSubtree? largeTitle; + static KeyedSubtree? createLargeTitle({ + required GlobalKey largeTitleKey, + required Widget? userLargeTitle, + required bool large, + required bool? automaticImplyTitle, + required ModalRoute? route, }) { if (!large) { return null; } - final Widget largeTitleContent = userLargeTitle ?? + final Widget? largeTitleContent = userLargeTitle ?? _derivedTitle( automaticallyImplyTitle: automaticImplyTitle, currentRoute: route, @@ -1211,7 +1212,7 @@ class _NavigationBarStaticComponents { return KeyedSubtree( key: largeTitleKey, - child: largeTitleContent, + child: largeTitleContent!, ); } } @@ -1255,12 +1256,12 @@ class OBCupertinoNavigationBarBackButton extends StatelessWidget { /// Can be used to override the color of the back button chevron and label. /// /// Defaults to [CupertinoTheme]'s `primaryColor` if null. - final Color color; + final Color? color; /// An override for showing the previous route's title. If null, it will be /// automatically derived from [CupertinoPageRoute.title] if the current and /// previous routes are both [CupertinoPageRoute]s. - final String previousPageTitle; + final String? previousPageTitle; /// An override callback to perform instead of the default behavior which is /// to pop the [Navigator]. @@ -1270,15 +1271,15 @@ class OBCupertinoNavigationBarBackButton extends StatelessWidget { /// situations. /// /// Defaults to null. - final VoidCallback onPressed; + final VoidCallback? onPressed; - final Widget _backChevron; + final Widget? _backChevron; - final Widget _backLabel; + final Widget? _backLabel; @override Widget build(BuildContext context) { - final ModalRoute currentRoute = ModalRoute.of(context); + final ModalRoute? currentRoute = ModalRoute.of(context); if (onPressed == null) { assert( currentRoute?.canPop == true, @@ -1290,7 +1291,7 @@ class OBCupertinoNavigationBarBackButton extends StatelessWidget { CupertinoTheme.of(context).textTheme.navActionTextStyle; if (color != null) { actionTextStyle = actionTextStyle.copyWith( - color: CupertinoDynamicColor.resolve(color, context)); + color: CupertinoDynamicColor.resolve(color!, context)); } return CupertinoButton( @@ -1326,7 +1327,7 @@ class OBCupertinoNavigationBarBackButton extends StatelessWidget { padding: EdgeInsets.zero, onPressed: () { if (onPressed != null) { - onPressed(); + onPressed!(); } else { Navigator.maybePop(context); } @@ -1336,7 +1337,7 @@ class OBCupertinoNavigationBarBackButton extends StatelessWidget { } class _BackChevron extends StatelessWidget { - const _BackChevron({Key key}) : super(key: key); + const _BackChevron({Key? key}) : super(key: key); @override Widget build(BuildContext context) { @@ -1378,18 +1379,18 @@ class _BackChevron extends StatelessWidget { /// is true. class _BackLabel extends StatelessWidget { const _BackLabel({ - Key key, - @required this.specifiedPreviousTitle, - @required this.route, + Key? key, + required this.specifiedPreviousTitle, + required this.route, }) : super(key: key); - final String specifiedPreviousTitle; - final ModalRoute route; + final String? specifiedPreviousTitle; + final ModalRoute? route; // `child` is never passed in into ValueListenableBuilder so it's always // null here and unused. Widget _buildPreviousTitleWidget( - BuildContext context, String previousTitle, Widget child) { + BuildContext context, String? previousTitle, Widget? child) { if (previousTitle == null) { return const SizedBox(height: 0.0, width: 0.0); } @@ -1415,12 +1416,12 @@ class _BackLabel extends StatelessWidget { Widget build(BuildContext context) { if (specifiedPreviousTitle != null) { return _buildPreviousTitleWidget(context, specifiedPreviousTitle, null); - } else if (route is CupertinoPageRoute && !route.isFirst) { - final CupertinoPageRoute cupertinoRoute = route; + } else if (route is CupertinoPageRoute && !route!.isFirst) { + final CupertinoPageRoute cupertinoRoute = route as CupertinoPageRoute; // There is no timing issue because the previousTitle Listenable changes // happen during route modifications before the ValueListenableBuilder // is built. - return ValueListenableBuilder( + return ValueListenableBuilder( valueListenable: cupertinoRoute.previousTitle, builder: _buildPreviousTitleWidget, ); @@ -1440,33 +1441,33 @@ class _BackLabel extends StatelessWidget { /// navigation bar in each route. class _TransitionableNavigationBar extends StatelessWidget { _TransitionableNavigationBar({ - @required this.componentsKeys, - @required this.backgroundColor, - @required this.backButtonTextStyle, - @required this.titleTextStyle, - @required this.largeTitleTextStyle, - @required this.border, - @required this.hasUserMiddle, - @required this.largeExpanded, - @required this.child, + required this.componentsKeys, + required this.backgroundColor, + required this.backButtonTextStyle, + required this.titleTextStyle, + required this.largeTitleTextStyle, + required this.border, + required this.hasUserMiddle, + required this.largeExpanded, + required this.child, }) : assert(componentsKeys != null), assert(largeExpanded != null), assert(!largeExpanded || largeTitleTextStyle != null), super(key: componentsKeys.navBarBoxKey); final _NavigationBarStaticComponentsKeys componentsKeys; - final Color backgroundColor; - final TextStyle backButtonTextStyle; - final TextStyle titleTextStyle; - final TextStyle largeTitleTextStyle; - final Border border; - final bool hasUserMiddle; + final Color? backgroundColor; + final TextStyle? backButtonTextStyle; + final TextStyle? titleTextStyle; + final TextStyle? largeTitleTextStyle; + final Border? border; + final bool? hasUserMiddle; final bool largeExpanded; - final Widget child; + final Widget? child; RenderBox get renderBox { final RenderBox box = - componentsKeys.navBarBoxKey.currentContext.findRenderObject(); + componentsKeys.navBarBoxKey.currentContext!.findRenderObject() as RenderBox; assert( box.attached, '_TransitionableNavigationBar.renderBox should be called when building ' @@ -1479,7 +1480,7 @@ class _TransitionableNavigationBar extends StatelessWidget { @override Widget build(BuildContext context) { assert(() { - bool inHero; + bool? inHero; context.visitAncestorElements((Element ancestor) { if (ancestor is ComponentElement) { assert( @@ -1503,7 +1504,7 @@ class _TransitionableNavigationBar extends StatelessWidget { ); return true; }()); - return child; + return child!; } } @@ -1524,9 +1525,9 @@ class _TransitionableNavigationBar extends StatelessWidget { /// results. class _NavigationBarTransition extends StatelessWidget { _NavigationBarTransition({ - @required this.animation, - @required this.topNavBar, - @required this.bottomNavBar, + required this.animation, + required this.topNavBar, + required this.bottomNavBar, }) : heightTween = Tween( begin: bottomNavBar.renderBox.size.height, end: topNavBar.renderBox.size.height, @@ -1563,7 +1564,7 @@ class _NavigationBarTransition extends StatelessWidget { // moving components without any components inside it itself. AnimatedBuilder( animation: animation, - builder: (BuildContext context, Widget child) { + builder: (BuildContext context, Widget? child) { return _wrapWithBackground( // Don't update the system status bar color mid-flight. updateSystemUiOverlay: false, @@ -1577,19 +1578,19 @@ class _NavigationBarTransition extends StatelessWidget { }, ), // Draw all the components on top of the empty bar box. - componentsTransition.bottomBackChevron, - componentsTransition.bottomBackLabel, - componentsTransition.bottomLeading, - componentsTransition.bottomMiddle, - componentsTransition.bottomLargeTitle, - componentsTransition.bottomTrailing, + componentsTransition.bottomBackChevron ?? SizedBox(), + componentsTransition.bottomBackLabel ?? SizedBox(), + componentsTransition.bottomLeading ?? SizedBox(), + componentsTransition.bottomMiddle ?? SizedBox(), + componentsTransition.bottomLargeTitle ?? SizedBox(), + componentsTransition.bottomTrailing ?? SizedBox(), // Draw top components on top of the bottom components. - componentsTransition.topLeading, - componentsTransition.topBackChevron, - componentsTransition.topBackLabel, - componentsTransition.topMiddle, - componentsTransition.topLargeTitle, - componentsTransition.topTrailing, + componentsTransition.topLeading ?? SizedBox(), + componentsTransition.topBackChevron ?? SizedBox(), + componentsTransition.topBackLabel ?? SizedBox(), + componentsTransition.topMiddle ?? SizedBox(), + componentsTransition.topLargeTitle ?? SizedBox(), + componentsTransition.topTrailing ?? SizedBox(), ]; children.removeWhere((Widget child) => child == null); @@ -1599,7 +1600,7 @@ class _NavigationBarTransition extends StatelessWidget { // can actually be outside the linearly lerp'ed Rect in the middle of // the animation, such as the topLargeTitle. return SizedBox( - height: math.max(heightTween.begin, heightTween.end) + + height: math.max(heightTween.begin!, heightTween.end!) + MediaQuery.of(context).padding.top, width: double.infinity, child: Stack( @@ -1633,10 +1634,10 @@ class _NavigationBarTransition extends StatelessWidget { @immutable class _NavigationBarComponentsTransition { _NavigationBarComponentsTransition({ - @required this.animation, - @required _TransitionableNavigationBar bottomNavBar, - @required _TransitionableNavigationBar topNavBar, - @required TextDirection directionality, + required this.animation, + required _TransitionableNavigationBar bottomNavBar, + required _TransitionableNavigationBar topNavBar, + required TextDirection directionality, }) : bottomComponents = bottomNavBar.componentsKeys, topComponents = topNavBar.componentsKeys, bottomNavBarBox = bottomNavBar.renderBox, @@ -1676,15 +1677,15 @@ class _NavigationBarComponentsTransition { final RenderBox bottomNavBarBox; final RenderBox topNavBarBox; - final TextStyle bottomBackButtonTextStyle; - final TextStyle topBackButtonTextStyle; - final TextStyle bottomTitleTextStyle; - final TextStyle topTitleTextStyle; - final TextStyle bottomLargeTitleTextStyle; - final TextStyle topLargeTitleTextStyle; + final TextStyle? bottomBackButtonTextStyle; + final TextStyle? topBackButtonTextStyle; + final TextStyle? bottomTitleTextStyle; + final TextStyle? topTitleTextStyle; + final TextStyle? bottomLargeTitleTextStyle; + final TextStyle? topLargeTitleTextStyle; - final bool bottomHasUserMiddle; - final bool topHasUserMiddle; + final bool? bottomHasUserMiddle; + final bool? topHasUserMiddle; final bool bottomLargeExpanded; final bool topLargeExpanded; @@ -1699,9 +1700,9 @@ class _NavigationBarComponentsTransition { // translate it into a RelativeBox in the transition navigation bar box. RelativeRect positionInTransitionBox( GlobalKey key, { - @required RenderBox from, + required RenderBox from, }) { - final RenderBox componentBox = key.currentContext.findRenderObject(); + final RenderBox componentBox = key.currentContext?.findRenderObject() as RenderBox; assert(componentBox.attached); return RelativeRect.fromRect( @@ -1722,16 +1723,16 @@ class _NavigationBarComponentsTransition { // BoxConstraints of the 'from' widget so that animating font sizes etc don't // produce rounding error artifacts with a linearly resizing rect. RelativeRectTween slideFromLeadingEdge({ - @required GlobalKey fromKey, - @required RenderBox fromNavBarBox, - @required GlobalKey toKey, - @required RenderBox toNavBarBox, + required GlobalKey fromKey, + required RenderBox fromNavBarBox, + required GlobalKey toKey, + required RenderBox toNavBarBox, }) { final RelativeRect fromRect = positionInTransitionBox(fromKey, from: fromNavBarBox); - final RenderBox fromBox = fromKey.currentContext.findRenderObject(); - final RenderBox toBox = toKey.currentContext.findRenderObject(); + final RenderBox fromBox = fromKey.currentContext!.findRenderObject() as RenderBox; + final RenderBox toBox = toKey.currentContext!.findRenderObject() as RenderBox; // We move a box with the size of the 'from' render object such that its // upper left corner is at the upper left corner of the 'to' render object. @@ -1771,9 +1772,9 @@ class _NavigationBarComponentsTransition { )); } - Widget get bottomLeading { - final KeyedSubtree bottomLeading = - bottomComponents.leadingKey.currentWidget; + Widget? get bottomLeading { + final KeyedSubtree? bottomLeading = + bottomComponents.leadingKey.currentWidget as KeyedSubtree?; if (bottomLeading == null) { return null; @@ -1789,9 +1790,9 @@ class _NavigationBarComponentsTransition { ); } - Widget get bottomBackChevron { - final KeyedSubtree bottomBackChevron = - bottomComponents.backChevronKey.currentWidget; + Widget? get bottomBackChevron { + final KeyedSubtree? bottomBackChevron = + bottomComponents.backChevronKey.currentWidget as KeyedSubtree?; if (bottomBackChevron == null) { return null; @@ -1803,16 +1804,16 @@ class _NavigationBarComponentsTransition { child: FadeTransition( opacity: fadeOutBy(0.6), child: DefaultTextStyle( - style: bottomBackButtonTextStyle, + style: bottomBackButtonTextStyle!, child: bottomBackChevron.child, ), ), ); } - Widget get bottomBackLabel { - final KeyedSubtree bottomBackLabel = - bottomComponents.backLabelKey.currentWidget; + Widget? get bottomBackLabel { + final KeyedSubtree? bottomBackLabel = + bottomComponents.backLabelKey.currentWidget as KeyedSubtree?; if (bottomBackLabel == null) { return null; @@ -1838,21 +1839,21 @@ class _NavigationBarComponentsTransition { child: FadeTransition( opacity: fadeOutBy(0.2), child: DefaultTextStyle( - style: bottomBackButtonTextStyle, + style: bottomBackButtonTextStyle!, child: bottomBackLabel.child, ), ), ); } - Widget get bottomMiddle { - final KeyedSubtree bottomMiddle = bottomComponents.middleKey.currentWidget; - final KeyedSubtree topBackLabel = topComponents.backLabelKey.currentWidget; - final KeyedSubtree topLeading = topComponents.leadingKey.currentWidget; + Widget? get bottomMiddle { + final KeyedSubtree? bottomMiddle = bottomComponents.middleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree?; // The middle component is non-null when the nav bar is a large title // nav bar but would be invisible when expanded, therefore don't show it here. - if (!bottomHasUserMiddle && bottomLargeExpanded) { + if ((bottomHasUserMiddle == null || !bottomHasUserMiddle!) && bottomLargeExpanded) { return null; } @@ -1867,7 +1868,7 @@ class _NavigationBarComponentsTransition { )), child: FadeTransition( // A custom middle widget like a segmented control fades away faster. - opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7), + opacity: fadeOutBy(bottomHasUserMiddle! ? 0.4 : 0.7), child: Align( // As the text shrinks, make sure it's still anchored to the leading // edge of a constantly sized outer box. @@ -1892,10 +1893,10 @@ class _NavigationBarComponentsTransition { rect: positionInTransitionBox(bottomComponents.middleKey, from: bottomNavBarBox), child: FadeTransition( - opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7), + opacity: fadeOutBy(bottomHasUserMiddle! ? 0.4 : 0.7), // Keep the font when transitioning into a non-back label leading. child: DefaultTextStyle( - style: bottomTitleTextStyle, + style: bottomTitleTextStyle!, child: bottomMiddle.child, ), ), @@ -1905,11 +1906,11 @@ class _NavigationBarComponentsTransition { return null; } - Widget get bottomLargeTitle { - final KeyedSubtree bottomLargeTitle = - bottomComponents.largeTitleKey.currentWidget; - final KeyedSubtree topBackLabel = topComponents.backLabelKey.currentWidget; - final KeyedSubtree topLeading = topComponents.leadingKey.currentWidget; + Widget? get bottomLargeTitle { + final KeyedSubtree? bottomLargeTitle = + bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree?; if (bottomLargeTitle == null || !bottomLargeExpanded) { return null; @@ -1969,7 +1970,7 @@ class _NavigationBarComponentsTransition { opacity: fadeOutBy(0.4), // Keep the font when transitioning into a non-back-label leading. child: DefaultTextStyle( - style: bottomLargeTitleTextStyle, + style: bottomLargeTitleTextStyle!, child: bottomLargeTitle.child, ), ), @@ -1979,9 +1980,9 @@ class _NavigationBarComponentsTransition { return null; } - Widget get bottomTrailing { - final KeyedSubtree bottomTrailing = - bottomComponents.trailingKey.currentWidget; + Widget? get bottomTrailing { + final KeyedSubtree? bottomTrailing = + bottomComponents.trailingKey.currentWidget as KeyedSubtree?; if (bottomTrailing == null) { return null; @@ -1997,8 +1998,8 @@ class _NavigationBarComponentsTransition { ); } - Widget get topLeading { - final KeyedSubtree topLeading = topComponents.leadingKey.currentWidget; + Widget? get topLeading { + final KeyedSubtree? topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree?; if (topLeading == null) { return null; @@ -2014,11 +2015,11 @@ class _NavigationBarComponentsTransition { ); } - Widget get topBackChevron { - final KeyedSubtree topBackChevron = - topComponents.backChevronKey.currentWidget; - final KeyedSubtree bottomBackChevron = - bottomComponents.backChevronKey.currentWidget; + Widget? get topBackChevron { + final KeyedSubtree? topBackChevron = + topComponents.backChevronKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomBackChevron = + bottomComponents.backChevronKey.currentWidget as KeyedSubtree?; if (topBackChevron == null) { return null; @@ -2033,7 +2034,7 @@ class _NavigationBarComponentsTransition { // right. if (bottomBackChevron == null) { final RenderBox topBackChevronBox = - topComponents.backChevronKey.currentContext.findRenderObject(); + topComponents.backChevronKey.currentContext!.findRenderObject() as RenderBox; from = to.shift( Offset( forwardDirection * topBackChevronBox.size.width * 2.0, @@ -2052,28 +2053,28 @@ class _NavigationBarComponentsTransition { child: FadeTransition( opacity: fadeInFrom(bottomBackChevron == null ? 0.7 : 0.4), child: DefaultTextStyle( - style: topBackButtonTextStyle, + style: topBackButtonTextStyle!, child: topBackChevron.child, ), ), ); } - Widget get topBackLabel { - final KeyedSubtree bottomMiddle = bottomComponents.middleKey.currentWidget; - final KeyedSubtree bottomLargeTitle = - bottomComponents.largeTitleKey.currentWidget; - final KeyedSubtree topBackLabel = topComponents.backLabelKey.currentWidget; + Widget? get topBackLabel { + final KeyedSubtree? bottomMiddle = bottomComponents.middleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomLargeTitle = + bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree?; if (topBackLabel == null) { return null; } - final RenderAnimatedOpacity topBackLabelOpacity = topComponents + final RenderAnimatedOpacity? topBackLabelOpacity = topComponents .backLabelKey.currentContext ?.findAncestorRenderObjectOfType(); - Animation midClickOpacity; + Animation? midClickOpacity; if (topBackLabelOpacity != null && topBackLabelOpacity.opacity.value < 1.0) { midClickOpacity = animation.drive(Tween( @@ -2138,8 +2139,8 @@ class _NavigationBarComponentsTransition { return null; } - Widget get topMiddle { - final KeyedSubtree topMiddle = topComponents.middleKey.currentWidget; + Widget? get topMiddle { + final KeyedSubtree? topMiddle = topComponents.middleKey.currentWidget as KeyedSubtree?; if (topMiddle == null) { return null; @@ -2147,7 +2148,7 @@ class _NavigationBarComponentsTransition { // The middle component is non-null when the nav bar is a large title // nav bar but would be invisible when expanded, therefore don't show it here. - if (!topHasUserMiddle && topLargeExpanded) { + if ((topHasUserMiddle == null || !topHasUserMiddle!) && topLargeExpanded) { return null; } @@ -2170,15 +2171,15 @@ class _NavigationBarComponentsTransition { child: FadeTransition( opacity: fadeInFrom(0.25), child: DefaultTextStyle( - style: topTitleTextStyle, + style: topTitleTextStyle!, child: topMiddle.child, ), ), ); } - Widget get topTrailing { - final KeyedSubtree topTrailing = topComponents.trailingKey.currentWidget; + Widget? get topTrailing { + final KeyedSubtree? topTrailing = topComponents.trailingKey.currentWidget as KeyedSubtree?; if (topTrailing == null) { return null; @@ -2194,9 +2195,9 @@ class _NavigationBarComponentsTransition { ); } - Widget get topLargeTitle { - final KeyedSubtree topLargeTitle = - topComponents.largeTitleKey.currentWidget; + Widget? get topLargeTitle { + final KeyedSubtree? topLargeTitle = + topComponents.largeTitleKey.currentWidget as KeyedSubtree?; if (topLargeTitle == null || !topLargeExpanded) { return null; @@ -2221,7 +2222,7 @@ class _NavigationBarComponentsTransition { child: FadeTransition( opacity: fadeInFrom(0.3), child: DefaultTextStyle( - style: topLargeTitleTextStyle, + style: topLargeTitleTextStyle!, maxLines: 1, overflow: TextOverflow.ellipsis, child: topLargeTitle.child, @@ -2234,9 +2235,9 @@ class _NavigationBarComponentsTransition { /// Navigation bars' hero rect tween that will move between the static bars /// but keep a constant size that's the bigger of both navigation bars. CreateRectTween _linearTranslateWithLargestRectSizeTween = - (Rect begin, Rect end) { + (Rect? begin, Rect? end) { final Size largestSize = Size( - math.max(begin.size.width, end.size.width), + math.max(begin!.size.width, end!.size.width), math.max(begin.size.height, end.size.height), ); return RectTween( @@ -2273,54 +2274,54 @@ final HeroPlaceholderBuilder _navBarHeroLaunchPadBuilder = ( /// Navigation bars' hero flight shuttle builder. final HeroFlightShuttleBuilder _navBarHeroFlightShuttleBuilder = ( - BuildContext flightContext, - Animation animation, - HeroFlightDirection flightDirection, - BuildContext fromHeroContext, - BuildContext toHeroContext, + BuildContext? flightContext, + Animation? animation, + HeroFlightDirection? flightDirection, + BuildContext? fromHeroContext, + BuildContext? toHeroContext, ) { assert(animation != null); assert(flightDirection != null); assert(fromHeroContext != null); assert(toHeroContext != null); - assert(fromHeroContext.widget is Hero); - assert(toHeroContext.widget is Hero); + assert(fromHeroContext?.widget is Hero); + assert(toHeroContext?.widget is Hero); - final Hero fromHeroWidget = fromHeroContext.widget; - final Hero toHeroWidget = toHeroContext.widget; + final Hero fromHeroWidget = fromHeroContext!.widget as Hero; + final Hero toHeroWidget = toHeroContext!.widget as Hero; assert(fromHeroWidget.child is _TransitionableNavigationBar); assert(toHeroWidget.child is _TransitionableNavigationBar); - final _TransitionableNavigationBar fromNavBar = fromHeroWidget.child; - final _TransitionableNavigationBar toNavBar = toHeroWidget.child; + final _TransitionableNavigationBar fromNavBar = fromHeroWidget.child as _TransitionableNavigationBar; + final _TransitionableNavigationBar toNavBar = toHeroWidget.child as _TransitionableNavigationBar; assert(fromNavBar.componentsKeys != null); assert(toNavBar.componentsKeys != null); assert( - fromNavBar.componentsKeys.navBarBoxKey.currentContext.owner != null, + fromNavBar.componentsKeys.navBarBoxKey.currentContext?.owner != null, 'The from nav bar to Hero must have been mounted in the previous frame', ); assert( - toNavBar.componentsKeys.navBarBoxKey.currentContext.owner != null, + toNavBar.componentsKeys.navBarBoxKey.currentContext?.owner != null, 'The to nav bar to Hero must have been mounted in the previous frame', ); switch (flightDirection) { case HeroFlightDirection.push: return _NavigationBarTransition( - animation: animation, + animation: animation!, bottomNavBar: fromNavBar, topNavBar: toNavBar, ); - break; case HeroFlightDirection.pop: return _NavigationBarTransition( - animation: animation, + animation: animation!, bottomNavBar: toNavBar, topNavBar: fromNavBar, ); + case null: + return SizedBox(); } - return null; }; diff --git a/lib/pages/home/pages/hashtag/widgets/hashtag_cover.dart b/lib/pages/home/pages/hashtag/widgets/hashtag_cover.dart index e4a9ffbd1..d173c42a4 100644 --- a/lib/pages/home/pages/hashtag/widgets/hashtag_cover.dart +++ b/lib/pages/home/pages/hashtag/widgets/hashtag_cover.dart @@ -14,7 +14,7 @@ class OBHashtagCover extends StatelessWidget { stream: hashtag.updateSubject, initialData: hashtag, builder: (BuildContext context, AsyncSnapshot snapshot) { - String hashtagCover = hashtag?.image; + String? hashtagCover = hashtag.image; return Stack( children: [ diff --git a/lib/pages/home/pages/hashtag/widgets/hashtag_nav_bar.dart b/lib/pages/home/pages/hashtag/widgets/hashtag_nav_bar.dart index 5206f1aa3..d518dc836 100644 --- a/lib/pages/home/pages/hashtag/widgets/hashtag_nav_bar.dart +++ b/lib/pages/home/pages/hashtag/widgets/hashtag_nav_bar.dart @@ -14,27 +14,27 @@ class OBHashtagNavBar extends StatelessWidget final Hashtag hashtag; final String rawHashtagName; - const OBHashtagNavBar({Key key, this.hashtag, this.rawHashtagName}) + const OBHashtagNavBar({Key? key, required this.hashtag, required this.rawHashtagName}) : super(key: key); @override Widget build(BuildContext context) { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); final Color hashtagTextColor = - openbookProvider.utilsService.parseHexColor(hashtag.textColor); + openbookProvider.utilsService.parseHexColor(hashtag.textColor ?? ''); return StreamBuilder( stream: hashtag.updateSubject, initialData: hashtag, builder: (BuildContext context, AsyncSnapshot snapshot) { - var hashtag = snapshot.data; + var hashtag = snapshot.data!; return hashtag.image != null ? OBImageNavBar( trailing: OBHashtagMoreButton( hashtag: hashtag, ), - imageSrc: hashtag.image, + imageSrc: hashtag.image!, middle: Row( mainAxisSize: MainAxisSize.min, children: [ diff --git a/lib/pages/home/pages/menu/menu.dart b/lib/pages/home/pages/menu/menu.dart index 20524b490..652b568f1 100644 --- a/lib/pages/home/pages/menu/menu.dart +++ b/lib/pages/home/pages/menu/menu.dart @@ -11,13 +11,13 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBMainMenuPage extends StatelessWidget { - final OBMainMenuPageController controller; + final OBMainMenuPageController? controller; const OBMainMenuPage({this.controller}); @override Widget build(BuildContext context) { - controller.attach(context: context); + controller?.attach(context: context); var openbookProvider = OpenbookProvider.of(context); var localizationService = openbookProvider.localizationService; var intercomService = openbookProvider.intercomService; @@ -35,17 +35,17 @@ class OBMainMenuPage extends StatelessWidget { stream: userService.loggedInUserChange, initialData: userService.getLoggedInUser(), builder: (BuildContext context, - AsyncSnapshot loggedInUserSnapshot) { - User loggedInUser = loggedInUserSnapshot.data; + AsyncSnapshot loggedInUserSnapshot) { + User? loggedInUser = loggedInUserSnapshot.data; if (loggedInUser == null) return const SizedBox(); return StreamBuilder( - stream: loggedInUserSnapshot.data.updateSubject, + stream: loggedInUserSnapshot.data!.updateSubject, initialData: loggedInUserSnapshot.data, builder: (BuildContext context, AsyncSnapshot userSnapshot) { - User user = userSnapshot.data; + User user = userSnapshot.data!; return Expanded( child: ListView( @@ -146,8 +146,8 @@ class OBMainMenuPage extends StatelessWidget { stream: userService.loggedInUserChange, initialData: userService.getLoggedInUser(), builder: (BuildContext context, - AsyncSnapshot snapshot) { - User loggedInUser = snapshot.data; + AsyncSnapshot snapshot) { + User? loggedInUser = snapshot.data; if (loggedInUser == null) return const SizedBox(); @@ -165,8 +165,8 @@ class OBMainMenuPage extends StatelessWidget { stream: userService.loggedInUserChange, initialData: userService.getLoggedInUser(), builder: (BuildContext context, - AsyncSnapshot snapshot) { - User loggedInUser = snapshot.data; + AsyncSnapshot snapshot) { + User? loggedInUser = snapshot.data; if (loggedInUser == null || !(loggedInUser.isGlobalModerator ?? false)) diff --git a/lib/pages/home/pages/menu/pages/community_guidelines.dart b/lib/pages/home/pages/menu/pages/community_guidelines.dart index bc30ad204..185d694d9 100644 --- a/lib/pages/home/pages/menu/pages/community_guidelines.dart +++ b/lib/pages/home/pages/menu/pages/community_guidelines.dart @@ -16,10 +16,10 @@ class OBCommunityGuidelinesPage extends StatefulWidget { } class OBCommunityGuidelinesPageState extends State { - String _guidelinesText; - bool _needsBootstrap; + late String _guidelinesText; + late bool _needsBootstrap; - CancelableOperation _getGuidelinesOperation; + CancelableOperation? _getGuidelinesOperation; @override void initState() { @@ -31,7 +31,7 @@ class OBCommunityGuidelinesPageState extends State { @override void dispose() { super.dispose(); - if (_getGuidelinesOperation != null) _getGuidelinesOperation.cancel(); + if (_getGuidelinesOperation != null) _getGuidelinesOperation!.cancel(); } void _bootstrap() async { @@ -39,7 +39,7 @@ class OBCommunityGuidelinesPageState extends State { _getGuidelinesOperation = CancelableOperation.fromFuture( openbookProvider.documentsService.getCommunityGuidelines()); - String guidelines = await _getGuidelinesOperation.value; + String guidelines = await _getGuidelinesOperation?.value; _setGuidelinesText(guidelines); } diff --git a/lib/pages/home/pages/menu/pages/connections_circle/connections_circle.dart b/lib/pages/home/pages/menu/pages/connections_circle/connections_circle.dart index dd42c63e3..74e55b88f 100644 --- a/lib/pages/home/pages/menu/pages/connections_circle/connections_circle.dart +++ b/lib/pages/home/pages/menu/pages/connections_circle/connections_circle.dart @@ -28,14 +28,14 @@ class OBConnectionsCirclePage extends StatefulWidget { } class OBConnectionsCirclePageState extends State { - UserService _userService; - ToastService _toastService; - ModalService _modalService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ModalService _modalService; + late LocalizationService _localizationService; - GlobalKey _refreshIndicatorKey; - bool _needsBootstrap; - bool _isConnectionsCircle; + late GlobalKey _refreshIndicatorKey; + late bool _needsBootstrap; + late bool _isConnectionsCircle; @override void initState() { @@ -97,7 +97,7 @@ class OBConnectionsCirclePageState extends State { void _bootstrap() async { await _refreshConnectionsCircle(); - var loggedInUser = _userService.getLoggedInUser(); + var loggedInUser = _userService.getLoggedInUser()!; bool isConnectionsCircle = loggedInUser.isConnectionsCircle(widget.connectionsCircle); _setIsConnectionsCircle(isConnectionsCircle); @@ -106,7 +106,7 @@ class OBConnectionsCirclePageState extends State { Future _refreshConnectionsCircle() async { try { await _userService - .getConnectionsCircleWithId(widget.connectionsCircle.id); + .getConnectionsCircleWithId(widget.connectionsCircle.id!); } catch (error) { _onError(error); } @@ -117,8 +117,8 @@ class OBConnectionsCirclePageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_header/connections_circle_header.dart b/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_header/connections_circle_header.dart index cb1f53284..0d3b3b516 100644 --- a/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_header/connections_circle_header.dart +++ b/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_header/connections_circle_header.dart @@ -20,7 +20,7 @@ class OBConnectionsCircleHeader extends StatelessWidget { stream: connectionsCircle.updateSubject, initialData: connectionsCircle, builder: (BuildContext context, AsyncSnapshot snapshot) { - var connectionsCircle = snapshot.data; + var connectionsCircle = snapshot.data!; LocalizationService _localizationService = OpenbookProvider.of(context).localizationService; List columnItems = [_buildCircleName(connectionsCircle)]; diff --git a/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_header/widgets/connections_circle_name.dart b/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_header/widgets/connections_circle_name.dart index 3c3c8c3b8..922ea1558 100644 --- a/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_header/widgets/connections_circle_name.dart +++ b/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_header/widgets/connections_circle_name.dart @@ -15,7 +15,7 @@ class OBConnectionsCircleName extends StatelessWidget { stream: connectionsCircle.updateSubject, initialData: connectionsCircle, builder: (BuildContext context, AsyncSnapshot snapshot) { - var connectionsCircle = snapshot.data; + var connectionsCircle = snapshot.data!; return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -28,7 +28,7 @@ class OBConnectionsCircleName extends StatelessWidget { children: [ Flexible( child: OBPrimaryAccentText( - connectionsCircle.name, + connectionsCircle.name!, size: OBTextSize.extraLarge, overflow: TextOverflow.ellipsis, maxLines: 2, diff --git a/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_users.dart b/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_users.dart index a845b9962..4a79f3dfa 100644 --- a/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_users.dart +++ b/lib/pages/home/pages/menu/pages/connections_circle/widgets/connections_circle_users.dart @@ -22,7 +22,7 @@ class OBConnectionsCircleUsers extends StatelessWidget { initialData: connectionsCircle, builder: (BuildContext context, AsyncSnapshot snapshot) { var connectionsCircle = snapshot.data; - List users = connectionsCircle.users?.users ?? []; + List users = connectionsCircle?.users?.users ?? []; var onUserTilePressed = (User user) { navigationService.navigateToUserProfile( @@ -35,7 +35,7 @@ class OBConnectionsCircleUsers extends StatelessWidget { itemBuilder: (context, index) { var user = users[index]; - Widget trailing; + Widget? trailing; bool isFullyConnected = user.isFullyConnected ?? true; if (!isFullyConnected) { diff --git a/lib/pages/home/pages/menu/pages/connections_circles/connections_circles.dart b/lib/pages/home/pages/menu/pages/connections_circles/connections_circles.dart index e3e907838..ea6bd8457 100644 --- a/lib/pages/home/pages/menu/pages/connections_circles/connections_circles.dart +++ b/lib/pages/home/pages/menu/pages/connections_circles/connections_circles.dart @@ -25,18 +25,18 @@ class OBConnectionsCirclesPage extends StatefulWidget { } class OBConnectionsCirclesPageState extends State { - UserService _userService; - ToastService _toastService; - ModalService _modalService; + late UserService _userService; + late ToastService _toastService; + late ModalService _modalService; - GlobalKey _refreshIndicatorKey; - ScrollController _connectionsCirclesScrollController; + late GlobalKey _refreshIndicatorKey; + late ScrollController _connectionsCirclesScrollController; List _connectionsCircles = []; List _connectionsCirclesSearchResults = []; - String _searchQuery; + String? _searchQuery; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -119,7 +119,7 @@ class OBConnectionsCirclesPageState extends State { return OBConnectionsCircleTile( connectionsCircle: connectionsCircle, isReadOnly: loggedInUser - .isConnectionsCircle(connectionsCircle), + ?.isConnectionsCircle(connectionsCircle) ?? false, onConnectionsCircleDeletedCallback: onConnectionsCircleDeletedCallback, ); @@ -140,7 +140,7 @@ class OBConnectionsCirclesPageState extends State { Future _refreshComments() async { try { _connectionsCircles = - (await _userService.getConnectionsCircles()).circles; + (await _userService.getConnectionsCircles()).circles!; // This assumes the connections circle always come last Circle connectionsCircle = _connectionsCircles.removeLast(); _connectionsCircles.insert(0, connectionsCircle); @@ -156,8 +156,8 @@ class OBConnectionsCirclesPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; @@ -165,7 +165,7 @@ class OBConnectionsCirclesPageState extends State { } void _onWantsToCreateCircle() async { - Circle createdConnectionsCircle = + Circle? createdConnectionsCircle = await _modalService.openCreateConnectionsCircle(context: context); if (createdConnectionsCircle != null) { _onConnectionsCircleCreated(createdConnectionsCircle); @@ -181,7 +181,7 @@ class OBConnectionsCirclesPageState extends State { _setSearchQuery(query); String uppercaseQuery = query.toUpperCase(); var searchResults = _connectionsCircles.where((connectionsCircle) { - return connectionsCircle.name.toUpperCase().contains(uppercaseQuery); + return connectionsCircle.name!.toUpperCase().contains(uppercaseQuery); }).toList(); _setConnectionsCirclesSearchResults(searchResults); @@ -226,7 +226,7 @@ class OBConnectionsCirclesPageState extends State { }); } - void _setSearchQuery(String searchQuery) { + void _setSearchQuery(String? searchQuery) { setState(() { _searchQuery = searchQuery; }); diff --git a/lib/pages/home/pages/menu/pages/connections_circles/widgets/connections_circle_tile.dart b/lib/pages/home/pages/menu/pages/connections_circles/widgets/connections_circle_tile.dart index 4728b3f14..d93597ad2 100644 --- a/lib/pages/home/pages/menu/pages/connections_circles/widgets/connections_circle_tile.dart +++ b/lib/pages/home/pages/menu/pages/connections_circles/widgets/connections_circle_tile.dart @@ -14,12 +14,12 @@ import 'package:flutter_slidable/flutter_slidable.dart'; class OBConnectionsCircleTile extends StatefulWidget { final Circle connectionsCircle; - final VoidCallback onConnectionsCircleDeletedCallback; + final VoidCallback? onConnectionsCircleDeletedCallback; final bool isReadOnly; OBConnectionsCircleTile( - {@required this.connectionsCircle, - Key key, + {required this.connectionsCircle, + Key? key, this.onConnectionsCircleDeletedCallback, this.isReadOnly = false}) : super(key: key); @@ -31,11 +31,11 @@ class OBConnectionsCircleTile extends StatefulWidget { } class OBConnectionsCircleTileState extends State { - bool _requestInProgress; - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; - LocalizationService _localizationService; + late bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; + late LocalizationService _localizationService; @override void initState() { @@ -76,7 +76,7 @@ class OBConnectionsCircleTileState extends State { Widget _buildTile() { String prettyCount = getPrettyCount( - widget.connectionsCircle.usersCount, _localizationService); + widget.connectionsCircle.usersCount ?? 0, _localizationService); return ListTile( onTap: () { @@ -88,7 +88,7 @@ class OBConnectionsCircleTileState extends State { size: OBCircleColorPreviewSize.medium, ), title: OBText( - widget.connectionsCircle.name, + widget.connectionsCircle.name!, style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: OBSecondaryText( @@ -102,7 +102,7 @@ class OBConnectionsCircleTileState extends State { // widget.post.decreaseCommentsCount(); _setRequestInProgress(false); if (widget.onConnectionsCircleDeletedCallback != null) { - widget.onConnectionsCircleDeletedCallback(); + widget.onConnectionsCircleDeletedCallback!(); } } catch (error) { _onError(error); @@ -116,8 +116,8 @@ class OBConnectionsCircleTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/pages/menu/pages/delete_account/delete_account.dart b/lib/pages/home/pages/menu/pages/delete_account/delete_account.dart index 60dcf1752..bfd924f40 100644 --- a/lib/pages/home/pages/menu/pages/delete_account/delete_account.dart +++ b/lib/pages/home/pages/menu/pages/delete_account/delete_account.dart @@ -18,9 +18,9 @@ class OBDeleteAccountPage extends StatefulWidget { } class OBDeleteAccountPageState extends State { - ValidationService _validationService; - NavigationService _navigationService; - LocalizationService _localizationService; + late ValidationService _validationService; + late NavigationService _navigationService; + late LocalizationService _localizationService; static const double INPUT_ICONS_SIZE = 16; static const EdgeInsetsGeometry INPUT_CONTENT_PADDING = @@ -66,9 +66,9 @@ class OBDeleteAccountPageState extends State { labelText: _localizationService.user__delete_account_current_pwd, hintText: _localizationService.user__delete_account_current_pwd_hint, ), - validator: (String password) { + validator: (String? password) { if (!_formWasSubmitted) return null; - String validatePassword = + String? validatePassword = _validationService.validateUserPassword(password); if (validatePassword != null) return validatePassword; }, @@ -79,7 +79,7 @@ class OBDeleteAccountPageState extends State { )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: _localizationService.user__delete_account_title, trailing: OBButton( @@ -92,7 +92,7 @@ class OBDeleteAccountPageState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { diff --git a/lib/pages/home/pages/menu/pages/delete_account/pages/confirm_delete_account.dart b/lib/pages/home/pages/menu/pages/delete_account/pages/confirm_delete_account.dart index 2cfd4d7e2..81eb4b4f5 100644 --- a/lib/pages/home/pages/menu/pages/delete_account/pages/confirm_delete_account.dart +++ b/lib/pages/home/pages/menu/pages/delete_account/pages/confirm_delete_account.dart @@ -12,7 +12,7 @@ import 'package:flutter/cupertino.dart'; class OBConfirmDeleteAccount extends StatefulWidget { final String userPassword; - const OBConfirmDeleteAccount({Key key, @required this.userPassword}) + const OBConfirmDeleteAccount({Key? key, required this.userPassword}) : super(key: key); @override @@ -22,11 +22,11 @@ class OBConfirmDeleteAccount extends StatefulWidget { } class OBConfirmDeleteAccountState extends State { - bool _confirmationInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late bool _confirmationInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; @override void initState() { @@ -131,8 +131,8 @@ class OBConfirmDeleteAccountState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); if (error.response.isUnauthorized()) { // Password was incorrect diff --git a/lib/pages/home/pages/menu/pages/followers.dart b/lib/pages/home/pages/menu/pages/followers.dart index 103f24922..d6f4551f8 100644 --- a/lib/pages/home/pages/menu/pages/followers.dart +++ b/lib/pages/home/pages/menu/pages/followers.dart @@ -23,12 +23,12 @@ class OBFollowersPage extends StatefulWidget { } class OBFollowersPageState extends State { - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -82,7 +82,7 @@ class OBFollowersPageState extends State { Future> _refreshFollowers() async { UsersList followers = await _userService.getFollowers(); - return followers.users; + return followers.users ?? []; } Future> _loadMoreFollowers(List followersList) async { @@ -93,12 +93,12 @@ class OBFollowersPageState extends State { count: 20, )) .users; - return moreFollowers; + return moreFollowers ?? []; } Future> _searchFollowers(String query) async { UsersList results = await _userService.searchFollowers(query: query); - return results.users; + return results.users ?? []; } } diff --git a/lib/pages/home/pages/menu/pages/following.dart b/lib/pages/home/pages/menu/pages/following.dart index 498fcb580..cf64fec66 100644 --- a/lib/pages/home/pages/menu/pages/following.dart +++ b/lib/pages/home/pages/menu/pages/following.dart @@ -23,12 +23,12 @@ class OBFollowingPage extends StatefulWidget { } class OBFollowingPageState extends State { - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -82,7 +82,7 @@ class OBFollowingPageState extends State { Future> _refreshFollowing() async { UsersList following = await _userService.getFollowings(); - return following.users; + return following.users ?? []; } Future> _loadMoreFollowing(List followingList) async { @@ -93,12 +93,12 @@ class OBFollowingPageState extends State { count: 20, )) .users; - return moreFollowing; + return moreFollowing ?? []; } Future> _searchFollowing(String query) async { UsersList results = await _userService.searchFollowings(query: query); - return results.users; + return results.users ?? []; } } diff --git a/lib/pages/home/pages/menu/pages/follows_list/follows_list.dart b/lib/pages/home/pages/menu/pages/follows_list/follows_list.dart index ef999db8c..e012adb60 100644 --- a/lib/pages/home/pages/menu/pages/follows_list/follows_list.dart +++ b/lib/pages/home/pages/menu/pages/follows_list/follows_list.dart @@ -25,12 +25,12 @@ class OBFollowsListPage extends StatefulWidget { } class OBFollowsListPageState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; - GlobalKey _refreshIndicatorKey; - bool _needsBootstrap; + late GlobalKey _refreshIndicatorKey; + late bool _needsBootstrap; @override void initState() { @@ -87,7 +87,7 @@ class OBFollowsListPageState extends State { Future _refreshFollowsList() async { try { - await _userService.getFollowsListWithId(widget.followsList.id); + await _userService.getFollowsListWithId(widget.followsList.id!); } catch (error) { _onError(error); } @@ -98,8 +98,8 @@ class OBFollowsListPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_header/follows_list_header.dart b/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_header/follows_list_header.dart index 34b300873..cce6e75df 100644 --- a/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_header/follows_list_header.dart +++ b/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_header/follows_list_header.dart @@ -20,7 +20,7 @@ class OBFollowsListHeader extends StatelessWidget { stream: followsList.updateSubject, initialData: followsList, builder: (BuildContext context, AsyncSnapshot snapshot) { - var followsList = snapshot.data; + var followsList = snapshot.data!; return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -33,7 +33,7 @@ class OBFollowsListHeader extends StatelessWidget { Flexible( child: OBFollowsListName(followsList), ), - OBEmoji(followsList.emoji, size: OBEmojiSize.large,), + OBEmoji(followsList.emoji!, size: OBEmojiSize.large,), ], ), ), diff --git a/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_header/widgets/follows_list_name.dart b/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_header/widgets/follows_list_name.dart index 04b21883a..83a1c9824 100644 --- a/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_header/widgets/follows_list_name.dart +++ b/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_header/widgets/follows_list_name.dart @@ -15,7 +15,7 @@ class OBFollowsListName extends StatelessWidget { stream: followsList.updateSubject, initialData: followsList, builder: (BuildContext context, AsyncSnapshot snapshot) { - var followsList = snapshot.data; + var followsList = snapshot.data!; return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -28,7 +28,7 @@ class OBFollowsListName extends StatelessWidget { children: [ Flexible( child: OBPrimaryAccentText( - followsList.name, + followsList.name!, size: OBTextSize.extraLarge, overflow: TextOverflow.ellipsis, maxLines: 2, diff --git a/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_users.dart b/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_users.dart index 07bf4d24d..de8d573ab 100644 --- a/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_users.dart +++ b/lib/pages/home/pages/menu/pages/follows_list/widgets/follows_list_users.dart @@ -17,7 +17,7 @@ class OBFollowsListUsers extends StatelessWidget { initialData: followsList, builder: (BuildContext context, AsyncSnapshot snapshot) { var followsList = snapshot.data; - List users = followsList.users?.users ?? []; + List users = followsList?.users?.users ?? []; return ListView.builder( padding: EdgeInsets.all(0), diff --git a/lib/pages/home/pages/menu/pages/follows_lists/follows_lists.dart b/lib/pages/home/pages/menu/pages/follows_lists/follows_lists.dart index 2c565ddc8..adc7f0560 100644 --- a/lib/pages/home/pages/menu/pages/follows_lists/follows_lists.dart +++ b/lib/pages/home/pages/menu/pages/follows_lists/follows_lists.dart @@ -24,19 +24,19 @@ class OBFollowsListsPage extends StatefulWidget { } class OBFollowsListsPageState extends State { - UserService _userService; - ToastService _toastService; - ModalService _modalService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ModalService _modalService; + late LocalizationService _localizationService; - GlobalKey _refreshIndicatorKey; - ScrollController _followsListsScrollController; + late GlobalKey _refreshIndicatorKey; + late ScrollController _followsListsScrollController; List _followsLists = []; List _followsListsSearchResults = []; - String _searchQuery; + String? _searchQuery; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -94,7 +94,7 @@ class OBFollowsListsPageState extends State { if(_searchQuery != null){ return ListTile( leading: OBIcon(OBIcons.sad), - title: OBText(_localizationService.user__follow_lists_no_list_found_for(_searchQuery))); + title: OBText(_localizationService.user__follow_lists_no_list_found_for(_searchQuery ?? ''))); }else{ return ListTile( leading: OBIcon(OBIcons.sad), @@ -132,7 +132,7 @@ class OBFollowsListsPageState extends State { Future _refreshComments() async { try { - _followsLists = (await _userService.getFollowsLists()).lists; + _followsLists = (await _userService.getFollowsLists()).lists!; _setFollowsLists(_followsLists); _scrollToTop(); } catch (error) { @@ -145,8 +145,8 @@ class OBFollowsListsPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -154,7 +154,7 @@ class OBFollowsListsPageState extends State { } void _onWantsToCreateList() async { - FollowsList createdFollowsList = + FollowsList? createdFollowsList = await _modalService.openCreateFollowsList(context: context); if (createdFollowsList != null) { _onFollowsListCreated(createdFollowsList); @@ -171,7 +171,7 @@ class OBFollowsListsPageState extends State { _setSearchQuery(query); String uppercaseQuery = query.toUpperCase(); var searchResults = _followsLists.where((followsList) { - return followsList.name.toUpperCase().contains(uppercaseQuery); + return followsList.name!.toUpperCase().contains(uppercaseQuery); }).toList(); _setFollowsListsSearchResults(searchResults); @@ -216,7 +216,7 @@ class OBFollowsListsPageState extends State { }); } - void _setSearchQuery(String searchQuery) { + void _setSearchQuery(String? searchQuery) { setState(() { _searchQuery = searchQuery; }); diff --git a/lib/pages/home/pages/menu/pages/follows_lists/widgets/follows_list_tile.dart b/lib/pages/home/pages/menu/pages/follows_lists/widgets/follows_list_tile.dart index 565b8b4dd..e1b746ee4 100644 --- a/lib/pages/home/pages/menu/pages/follows_lists/widgets/follows_list_tile.dart +++ b/lib/pages/home/pages/menu/pages/follows_lists/widgets/follows_list_tile.dart @@ -11,10 +11,10 @@ import 'package:flutter_slidable/flutter_slidable.dart'; class OBFollowsListTile extends StatefulWidget { final FollowsList followsList; - final VoidCallback onFollowsListDeletedCallback; + final VoidCallback? onFollowsListDeletedCallback; OBFollowsListTile( - {@required this.followsList, Key key, this.onFollowsListDeletedCallback}) + {required this.followsList, Key? key, this.onFollowsListDeletedCallback}) : super(key: key); @override @@ -24,9 +24,9 @@ class OBFollowsListTile extends StatefulWidget { } class OBFollowsListTileState extends State { - bool _requestInProgress; - UserService _userService; - ToastService _toastService; + late bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; @override void initState() { @@ -49,9 +49,9 @@ class OBFollowsListTileState extends State { navigationService.navigateToFollowsList( followsList: widget.followsList, context: context); }, - leading: OBEmoji(widget.followsList.emoji), + leading: OBEmoji(widget.followsList.emoji!), title: OBText( - widget.followsList.name, + widget.followsList.name!, style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: OBSecondaryText( @@ -78,7 +78,7 @@ class OBFollowsListTileState extends State { // widget.post.decreaseCommentsCount(); _setRequestInProgress(false); if (widget.onFollowsListDeletedCallback != null) { - widget.onFollowsListDeletedCallback(); + widget.onFollowsListDeletedCallback!(); } } catch (error) { _onError(error); @@ -92,8 +92,8 @@ class OBFollowsListTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/home/pages/menu/pages/my_moderation_penalties/my_moderation_penalties.dart b/lib/pages/home/pages/menu/pages/my_moderation_penalties/my_moderation_penalties.dart index cb264e32b..e81fdb6cd 100644 --- a/lib/pages/home/pages/menu/pages/my_moderation_penalties/my_moderation_penalties.dart +++ b/lib/pages/home/pages/menu/pages/my_moderation_penalties/my_moderation_penalties.dart @@ -22,11 +22,11 @@ class OBMyModerationPenaltiesPage extends StatefulWidget { class OBMyModerationPenaltiesPageState extends State { - UserService _userService; - LocalizationService _localizationService; + late UserService _userService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -72,7 +72,7 @@ class OBMyModerationPenaltiesPageState Future> _refreshModerationPenalties() async { ModerationPenaltiesList moderationPenalties = await _userService.getModerationPenalties(); - return moderationPenalties.moderationPenalties; + return moderationPenalties.moderationPenalties ?? []; } Future> _loadMoreModerationPenalties( @@ -84,6 +84,6 @@ class OBMyModerationPenaltiesPageState count: 10, )) .moderationPenalties; - return moreModerationPenalties; + return moreModerationPenalties ?? []; } } diff --git a/lib/pages/home/pages/menu/pages/my_moderation_penalties/widgets/moderation_penalty/moderation_penalty.dart b/lib/pages/home/pages/menu/pages/my_moderation_penalties/widgets/moderation_penalty/moderation_penalty.dart index 309deee41..ae1a42188 100644 --- a/lib/pages/home/pages/menu/pages/my_moderation_penalties/widgets/moderation_penalty/moderation_penalty.dart +++ b/lib/pages/home/pages/menu/pages/my_moderation_penalties/widgets/moderation_penalty/moderation_penalty.dart @@ -10,7 +10,7 @@ import 'package:flutter/material.dart'; class OBModerationPenaltyTile extends StatelessWidget { final ModerationPenalty moderationPenalty; - const OBModerationPenaltyTile({Key key, @required this.moderationPenalty}) + const OBModerationPenaltyTile({Key? key, required this.moderationPenalty}) : super(key: key); @override @@ -22,13 +22,13 @@ class OBModerationPenaltyTile extends StatelessWidget { title: 'Object', ), OBModeratedObjectPreview( - moderatedObject: moderationPenalty.moderatedObject, + moderatedObject: moderationPenalty.moderatedObject!, ), const SizedBox( height: 10, ), OBModeratedObjectCategory( - moderatedObject: moderationPenalty.moderatedObject, + moderatedObject: moderationPenalty.moderatedObject!, isEditable: false, ), Row( @@ -42,7 +42,7 @@ class OBModerationPenaltyTile extends StatelessWidget { title: 'Status', ), OBModeratedObjectStatusTile( - moderatedObject: moderationPenalty.moderatedObject, + moderatedObject: moderationPenalty.moderatedObject!, ), ], ), @@ -57,7 +57,7 @@ class OBModerationPenaltyTile extends StatelessWidget { ListTile( title: OBText(ModerationPenalty .convertModerationPenaltyTypeToHumanReadableString( - moderationPenalty.type, + moderationPenalty.type!, capitalize: true)), ) ], diff --git a/lib/pages/home/pages/menu/pages/my_moderation_penalties/widgets/moderation_penalty/widgets/moderation_penalty_actions.dart b/lib/pages/home/pages/menu/pages/my_moderation_penalties/widgets/moderation_penalty/widgets/moderation_penalty_actions.dart index 8d89463d7..013b67b56 100644 --- a/lib/pages/home/pages/menu/pages/my_moderation_penalties/widgets/moderation_penalty/widgets/moderation_penalty_actions.dart +++ b/lib/pages/home/pages/menu/pages/my_moderation_penalties/widgets/moderation_penalty/widgets/moderation_penalty_actions.dart @@ -11,7 +11,7 @@ import 'package:flutter/material.dart'; class OBModerationPenaltyActions extends StatelessWidget { final ModerationPenalty moderationPenalty; - OBModerationPenaltyActions({@required this.moderationPenalty}); + OBModerationPenaltyActions({required this.moderationPenalty}); @override Widget build(BuildContext context) { diff --git a/lib/pages/home/pages/menu/pages/my_moderation_tasks/my_moderation_tasks.dart b/lib/pages/home/pages/menu/pages/my_moderation_tasks/my_moderation_tasks.dart index 16d397720..9c87ae5b9 100644 --- a/lib/pages/home/pages/menu/pages/my_moderation_tasks/my_moderation_tasks.dart +++ b/lib/pages/home/pages/menu/pages/my_moderation_tasks/my_moderation_tasks.dart @@ -23,12 +23,12 @@ class OBMyModerationTasksPage extends StatefulWidget { } class OBMyModerationTasksPageState extends State { - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -95,7 +95,7 @@ class OBMyModerationTasksPageState extends State { Future> _refreshPendingModeratedObjectsCommunities() async { CommunitiesList pendingModeratedObjectsCommunities = await _userService.getPendingModeratedObjectsCommunities(); - return pendingModeratedObjectsCommunities.communities; + return pendingModeratedObjectsCommunities.communities ?? []; } Future> _loadMorePendingModeratedObjectsCommunities( @@ -110,6 +110,6 @@ class OBMyModerationTasksPageState extends State { count: 10, )) .communities; - return morePendingModeratedObjectsCommunities; + return morePendingModeratedObjectsCommunities ?? []; } } diff --git a/lib/pages/home/pages/menu/pages/privacy_policy.dart b/lib/pages/home/pages/menu/pages/privacy_policy.dart index 88bf22602..74b98cc9d 100644 --- a/lib/pages/home/pages/menu/pages/privacy_policy.dart +++ b/lib/pages/home/pages/menu/pages/privacy_policy.dart @@ -16,10 +16,10 @@ class OBPrivacyPolicyPage extends StatefulWidget { } class OBPrivacyPolicyPageState extends State { - String _guidelinesText; - bool _needsBootstrap; + late String _guidelinesText; + late bool _needsBootstrap; - CancelableOperation _getGuidelinesOperation; + CancelableOperation? _getGuidelinesOperation; @override void initState() { @@ -31,7 +31,7 @@ class OBPrivacyPolicyPageState extends State { @override void dispose() { super.dispose(); - if (_getGuidelinesOperation != null) _getGuidelinesOperation.cancel(); + if (_getGuidelinesOperation != null) _getGuidelinesOperation!.cancel(); } void _bootstrap() async { @@ -39,7 +39,7 @@ class OBPrivacyPolicyPageState extends State { _getGuidelinesOperation = CancelableOperation.fromFuture( openbookProvider.documentsService.getPrivacyPolicy()); - String guidelines = await _getGuidelinesOperation.value; + String guidelines = await _getGuidelinesOperation?.value; _setGuidelinesText(guidelines); } diff --git a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/account_settings.dart b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/account_settings.dart index a0db2ad8d..e515524ba 100644 --- a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/account_settings.dart +++ b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/account_settings.dart @@ -15,7 +15,7 @@ class OBAccountSettingsPage extends StatelessWidget { var localizationService = openbookProvider.localizationService; var navigationService = openbookProvider.navigationService; var userService = openbookProvider.userService; - String currentUserLanguage = userService.getUserLanguage() != null ? userService.getUserLanguage().name : null; + String? currentUserLanguage = userService.getUserLanguage() != null ? userService.getUserLanguage()!.name : null; return CupertinoPageScaffold( backgroundColor: Color.fromARGB(0, 0, 0, 0), diff --git a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/modals/change-password/change_password.dart b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/modals/change-password/change_password.dart index 509351e95..133827b35 100644 --- a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/modals/change-password/change_password.dart +++ b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/modals/change-password/change_password.dart @@ -21,20 +21,20 @@ class OBChangePasswordModal extends StatefulWidget { } class OBChangePasswordModalState extends State { - ValidationService _validationService; - ToastService _toastService; - UserService _userService; - LocalizationService _localizationService; + late ValidationService _validationService; + late ToastService _toastService; + late UserService _userService; + late LocalizationService _localizationService; static const double INPUT_ICONS_SIZE = 16; static const EdgeInsetsGeometry INPUT_CONTENT_PADDING = EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0); final GlobalKey _formKey = GlobalKey(); bool _requestInProgress = false; bool _formWasSubmitted = false; - bool _isPasswordValid = true; + bool? _isPasswordValid = true; bool _formValid = true; - TextEditingController _currentPasswordController = TextEditingController(); - TextEditingController _newPasswordController = TextEditingController(); + late TextEditingController _currentPasswordController = TextEditingController(); + late TextEditingController _newPasswordController = TextEditingController(); @override void initState() { @@ -76,14 +76,14 @@ class OBChangePasswordModalState extends State { hintText: _localizationService .auth__change_password_current_pwd_hint, ), - validator: (String password) { + validator: (String? password) { if (!_formWasSubmitted) return null; - if (_isPasswordValid != null && !_isPasswordValid) { + if (_isPasswordValid != null && !_isPasswordValid!) { _setIsPasswordValid(true); return _localizationService .auth__change_password_current_pwd_incorrect; } - String validatePassword = + String? validatePassword = _validationService.validateUserPassword(password); if (validatePassword != null) return validatePassword; @@ -100,10 +100,10 @@ class OBChangePasswordModalState extends State { .auth__change_password_new_pwd, hintText: _localizationService .auth__change_password_new_pwd_hint), - validator: (String newPassword) { + validator: (String? newPassword) { if (!_formWasSubmitted) return null; if (!_validationService - .isPasswordAllowedLength(newPassword)) { + .isPasswordAllowedLength(newPassword ?? '')) { return _localizationService .auth__change_password_new_pwd_error; } @@ -115,7 +115,7 @@ class OBChangePasswordModalState extends State { )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( leading: GestureDetector( child: const OBIcon(OBIcons.close), @@ -135,7 +135,7 @@ class OBChangePasswordModalState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { @@ -175,8 +175,8 @@ class OBChangePasswordModalState extends State { _setIsPasswordValid(false); _validateForm(); } - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/modals/change_email/change_email.dart b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/modals/change_email/change_email.dart index 57338f503..09eb839a7 100644 --- a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/modals/change_email/change_email.dart +++ b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/modals/change_email/change_email.dart @@ -23,21 +23,21 @@ class OBChangeEmailModal extends StatefulWidget { } class OBChangeEmailModalState extends State { - ValidationService _validationService; - ToastService _toastService; - UserService _userService; - LocalizationService _localizationService; + late ValidationService _validationService; + late ToastService _toastService; + late UserService _userService; + late LocalizationService _localizationService; static const double INPUT_ICONS_SIZE = 16; static const EdgeInsetsGeometry INPUT_CONTENT_PADDING = EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0); final GlobalKey _formKey = GlobalKey(); bool _requestInProgress = false; bool _formWasSubmitted = false; - bool _changedEmailTaken = false; + bool? _changedEmailTaken = false; bool _formValid = true; TextEditingController _emailController = TextEditingController(); - TextEditingController _currentEmailController; - CancelableOperation _requestOperation; + late TextEditingController _currentEmailController; + CancelableOperation? _requestOperation; @override void initState() { @@ -52,7 +52,7 @@ class OBChangeEmailModalState extends State { @override void dispose() { super.dispose(); - if (_requestOperation != null) _requestOperation.cancel(); + if (_requestOperation != null) _requestOperation!.cancel(); } @override @@ -62,8 +62,8 @@ class OBChangeEmailModalState extends State { _toastService = openbookProvider.toastService; _userService = openbookProvider.userService; _localizationService = openbookProvider.localizationService; - - String currentUserEmail = _userService.getLoggedInUser().getEmail(); + + String currentUserEmail = _userService.getLoggedInUser()!.getEmail()!; _currentEmailController = TextEditingController(text: currentUserEmail); return OBCupertinoPageScaffold( @@ -93,12 +93,12 @@ class OBChangeEmailModalState extends State { labelText:_localizationService.user__change_email_email_text, hintText:_localizationService.user__change_email_hint_text, ), - validator: (String email) { + validator: (String? email) { if (!_formWasSubmitted) return null; - String validateEmail = + String? validateEmail = _validationService.validateUserEmail(email); if (validateEmail != null) return validateEmail; - if (_changedEmailTaken != null && _changedEmailTaken) { + if (_changedEmailTaken != null && _changedEmailTaken!) { return _localizationService.user__change_email_error; } }, @@ -109,7 +109,7 @@ class OBChangeEmailModalState extends State { )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( leading: GestureDetector( child: const OBIcon(OBIcons.close), @@ -129,7 +129,7 @@ class OBChangeEmailModalState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { @@ -148,7 +148,7 @@ class OBChangeEmailModalState extends State { var email = _emailController.text; _requestOperation = CancelableOperation.fromFuture(_userService.updateUserEmail(email)); - await _requestOperation.value; + await _requestOperation?.value; _toastService.success( message: _localizationService.user__change_email_success_info, @@ -167,8 +167,8 @@ class OBChangeEmailModalState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/blocked_users.dart b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/blocked_users.dart index 6f8d22724..7cdb0390b 100644 --- a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/blocked_users.dart +++ b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/blocked_users.dart @@ -23,12 +23,12 @@ class OBBlockedUsersPage extends StatefulWidget { } class OBBlockedUsersPageState extends State { - UserService _userService; - NavigationService _navigationService; - ToastService _toastService; + late UserService _userService; + late NavigationService _navigationService; + late ToastService _toastService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -93,8 +93,8 @@ class OBBlockedUsersPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; @@ -103,7 +103,7 @@ class OBBlockedUsersPageState extends State { Future> _refreshBlockedUsers() async { UsersList blockedUsers = await _userService.getBlockedUsers(); - return blockedUsers.users; + return blockedUsers.users ?? []; } Future> _loadMoreBlockedUsers(List blockedUsersList) async { @@ -114,13 +114,13 @@ class OBBlockedUsersPageState extends State { count: 10, )) .users; - return moreBlockedUsers; + return moreBlockedUsers ?? []; } Future> _searchBlockedUsers(String query) async { UsersList results = await _userService.searchBlockedUsers(query: query); - return results.users; + return results.users ?? []; } } diff --git a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/user_language_settings/user_language_settings.dart b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/user_language_settings/user_language_settings.dart index 078c35bb1..4a4c9685f 100644 --- a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/user_language_settings/user_language_settings.dart +++ b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/user_language_settings/user_language_settings.dart @@ -23,17 +23,17 @@ class OBUserLanguageSettingsPage extends StatefulWidget { class OBUserLanguageSettingsPageState extends State { - Language _selectedLanguage; - Locale _selectedLocale; - Language _currentUserLanguage; - List _allLanguages; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - - bool _needsBootstrap; - bool _bootstrapInProgress; - bool _requestInProgress; + Language? _selectedLanguage; + Locale? _selectedLocale; + Language? _currentUserLanguage; + late List _allLanguages; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + + late bool _needsBootstrap; + late bool _bootstrapInProgress; + late bool _requestInProgress; @override void initState() { @@ -95,7 +95,7 @@ class OBUserLanguageSettingsPageState shrinkWrap: true, itemBuilder: (BuildContext context, int index) { Language language = _allLanguages[index]; - bool isSelected = language.code == _selectedLanguage.code; + bool isSelected = language.code == _selectedLanguage?.code; return OBLanguageSelectableTile( language, @@ -110,10 +110,14 @@ class OBUserLanguageSettingsPageState } void _saveNewLanguage() async { + if (_selectedLanguage == null || _selectedLocale == null) { + return; + } + _setRequestInProgress(true); try { - await _userService.setNewLanguage(_selectedLanguage); - MyApp.setLocale(context, _selectedLocale); + await _userService.setNewLanguage(_selectedLanguage!); + MyApp.setLocale(context, _selectedLocale!); } catch (error) { _onError(error); } finally { @@ -128,8 +132,8 @@ class OBUserLanguageSettingsPageState } void _setLanguagesList(LanguagesList list) { - List supportedList = list.languages.where((Language language) => - supportedLanguages.contains(language.code)).toList(); + List supportedList = list.languages?.where((Language language) => + supportedLanguages.contains(language.code)).toList() ?? []; setState(() { _allLanguages = supportedList; }); @@ -165,7 +169,7 @@ class OBUserLanguageSettingsPageState void _bootstrap() async { Language userLanguage = _userService .getLoggedInUser() - .language; + !.language!; _setSelectedLanguageInWidget(userLanguage); _setCurrentUserLanguage(userLanguage); await _refreshLanguages(); @@ -186,8 +190,8 @@ class OBUserLanguageSettingsPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -201,4 +205,3 @@ class OBUserLanguageSettingsPageState }); } } - diff --git a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/user_language_settings/widgets/language_selectable_tile.dart b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/user_language_settings/widgets/language_selectable_tile.dart index 4b93aa955..d28941307 100644 --- a/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/user_language_settings/widgets/language_selectable_tile.dart +++ b/lib/pages/home/pages/menu/pages/settings/pages/account_settings/pages/user_language_settings/widgets/language_selectable_tile.dart @@ -4,22 +4,23 @@ import 'package:flutter/material.dart'; class OBLanguageSelectableTile extends StatelessWidget { final Language language; - final OnLanguagePressed onLanguagePressed; - final bool isSelected; + final OnLanguagePressed? onLanguagePressed; + final bool? isSelected; static double circleSize = 15; const OBLanguageSelectableTile(this.language, - {Key key, this.onLanguagePressed, this.isSelected}) + {Key? key, this.onLanguagePressed, this.isSelected}) : super(key: key); @override Widget build(BuildContext context) { - return OBCheckboxField( - value: isSelected, - title: language.name, + value: isSelected ?? false, + title: language.name!, onTap: () { - onLanguagePressed(language); + if (onLanguagePressed != null) { + onLanguagePressed!(language); + } }, ); } diff --git a/lib/pages/home/pages/menu/pages/terms_of_use.dart b/lib/pages/home/pages/menu/pages/terms_of_use.dart index 37437de28..3aacae255 100644 --- a/lib/pages/home/pages/menu/pages/terms_of_use.dart +++ b/lib/pages/home/pages/menu/pages/terms_of_use.dart @@ -16,10 +16,10 @@ class OBTermsOfUsePage extends StatefulWidget { } class OBTermsOfUsePageState extends State { - String _guidelinesText; - bool _needsBootstrap; + late String _guidelinesText; + late bool _needsBootstrap; - CancelableOperation _getGuidelinesOperation; + CancelableOperation? _getGuidelinesOperation; @override void initState() { @@ -31,7 +31,7 @@ class OBTermsOfUsePageState extends State { @override void dispose() { super.dispose(); - if (_getGuidelinesOperation != null) _getGuidelinesOperation.cancel(); + if (_getGuidelinesOperation != null) _getGuidelinesOperation!.cancel(); } void _bootstrap() async { @@ -39,7 +39,7 @@ class OBTermsOfUsePageState extends State { _getGuidelinesOperation = CancelableOperation.fromFuture( openbookProvider.documentsService.getTermsOfUse()); - String guidelines = await _getGuidelinesOperation.value; + String guidelines = await _getGuidelinesOperation?.value; _setGuidelinesText(guidelines); } diff --git a/lib/pages/home/pages/menu/pages/themes/widgets/curated_themes.dart b/lib/pages/home/pages/menu/pages/themes/widgets/curated_themes.dart index 9115a3475..d75ca4117 100644 --- a/lib/pages/home/pages/menu/pages/themes/widgets/curated_themes.dart +++ b/lib/pages/home/pages/menu/pages/themes/widgets/curated_themes.dart @@ -6,7 +6,7 @@ import 'package:Okuna/services/theme.dart'; import 'package:flutter/material.dart'; class OBCuratedThemes extends StatelessWidget { - ThemeService _themeService; + late ThemeService _themeService; @override Widget build(BuildContext context) { diff --git a/lib/pages/home/pages/menu/pages/themes/widgets/theme_preview.dart b/lib/pages/home/pages/menu/pages/themes/widgets/theme_preview.dart index 8eb15400f..50337440c 100644 --- a/lib/pages/home/pages/menu/pages/themes/widgets/theme_preview.dart +++ b/lib/pages/home/pages/menu/pages/themes/widgets/theme_preview.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; class OBThemePreview extends StatelessWidget { static const maxWidth = 120.0; final OBTheme theme; - final OnThemePreviewPressed onThemePreviewPressed; + final OnThemePreviewPressed? onThemePreviewPressed; OBThemePreview(this.theme, {this.onThemePreviewPressed}); @@ -29,7 +29,7 @@ class OBThemePreview extends StatelessWidget { return GestureDetector( onTap: () { if (this.onThemePreviewPressed != null) { - this.onThemePreviewPressed(theme); + this.onThemePreviewPressed!(theme); } }, child: ConstrainedBox( @@ -47,15 +47,17 @@ class OBThemePreview extends StatelessWidget { : Color.fromARGB(10, 0, 0, 0), width: 3), borderRadius: BorderRadius.circular(50)), - child: ClipRRect( - borderRadius: BorderRadius.circular(50.0), - child: Image.asset(theme.themePreview), - )), + child: theme.themePreview == null + ? SizedBox() + : ClipRRect( + borderRadius: BorderRadius.circular(50.0), + child: Image.asset(theme.themePreview!), + )), const SizedBox( height: 10, ), OBText( - theme.name, + theme.name ?? '', size: OBTextSize.small, maxLines: 3, textAlign: TextAlign.center, diff --git a/lib/pages/home/pages/menu/pages/user_invites/pages/user_invite_detail.dart b/lib/pages/home/pages/menu/pages/user_invites/pages/user_invite_detail.dart index 18035908e..09f6d6942 100644 --- a/lib/pages/home/pages/menu/pages/user_invites/pages/user_invite_detail.dart +++ b/lib/pages/home/pages/menu/pages/user_invites/pages/user_invite_detail.dart @@ -17,14 +17,14 @@ import 'package:Okuna/widgets/theming/text.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:Okuna/services/httpie.dart'; -import 'package:share/share.dart'; +import 'package:share_plus/share_plus.dart'; class OBUserInviteDetailPage extends StatefulWidget { final UserInvite userInvite; final bool showEdit; OBUserInviteDetailPage({ - @required this.userInvite, + required this.userInvite, this.showEdit = false }); @@ -35,12 +35,12 @@ class OBUserInviteDetailPage extends StatefulWidget { } class OBUserInviteDetailPageState extends State { - ToastService _toastService; - ModalService _modalService; - LocalizationService _localizationService; - UserInvitesApiService _userInvitesApiService; - StringTemplateService _stringTemplateService; - bool _needsBootstrap; + late ToastService _toastService; + late ModalService _modalService; + late LocalizationService _localizationService; + late UserInvitesApiService _userInvitesApiService; + late StringTemplateService _stringTemplateService; + late bool _needsBootstrap; @override void initState() { @@ -101,7 +101,7 @@ class OBUserInviteDetailPageState extends State { ), onTap: () { String apiURL = _userInvitesApiService.apiURL; - String token = widget.userInvite.token; + String token = widget.userInvite.token!; Share.share(getShareMessageForInviteWithToken(token, apiURL)); }, ), @@ -154,8 +154,8 @@ class OBUserInviteDetailPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/pages/menu/pages/user_invites/user_invites.dart b/lib/pages/home/pages/menu/pages/user_invites/user_invites.dart index 9fed5e506..ba03010f9 100644 --- a/lib/pages/home/pages/menu/pages/user_invites/user_invites.dart +++ b/lib/pages/home/pages/menu/pages/user_invites/user_invites.dart @@ -27,24 +27,24 @@ class OBUserInvitesPage extends StatefulWidget { } class OBUserInvitesPageState extends State { - UserService _userService; - ToastService _toastService; - ModalService _modalService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ModalService _modalService; + late LocalizationService _localizationService; - User _user; - GlobalKey _refreshIndicatorKey; - ScrollController _userInvitesScrollController; - OBMyInvitesGroupController _acceptedInvitesGroupController; - OBMyInvitesGroupController _pendingInvitesGroupController; + late User _user; + late GlobalKey _refreshIndicatorKey; + late ScrollController _userInvitesScrollController; + late OBMyInvitesGroupController _acceptedInvitesGroupController; + late OBMyInvitesGroupController _pendingInvitesGroupController; - bool _hasAcceptedInvites; - bool _hasPendingInvites; - bool _refreshInProgress; + late bool _hasAcceptedInvites; + late bool _hasPendingInvites; + late bool _refreshInProgress; - CancelableOperation _refreshUserOperation; + CancelableOperation? _refreshUserOperation; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -62,7 +62,7 @@ class OBUserInvitesPageState extends State { @override void dispose() { super.dispose(); - if (_refreshUserOperation != null) _refreshUserOperation.cancel(); + if (_refreshUserOperation != null) _refreshUserOperation!.cancel(); } @override @@ -73,7 +73,7 @@ class OBUserInvitesPageState extends State { _toastService = provider.toastService; _modalService = provider.modalService; _localizationService = provider.localizationService; - _user = _userService.getLoggedInUser(); + _user = _userService.getLoggedInUser()!; _bootstrap(); _needsBootstrap = false; } @@ -167,7 +167,7 @@ class OBUserInvitesPageState extends State { } Widget _buildNoInvitesFallback() { - bool hasInvites = _user.inviteCount > 0; + bool hasInvites = _user.inviteCount != null && _user.inviteCount! > 0; String message = hasInvites ? _localizationService.user__invites_none_used @@ -177,7 +177,7 @@ class OBUserInvitesPageState extends State { ? 'assets/images/stickers/perplexed-owl.png' : 'assets/images/stickers/owl-instructor.png'; - Function _onPressed = hasInvites + VoidCallback _onPressed = hasInvites ? _onWantsToCreateInvite : _refreshInvites; @@ -195,10 +195,12 @@ class OBUserInvitesPageState extends State { ); } - Widget _onUserInviteDeletedCallback( + Widget? _onUserInviteDeletedCallback( BuildContext context, UserInvite userInvite) { setState(() { - if (userInvite.createdUser == null) _user.inviteCount += 1; + if (userInvite.createdUser == null) { + _user.inviteCount = _user.inviteCount! + 1; + } }); } @@ -223,11 +225,11 @@ class OBUserInvitesPageState extends State { } Future _refreshUser() async { - if (_refreshUserOperation != null) _refreshUserOperation.cancel(); + if (_refreshUserOperation != null) _refreshUserOperation!.cancel(); _refreshUserOperation = CancelableOperation.fromFuture(_userService.refreshUser()); - await _refreshUserOperation.value; - User refreshedUser = _userService.getLoggedInUser(); + await _refreshUserOperation!.value; + User refreshedUser = _userService.getLoggedInUser()!; setState(() { _user = refreshedUser; }); @@ -236,15 +238,15 @@ class OBUserInvitesPageState extends State { Future> _refreshPendingInvites() async { UserInvitesList pendingInvitesList = await _userService.getUserInvites( status: UserInviteFilterByStatus.pending); - _setHasPendingInvites(pendingInvitesList.invites.isNotEmpty); - return pendingInvitesList.invites; + _setHasPendingInvites(pendingInvitesList.invites?.isNotEmpty ?? false); + return pendingInvitesList.invites ?? []; } Future> _refreshAcceptedInvites() async { UserInvitesList acceptedInvitesList = await _userService.getUserInvites( status: UserInviteFilterByStatus.accepted); - _setHasAcceptedInvites(acceptedInvitesList.invites.isNotEmpty); - return acceptedInvitesList.invites; + _setHasAcceptedInvites(acceptedInvitesList.invites?.isNotEmpty ?? false); + return acceptedInvitesList.invites ?? []; } Future> _loadMorePendingInvites( @@ -253,7 +255,7 @@ class OBUserInvitesPageState extends State { UserInvitesList morePendingInvites = await _userService.getUserInvites( offset: offset, status: UserInviteFilterByStatus.pending); - return morePendingInvites.invites; + return morePendingInvites.invites ?? []; } Future> _loadMoreAcceptedInvites( @@ -262,19 +264,19 @@ class OBUserInvitesPageState extends State { UserInvitesList moreAcceptedInvites = await _userService.getUserInvites( offset: offset, status: UserInviteFilterByStatus.accepted); - return moreAcceptedInvites.invites; + return moreAcceptedInvites.invites ?? []; } Future> _searchPendingUserInvites(String query) async { UserInvitesList results = await _userService.searchUserInvites( query: query, status: UserInviteFilterByStatus.pending); - return results.invites; + return results.invites ?? []; } Future> _searchAcceptedUserInvites(String query) async { UserInvitesList results = await _userService.searchUserInvites( query: query, status: UserInviteFilterByStatus.accepted); - return results.invites; + return results.invites ?? []; } void _onError(error) async { @@ -282,8 +284,8 @@ class OBUserInvitesPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -295,7 +297,7 @@ class OBUserInvitesPageState extends State { _showNoInvitesLeft(); return; } - UserInvite createdUserInvite = + UserInvite? createdUserInvite = await _modalService.openCreateUserInvite(context: context); if (createdUserInvite != null) { _onUserInviteCreated(createdUserInvite); diff --git a/lib/pages/home/pages/menu/pages/user_invites/widgets/my_invite_group.dart b/lib/pages/home/pages/menu/pages/user_invites/widgets/my_invite_group.dart index a75a09536..1e446987d 100644 --- a/lib/pages/home/pages/menu/pages/user_invites/widgets/my_invite_group.dart +++ b/lib/pages/home/pages/menu/pages/user_invites/widgets/my_invite_group.dart @@ -19,23 +19,23 @@ class OBMyInvitesGroup extends StatefulWidget { final OBHttpListSearcher inviteListSearcher; final void Function(BuildContext, UserInvite) inviteGroupListItemDeleteCallback; final OBHttpListOnScrollLoader inviteGroupListOnScrollLoader; - final OBMyInvitesGroupFallbackBuilder noGroupItemsFallbackBuilder; - final OBMyInvitesGroupController controller; + final OBMyInvitesGroupFallbackBuilder? noGroupItemsFallbackBuilder; + final OBMyInvitesGroupController? controller; final String groupItemName; final String groupName; final int maxGroupListPreviewItems; final String title; const OBMyInvitesGroup({ - Key key, - @required this.inviteGroupListRefresher, - @required this.inviteGroupListOnScrollLoader, - @required this.groupItemName, - @required this.inviteListSearcher, - @required this.groupName, - @required this.title, - @required this.maxGroupListPreviewItems, - @required this.inviteGroupListItemDeleteCallback, + Key? key, + required this.inviteGroupListRefresher, + required this.inviteGroupListOnScrollLoader, + required this.groupItemName, + required this.inviteListSearcher, + required this.groupName, + required this.title, + required this.maxGroupListPreviewItems, + required this.inviteGroupListItemDeleteCallback, this.noGroupItemsFallbackBuilder, this.controller, }) : super(key: key); @@ -47,18 +47,18 @@ class OBMyInvitesGroup extends StatefulWidget { } class OBMyInvitesGroupState extends State { - bool _needsBootstrap; - ToastService _toastService; - NavigationService _navigationService; - LocalizationService _localizationService; - List _inviteGroupList; - bool _refreshInProgress; - CancelableOperation _refreshOperation; + late bool _needsBootstrap; + late ToastService _toastService; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late List _inviteGroupList; + late bool _refreshInProgress; + CancelableOperation? _refreshOperation; @override void initState() { super.initState(); - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); _needsBootstrap = true; _inviteGroupList = []; _refreshInProgress = false; @@ -82,7 +82,7 @@ class OBMyInvitesGroupState extends State { if (listItemCount == 0) { if (widget.noGroupItemsFallbackBuilder != null && !_refreshInProgress) { - return widget.noGroupItemsFallbackBuilder( + return widget.noGroupItemsFallbackBuilder!( context, _refreshInvites); } return const SizedBox(); @@ -120,8 +120,8 @@ class OBMyInvitesGroupState extends State { @override void dispose() { super.dispose(); - if (widget.controller != null) widget.controller.detach(); - if (_refreshOperation != null) _refreshOperation.cancel(); + if (widget.controller != null) widget.controller!.detach(); + if (_refreshOperation != null) _refreshOperation!.cancel(); } Widget _buildSeeAllButton() { @@ -178,13 +178,13 @@ class OBMyInvitesGroupState extends State { } Future _refreshInvites() async { - if (_refreshOperation != null) _refreshOperation.cancel(); + if (_refreshOperation != null) _refreshOperation!.cancel(); _setRefreshInProgress(true); try { _refreshOperation = CancelableOperation.fromFuture(widget.inviteGroupListRefresher()); - List groupInvites = await _refreshOperation.value; + List groupInvites = await _refreshOperation!.value; _setUserInviteGroupList(groupInvites); } catch (error) { @@ -200,8 +200,8 @@ class OBMyInvitesGroupState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; @@ -249,7 +249,7 @@ class OBMyInvitesGroupState extends State { } class OBMyInvitesGroupController { - OBMyInvitesGroupState _state; + OBMyInvitesGroupState? _state; void attach(OBMyInvitesGroupState state) { this._state = state; @@ -261,7 +261,7 @@ class OBMyInvitesGroupController { Future refresh() { if (_state == null) return Future.value(); - return _state._refreshInvites(); + return _state!._refreshInvites(); } } diff --git a/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_count.dart b/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_count.dart index a347ef698..b618b77a9 100644 --- a/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_count.dart +++ b/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_count.dart @@ -4,10 +4,10 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBUserInviteCount extends StatelessWidget { - final int count; - final double size; + final int? count; + final double? size; - const OBUserInviteCount({Key key, this.count, this.size=19}) : super(key: key); + const OBUserInviteCount({Key? key, this.count, this.size=19}) : super(key: key); @override Widget build(BuildContext context) { @@ -20,7 +20,7 @@ class OBUserInviteCount extends StatelessWidget { stream: themeService.themeChange, initialData: themeService.getActiveTheme(), builder: (BuildContext context, AsyncSnapshot snapshot) { - var theme = snapshot.data; + var theme = snapshot.data!; var primaryAccentColor = themeValueParserService.parseGradient(theme.primaryAccentColor); return GestureDetector( @@ -42,7 +42,7 @@ class OBUserInviteCount extends StatelessWidget { count.toString(), style: TextStyle( color: Colors.white, - fontSize: count < 10 ? 12 : 10, + fontSize: count! < 10 ? 12 : 10, fontWeight: FontWeight.bold), ) : const SizedBox() ), diff --git a/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_detail_header.dart b/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_detail_header.dart index de36c2d7f..f45651b63 100644 --- a/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_detail_header.dart +++ b/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_detail_header.dart @@ -20,7 +20,7 @@ class OBUserInviteDetailHeader extends StatelessWidget { stream: this.userInvite.updateSubject, initialData: this.userInvite, builder: (BuildContext context, AsyncSnapshot snapshot) { - var userInvite = snapshot.data; + var userInvite = snapshot.data!; List columnItems = [_buildUserInviteNickname(userInvite)]; @@ -51,9 +51,9 @@ class OBUserInviteDetailHeader extends StatelessWidget { Widget _buildUserDescription(UserInvite userInvite, LocalizationService localizationService) { Widget _description; if (userInvite.createdUser != null) { - _description = OBActionableSmartText(text:localizationService.user__invites_joined_with(userInvite.createdUser.username)); - } else if (userInvite.isInviteEmailSent) { - _description = OBText(localizationService.user__invites_pending_email(userInvite.email)); + _description = OBActionableSmartText(text:localizationService.user__invites_joined_with(userInvite.createdUser!.username!)); + } else if (userInvite.isInviteEmailSent == true) { + _description = OBText(localizationService.user__invites_pending_email(userInvite.email!)); } else { _description = OBText(localizationService.user__invites_pending); } diff --git a/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_nickname.dart b/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_nickname.dart index a3b45c33e..7771d0a53 100644 --- a/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_nickname.dart +++ b/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_nickname.dart @@ -15,7 +15,7 @@ class OBUserInviteNickname extends StatelessWidget { stream: userInvite.updateSubject, initialData: userInvite, builder: (BuildContext context, AsyncSnapshot snapshot) { - var userInvite = snapshot.data; + var userInvite = snapshot.data!; return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -28,7 +28,7 @@ class OBUserInviteNickname extends StatelessWidget { children: [ Flexible( child: OBPrimaryAccentText( - userInvite.nickname, + userInvite.nickname!, size: OBTextSize.extraLarge, overflow: TextOverflow.ellipsis, maxLines: 2, diff --git a/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_tile.dart b/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_tile.dart index b759d7029..886488aae 100644 --- a/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_tile.dart +++ b/lib/pages/home/pages/menu/pages/user_invites/widgets/user_invite_tile.dart @@ -14,10 +14,10 @@ import 'package:flutter_slidable/flutter_slidable.dart'; class OBUserInviteTile extends StatefulWidget { final UserInvite userInvite; - final VoidCallback onUserInviteDeletedCallback; + final VoidCallback? onUserInviteDeletedCallback; OBUserInviteTile( - {@required this.userInvite, Key key, this.onUserInviteDeletedCallback}) + {required this.userInvite, Key? key, this.onUserInviteDeletedCallback}) : super(key: key); @override @@ -27,12 +27,12 @@ class OBUserInviteTile extends StatefulWidget { } class OBUserInviteTileState extends State { - bool _requestInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; - CancelableOperation _deleteOperation; + CancelableOperation? _deleteOperation; @override void initState() { @@ -43,7 +43,7 @@ class OBUserInviteTileState extends State { @override void dispose() { super.dispose(); - if (_deleteOperation != null) _deleteOperation.cancel(); + if (_deleteOperation != null) _deleteOperation!.cancel(); } @override @@ -59,11 +59,11 @@ class OBUserInviteTileState extends State { tile = ListTile( onTap: () { navigationService.navigateToUserProfile( - user: widget.userInvite.createdUser, context: context); + user: widget.userInvite.createdUser!, context: context); }, leading: const OBIcon(OBIcons.invite), title: OBText( - widget.userInvite.nickname, + widget.userInvite.nickname!, style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: _buildActionableSecondaryText()); @@ -78,7 +78,7 @@ class OBUserInviteTileState extends State { }, leading: const OBIcon(OBIcons.invite), title: OBText( - widget.userInvite.nickname, + widget.userInvite.nickname!, style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: _buildActionableSecondaryText()), @@ -103,7 +103,7 @@ class OBUserInviteTileState extends State { return OBActionableSmartText( size: OBTextSize.mediumSecondary, text: _localizationService - .user__invites_joined_with(widget.userInvite.createdUser.username), + .user__invites_joined_with(widget.userInvite.createdUser!.username!), ); } else { return OBSecondaryText(_localizationService.user__invites_pending); @@ -115,10 +115,10 @@ class OBUserInviteTileState extends State { try { _deleteOperation = CancelableOperation.fromFuture( _userService.deleteUserInvite(widget.userInvite)); - await _deleteOperation.value; + await _deleteOperation!.value; _setRequestInProgress(false); if (widget.onUserInviteDeletedCallback != null) { - widget.onUserInviteDeletedCallback(); + widget.onUserInviteDeletedCallback!(); } } catch (error) { _onError(error); @@ -133,8 +133,8 @@ class OBUserInviteTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/pages/moderated_objects/modals/moderated_objects_filters/moderated_objects_filters.dart b/lib/pages/home/pages/moderated_objects/modals/moderated_objects_filters/moderated_objects_filters.dart index 64feb3c80..7a0b7692b 100644 --- a/lib/pages/home/pages/moderated_objects/modals/moderated_objects_filters/moderated_objects_filters.dart +++ b/lib/pages/home/pages/moderated_objects/modals/moderated_objects_filters/moderated_objects_filters.dart @@ -17,7 +17,7 @@ class OBModeratedObjectsFiltersModal extends StatefulWidget { final OBModeratedObjectsPageController moderatedObjectsPageController; const OBModeratedObjectsFiltersModal( - {Key key, @required this.moderatedObjectsPageController}) + {Key? key, required this.moderatedObjectsPageController}) : super(key: key); @override @@ -28,18 +28,18 @@ class OBModeratedObjectsFiltersModal extends StatefulWidget { class OBModeratedObjectsFiltersModalState extends State { - bool _requestInProgress; - LocalizationService _localizationService; + late bool _requestInProgress; + late LocalizationService _localizationService; - List _types; - List _selectedTypes; + late List _types; + late List _selectedTypes; List _statuses = [ ModeratedObjectStatus.approved, ModeratedObjectStatus.rejected, ModeratedObjectStatus.pending, ]; - List _selectedStatuses; - bool _onlyVerified; + late List _selectedStatuses; + late bool _onlyVerified; @override void initState() { @@ -47,7 +47,7 @@ class OBModeratedObjectsFiltersModalState _requestInProgress = false; OBModeratedObjectsFilters currentFilters = - widget.moderatedObjectsPageController.getFilters(); + widget.moderatedObjectsPageController.getFilters()!; if (widget.moderatedObjectsPageController.hasCommunity()) { _types = [ @@ -155,7 +155,7 @@ class OBModeratedObjectsFiltersModalState Widget _buildTypeListTile(BuildContext context, int index) { ModeratedObjectType type = _types[index]; String typeString = ModeratedObject.factory - .convertTypeToHumanReadableString(type, capitalize: true); + .convertTypeToHumanReadableString(type, capitalize: true) ?? ''; return OBCheckboxField( titleStyle: TextStyle(fontWeight: FontWeight.normal), onTap: () { @@ -169,7 +169,7 @@ class OBModeratedObjectsFiltersModalState Widget _buildStatusListTile(BuildContext context, int index) { ModeratedObjectStatus status = _statuses[index]; String statusString = ModeratedObject.factory - .convertStatusToHumanReadableString(status, capitalize: true); + .convertStatusToHumanReadableString(status, capitalize: true) ?? ''; return Row( mainAxisSize: MainAxisSize.max, children: [ @@ -216,7 +216,7 @@ class OBModeratedObjectsFiltersModalState ); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( leading: GestureDetector( child: const OBIcon(OBIcons.close), diff --git a/lib/pages/home/pages/moderated_objects/moderated_objects.dart b/lib/pages/home/pages/moderated_objects/moderated_objects.dart index 86b006bb9..fa31b7e5a 100644 --- a/lib/pages/home/pages/moderated_objects/moderated_objects.dart +++ b/lib/pages/home/pages/moderated_objects/moderated_objects.dart @@ -21,9 +21,9 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBModeratedObjectsPage extends StatefulWidget { - final Community community; + final Community? community; - const OBModeratedObjectsPage({Key key, this.community}) : super(key: key); + const OBModeratedObjectsPage({Key? key, this.community}) : super(key: key); @override OBModeratedObjectsPageState createState() { @@ -34,26 +34,26 @@ class OBModeratedObjectsPage extends StatefulWidget { class OBModeratedObjectsPageState extends State { static int itemsLoadMoreCount = 10; - OBModeratedObjectsPageController _controller; + late OBModeratedObjectsPageController _controller; - Community _community; - OBModeratedObjectsFilters _filters; - ScrollController _scrollController; + Community? _community; + late OBModeratedObjectsFilters _filters; + late ScrollController _scrollController; final GlobalKey _refreshIndicatorKey = GlobalKey(); - List _moderatedObjects; + late List _moderatedObjects; - UserService _userService; - ToastService _toastService; - ModalService _modalService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ModalService _modalService; + late LocalizationService _localizationService; - CancelableOperation _loadMoreOperation; - CancelableOperation _refreshModeratedObjectsOperation; + CancelableOperation? _loadMoreOperation; + CancelableOperation? _refreshModeratedObjectsOperation; - bool _needsBootstrap; - bool _moreModeratedObjectsToLoad; - bool _refreshModeratedObjectsInProgress; + late bool _needsBootstrap; + late bool _moreModeratedObjectsToLoad; + late bool _refreshModeratedObjectsInProgress; @override void initState() { @@ -72,9 +72,9 @@ class OBModeratedObjectsPageState extends State { @override void dispose() { super.dispose(); - if (_loadMoreOperation != null) _loadMoreOperation.cancel(); + if (_loadMoreOperation != null) _loadMoreOperation!.cancel(); if (_refreshModeratedObjectsOperation != null) - _refreshModeratedObjectsOperation.cancel(); + _refreshModeratedObjectsOperation!.cancel(); } @override @@ -179,7 +179,7 @@ class OBModeratedObjectsPageState extends State { }); } - Future setFilters(OBModeratedObjectsFilters filters) { + Future? setFilters(OBModeratedObjectsFilters filters) { _filters = filters; _refresh(); } @@ -199,7 +199,7 @@ class OBModeratedObjectsPageState extends State { } Future _refresh() async { - _refreshIndicatorKey.currentState.show(); + _refreshIndicatorKey.currentState?.show(); } Future _refreshModeratedObjects() async { @@ -215,7 +215,7 @@ class OBModeratedObjectsPageState extends State { } else { _refreshModeratedObjectsOperation = CancelableOperation.fromFuture( _userService.getCommunityModeratedObjects( - community: widget.community, + community: widget.community!, count: itemsLoadMoreCount, verified: _filters.onlyVerified, statuses: _filters.statuses, @@ -223,8 +223,8 @@ class OBModeratedObjectsPageState extends State { } ModeratedObjectsList moderatedObjectList = - await _refreshModeratedObjectsOperation.value; - _setModeratedObjects(moderatedObjectList.moderatedObjects); + await _refreshModeratedObjectsOperation?.value; + _setModeratedObjects(moderatedObjectList.moderatedObjects ?? []); } catch (error) { _onError(error); } finally { @@ -233,7 +233,7 @@ class OBModeratedObjectsPageState extends State { } Future _loadMoreModeratedObjects() async { - if (_loadMoreOperation != null) _loadMoreOperation.cancel(); + if (_loadMoreOperation != null) _loadMoreOperation!.cancel(); var lastModeratedObjectId; if (_moderatedObjects.isNotEmpty) { @@ -253,7 +253,7 @@ class OBModeratedObjectsPageState extends State { } else { _loadMoreOperation = CancelableOperation.fromFuture( _userService.getCommunityModeratedObjects( - community: _community, + community: _community!, maxId: lastModeratedObjectId, count: itemsLoadMoreCount, verified: _filters.onlyVerified, @@ -262,7 +262,7 @@ class OBModeratedObjectsPageState extends State { } var moreModeratedObjects = - (await _loadMoreOperation.value).moderatedObjects; + (await _loadMoreOperation?.value).moderatedObjects; if (moreModeratedObjects.length == 0) { _setMoreModeratedObjectsToLoad(false); @@ -313,8 +313,8 @@ class OBModeratedObjectsPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -328,7 +328,7 @@ class OBModeratedObjectsFilters { final List statuses; final bool onlyVerified; - static OBModeratedObjectsFilters makeDefault({@required isGlobalModeration}) { + static OBModeratedObjectsFilters makeDefault({required isGlobalModeration}) { List filterTypes = [ ModeratedObjectType.postComment, ModeratedObjectType.post, @@ -352,9 +352,9 @@ class OBModeratedObjectsFilters { } OBModeratedObjectsFilters( - {@required this.types, - @required this.statuses, - @required this.onlyVerified}); + {required this.types, + required this.statuses, + required this.onlyVerified}); OBModeratedObjectsFilters clone() { return OBModeratedObjectsFilters( @@ -369,33 +369,33 @@ class OBModeratedObjectsFilters { } class OBModeratedObjectsPageController { - OBModeratedObjectsPageState state; + OBModeratedObjectsPageState? state; OBModeratedObjectsPageController({this.state}); - void attach({OBModeratedObjectsPageState state}) { + void attach({OBModeratedObjectsPageState? state}) { state = state; } - Future setFilters(OBModeratedObjectsFilters filters) async { - return state.setFilters(filters); + Future? setFilters(OBModeratedObjectsFilters filters) async { + return state?.setFilters(filters); } - OBModeratedObjectsFilters getFilters() { - return state.getFilters(); + OBModeratedObjectsFilters? getFilters() { + return state?.getFilters(); } void scrollToTop() { - state.scrollToTop(); + state?.scrollToTop(); } bool hasCommunity() { - return state.hasCommunity(); + return state?.hasCommunity() ?? false; } } class OBModeratedObjectsPageLoadMoreDelegate extends LoadMoreDelegate { - final VoidCallback onWantsToRetryLoading; + final VoidCallback? onWantsToRetryLoading; const OBModeratedObjectsPageLoadMoreDelegate({this.onWantsToRetryLoading}); @@ -407,7 +407,7 @@ class OBModeratedObjectsPageLoadMoreDelegate extends LoadMoreDelegate { if (status == LoadMoreStatus.fail) { return OBRetryTile( text: 'Tap to retry loading items', - onWantsToRetry: onWantsToRetryLoading, + onWantsToRetry: onWantsToRetryLoading ?? () {}, ); } if (status == LoadMoreStatus.idle) { diff --git a/lib/pages/home/pages/moderated_objects/pages/moderated_object_community_review.dart b/lib/pages/home/pages/moderated_objects/pages/moderated_object_community_review.dart index 69802c22f..61d01e741 100644 --- a/lib/pages/home/pages/moderated_objects/pages/moderated_object_community_review.dart +++ b/lib/pages/home/pages/moderated_objects/pages/moderated_object_community_review.dart @@ -24,7 +24,7 @@ class OBModeratedObjectCommunityReviewPage extends StatefulWidget { final Community community; const OBModeratedObjectCommunityReviewPage( - {Key key, @required this.moderatedObject, @required this.community}) + {Key? key, required this.moderatedObject, required this.community}) : super(key: key); @override @@ -35,16 +35,16 @@ class OBModeratedObjectCommunityReviewPage extends StatefulWidget { class OBModeratedObjectCommunityReviewPageState extends State { - bool _requestInProgress; - bool _isEditable; + late bool _requestInProgress; + late bool _isEditable; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; - CancelableOperation _requestOperation; - OBModeratedObjectLogsController _logsController; + CancelableOperation? _requestOperation; + late OBModeratedObjectLogsController _logsController; @override void initState() { @@ -58,7 +58,7 @@ class OBModeratedObjectCommunityReviewPageState @override void dispose() { super.dispose(); - if (_requestOperation != null) _requestOperation.cancel(); + if (_requestOperation != null) _requestOperation!.cancel(); } @override @@ -125,7 +125,7 @@ class OBModeratedObjectCommunityReviewPageState Widget _buildPrimaryActions() { List actions = []; - if (widget.moderatedObject.verified) { + if (widget.moderatedObject.verified == true) { actions.add(_buildVerifiedButton()); } else if (widget.moderatedObject.status != ModeratedObjectStatus.pending) { if (widget.moderatedObject.status == ModeratedObjectStatus.approved) { @@ -202,7 +202,7 @@ class OBModeratedObjectCommunityReviewPageState try { _requestOperation = CancelableOperation.fromFuture( _userService.approveModeratedObject(widget.moderatedObject)); - await _requestOperation.value; + await _requestOperation?.value; widget.moderatedObject.setIsApproved(); _updateIsEditable(); } catch (error) { @@ -218,7 +218,7 @@ class OBModeratedObjectCommunityReviewPageState try { _requestOperation = CancelableOperation.fromFuture( _userService.rejectModeratedObject(widget.moderatedObject)); - await _requestOperation.value; + await _requestOperation?.value; widget.moderatedObject.setIsRejected(); _updateIsEditable(); } catch (error) { @@ -251,8 +251,8 @@ class OBModeratedObjectCommunityReviewPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/pages/moderated_objects/pages/moderated_object_global_review.dart b/lib/pages/home/pages/moderated_objects/pages/moderated_object_global_review.dart index 99b10dab6..57cb5a4d5 100644 --- a/lib/pages/home/pages/moderated_objects/pages/moderated_object_global_review.dart +++ b/lib/pages/home/pages/moderated_objects/pages/moderated_object_global_review.dart @@ -24,7 +24,7 @@ class OBModeratedObjectGlobalReviewPage extends StatefulWidget { final ModeratedObject moderatedObject; const OBModeratedObjectGlobalReviewPage( - {Key key, @required this.moderatedObject}) + {Key? key, required this.moderatedObject}) : super(key: key); @override @@ -35,16 +35,16 @@ class OBModeratedObjectGlobalReviewPage extends StatefulWidget { class OBModeratedObjectGlobalReviewPageState extends State { - bool _requestInProgress; - bool _isEditable; + late bool _requestInProgress; + late bool _isEditable; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; - CancelableOperation _requestOperation; - OBModeratedObjectLogsController _logsController; + CancelableOperation? _requestOperation; + late OBModeratedObjectLogsController _logsController; @override void initState() { @@ -126,7 +126,7 @@ class OBModeratedObjectGlobalReviewPageState builder: (BuildContext context, AsyncSnapshot snapshot) { List actions = []; - if (snapshot.data.verified) { + if (snapshot.data?.verified == true) { actions.add(Expanded( child: OBButton( size: OBButtonSize.large, @@ -201,7 +201,7 @@ class OBModeratedObjectGlobalReviewPageState try { _requestOperation = CancelableOperation.fromFuture( _userService.verifyModeratedObject(widget.moderatedObject)); - await _requestOperation.value; + await _requestOperation?.value; widget.moderatedObject.setIsVerified(true); _updateIsEditable(); _refreshLogs(); @@ -218,7 +218,7 @@ class OBModeratedObjectGlobalReviewPageState try { _requestOperation = CancelableOperation.fromFuture( _userService.unverifyModeratedObject(widget.moderatedObject)); - await _requestOperation.value; + await _requestOperation?.value; widget.moderatedObject.setIsVerified(false); _updateIsEditable(); _refreshLogs(); @@ -230,12 +230,12 @@ class OBModeratedObjectGlobalReviewPageState } void _bootstrap() { - _isEditable = !widget.moderatedObject.verified; + _isEditable = !(widget.moderatedObject.verified ?? false); } void _updateIsEditable() { setState(() { - _isEditable = !widget.moderatedObject.verified; + _isEditable = !(widget.moderatedObject.verified ?? false); }); } @@ -244,8 +244,8 @@ class OBModeratedObjectGlobalReviewPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_category/modals/moderated_object_update_category.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_category/modals/moderated_object_update_category.dart index bca31bee1..9b768b609 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_category/modals/moderated_object_update_category.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_category/modals/moderated_object_update_category.dart @@ -20,7 +20,7 @@ class OBModeratedObjectUpdateCategoryModal extends StatefulWidget { final ModeratedObject moderatedObject; const OBModeratedObjectUpdateCategoryModal( - {Key key, @required this.moderatedObject}) + {Key? key, required this.moderatedObject}) : super(key: key); @override @@ -31,20 +31,20 @@ class OBModeratedObjectUpdateCategoryModal extends StatefulWidget { class OBModeratedObjectUpdateCategoryModalState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; List _moderationCategories = []; - ModerationCategory _selectedModerationCategory; - bool _needsBootstrap; - bool _requestInProgress; + late ModerationCategory _selectedModerationCategory; + late bool _needsBootstrap; + late bool _requestInProgress; @override void initState() { super.initState(); _needsBootstrap = true; _requestInProgress = false; - _selectedModerationCategory = widget.moderatedObject.category; + _selectedModerationCategory = widget.moderatedObject.category!; } @override @@ -104,10 +104,10 @@ class OBModeratedObjectUpdateCategoryModalState Expanded( child: ListTile( title: OBText( - category.title, + category.title!, style: TextStyle(fontWeight: FontWeight.bold), ), - subtitle: OBSecondaryText(category.description), + subtitle: OBSecondaryText(category.description!), //trailing: OBIcon(OBIcons.chevronRight), ), ), @@ -146,15 +146,15 @@ class OBModeratedObjectUpdateCategoryModalState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; } } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: _localizationService.trans('moderation__update_category_title'), trailing: OBButton( @@ -173,7 +173,7 @@ class OBModeratedObjectUpdateCategoryModalState _setModerationCategories(ModerationCategoriesList moderationCategoriesList) { setState(() { - _moderationCategories = moderationCategoriesList.moderationCategories; + _moderationCategories = moderationCategoriesList.moderationCategories ?? []; }); } diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_category/moderated_object_category.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_category/moderated_object_category.dart index b9b7733d6..e04d2084e 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_category/moderated_object_category.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_category/moderated_object_category.dart @@ -11,12 +11,12 @@ import 'package:flutter/material.dart'; class OBModeratedObjectCategory extends StatelessWidget { final bool isEditable; final ModeratedObject moderatedObject; - final ValueChanged onCategoryChanged; + final ValueChanged? onCategoryChanged; const OBModeratedObjectCategory( - {Key key, - @required this.moderatedObject, - @required this.isEditable, + {Key? key, + required this.moderatedObject, + required this.isEditable, this.onCategoryChanged}) : super(key: key); @@ -36,17 +36,17 @@ class OBModeratedObjectCategory extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { return OBModerationCategoryTile( - category: snapshot.data.category, + category: snapshot.data!.category!, onPressed: (category) async { if (!isEditable) return; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - ModerationCategory newModerationCategory = + ModerationCategory? newModerationCategory = await openbookProvider.modalService .openModeratedObjectUpdateCategory( context: context, moderatedObject: moderatedObject); if (newModerationCategory != null && onCategoryChanged != null) - onCategoryChanged(newModerationCategory); + onCategoryChanged!(newModerationCategory); }, trailing: isEditable ? const OBIcon( OBIcons.edit, diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_description/modals/moderated_object_update_description.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_description/modals/moderated_object_update_description.dart index 20102f07f..f8ba2da7e 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_description/modals/moderated_object_update_description.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_description/modals/moderated_object_update_description.dart @@ -19,7 +19,7 @@ class OBModeratedObjectUpdateDescriptionModal extends StatefulWidget { final ModeratedObject moderatedObject; const OBModeratedObjectUpdateDescriptionModal( - {Key key, @required this.moderatedObject}) + {Key? key, required this.moderatedObject}) : super(key: key); @override @@ -30,20 +30,20 @@ class OBModeratedObjectUpdateDescriptionModal extends StatefulWidget { class OBModeratedObjectUpdateDescriptionModalState extends State { - UserService _userService; - ToastService _toastService; - ValidationService _validationService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ValidationService _validationService; + late LocalizationService _localizationService; - bool _requestInProgress; - bool _formWasSubmitted; - bool _formValid; + late bool _requestInProgress; + late bool _formWasSubmitted; + late bool _formValid; - GlobalKey _formKey; + late GlobalKey _formKey; - TextEditingController _descriptionController; + late TextEditingController _descriptionController; - CancelableOperation _editDescriptionOperation; + CancelableOperation? _editDescriptionOperation; @override void initState() { @@ -61,7 +61,7 @@ class OBModeratedObjectUpdateDescriptionModalState @override void dispose() { super.dispose(); - if (_editDescriptionOperation != null) _editDescriptionOperation.cancel(); + if (_editDescriptionOperation != null) _editDescriptionOperation!.cancel(); } @override @@ -96,7 +96,7 @@ class OBModeratedObjectUpdateDescriptionModalState labelText: _localizationService.trans('moderation__update_description_report_desc'), hintText: _localizationService.trans('moderation__update_description_report_hint_text')), - validator: (String description) { + validator: (String? description) { if (!_formWasSubmitted) return null; return _validationService .validateModeratedObjectDescription( @@ -110,7 +110,7 @@ class OBModeratedObjectUpdateDescriptionModalState )); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: _localizationService.trans('moderation__update_description_title'), trailing: OBButton( @@ -123,7 +123,7 @@ class OBModeratedObjectUpdateDescriptionModalState } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } bool _updateFormValid() { @@ -143,7 +143,7 @@ class OBModeratedObjectUpdateDescriptionModalState _userService.updateModeratedObject(widget.moderatedObject, description: _descriptionController.text)); - await _editDescriptionOperation.value; + await _editDescriptionOperation?.value; Navigator.of(context).pop(_descriptionController.text); } catch (error) { @@ -159,8 +159,8 @@ class OBModeratedObjectUpdateDescriptionModalState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_description/moderated_object_description.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_description/moderated_object_description.dart index 3d0f4ffb8..95f1451c6 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_description/moderated_object_description.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_description/moderated_object_description.dart @@ -9,12 +9,12 @@ import 'package:flutter/material.dart'; class OBModeratedObjectDescription extends StatelessWidget { final bool isEditable; final ModeratedObject moderatedObject; - final ValueChanged onDescriptionChanged; + final ValueChanged? onDescriptionChanged; const OBModeratedObjectDescription( - {Key key, - @required this.moderatedObject, - @required this.isEditable, + {Key? key, + required this.moderatedObject, + required this.isEditable, this.onDescriptionChanged}) : super(key: key); @@ -32,20 +32,20 @@ class OBModeratedObjectDescription extends StatelessWidget { if(!isEditable) return; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - String newDescription = await openbookProvider.modalService + String? newDescription = await openbookProvider.modalService .openModeratedObjectUpdateDescription( context: context, moderatedObject: moderatedObject); if (newDescription != null && onDescriptionChanged != null) - onDescriptionChanged(newDescription); + onDescriptionChanged!(newDescription); }, title: StreamBuilder( initialData: moderatedObject, stream: moderatedObject.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot) { - String description = snapshot.data.description; + String? description = snapshot.data?.description; return description != null - ? OBText(snapshot.data.description) + ? OBText(description) : OBSecondaryText( 'No description', style: TextStyle(fontStyle: FontStyle.italic), diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/moderated_object_logs.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/moderated_object_logs.dart index c9162bcb6..3e5b0247b 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/moderated_object_logs.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/moderated_object_logs.dart @@ -14,10 +14,10 @@ import 'package:flutter/material.dart'; class OBModeratedObjectLogs extends StatefulWidget { final ModeratedObject moderatedObject; - final OBModeratedObjectLogsController controller; + final OBModeratedObjectLogsController? controller; const OBModeratedObjectLogs( - {Key key, @required this.moderatedObject, this.controller}) + {Key? key, required this.moderatedObject, this.controller}) : super(key: key); @override @@ -29,13 +29,13 @@ class OBModeratedObjectLogs extends StatefulWidget { class OBModeratedObjectLogsState extends State { static int logssCount = 5; - bool _needsBootstrap; - UserService _userService; - ToastService _toastService; + late bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; - CancelableOperation _refreshLogsOperation; - bool _refreshInProgress; - List _logs; + CancelableOperation? _refreshLogsOperation; + late bool _refreshInProgress; + late List _logs; @override void initState() { @@ -43,13 +43,13 @@ class OBModeratedObjectLogsState extends State { _needsBootstrap = true; _refreshInProgress = false; _logs = []; - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); } @override void dispose() { super.dispose(); - if (_refreshLogsOperation != null) _refreshLogsOperation.cancel(); + if (_refreshLogsOperation != null) _refreshLogsOperation!.cancel(); } @override @@ -114,8 +114,8 @@ class OBModeratedObjectLogsState extends State { .getModeratedObjectLogs(widget.moderatedObject, count: 5)); ModeratedObjectLogsList moderationLogsList = - await _refreshLogsOperation.value; - _setLogs(moderationLogsList.moderatedObjectLogs); + await _refreshLogsOperation?.value; + _setLogs(moderationLogsList.moderatedObjectLogs ?? []); } catch (error) { _onError(error); } finally { @@ -140,8 +140,8 @@ class OBModeratedObjectLogsState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; @@ -150,13 +150,13 @@ class OBModeratedObjectLogsState extends State { } class OBModeratedObjectLogsController { - OBModeratedObjectLogsState _state; + OBModeratedObjectLogsState? _state; void attach(state) { _state = state; } - Future refreshLogs() { - return _state._refreshLogs(); + Future? refreshLogs() { + return _state?._refreshLogs(); } } diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/moderated_object_log_tile.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/moderated_object_log_tile.dart index 6ef409511..66fddfab5 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/moderated_object_log_tile.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/moderated_object_log_tile.dart @@ -10,12 +10,12 @@ import 'package:flutter/material.dart'; class OBModeratedObjectLogTile extends StatelessWidget { final ModeratedObjectLog log; - final ValueChanged onModeratedObjectLogTileDeleted; - final ValueChanged onPressed; + final ValueChanged? onModeratedObjectLogTileDeleted; + final ValueChanged? onPressed; const OBModeratedObjectLogTile( - {Key key, - @required this.log, + {Key? key, + required this.log, this.onModeratedObjectLogTileDeleted, this.onPressed}) : super(key: key); @@ -77,7 +77,7 @@ class OBModeratedObjectLogTile extends StatelessWidget { style: TextStyle(fontWeight: FontWeight.bold), ), OBModeratedObjectLogActor( - actor: log.actor, + actor: log.actor!, ), SizedBox( height: 5, diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_category_changed_log_tile.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_category_changed_log_tile.dart index 066ad9825..bc3a61214 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_category_changed_log_tile.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_category_changed_log_tile.dart @@ -9,12 +9,12 @@ import 'moderated_object_log_actor.dart'; class OBModeratedObjectCategoryChangedLogTile extends StatelessWidget { final ModeratedObjectLog log; final ModeratedObjectCategoryChangedLog moderatedObjectCategoryChangedLog; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBModeratedObjectCategoryChangedLogTile( - {Key key, - @required this.log, - @required this.moderatedObjectCategoryChangedLog, + {Key? key, + required this.log, + required this.moderatedObjectCategoryChangedLog, this.onPressed}) : super(key: key); @@ -30,14 +30,14 @@ class OBModeratedObjectCategoryChangedLogTile extends StatelessWidget { ), OBModerationCategoryTile( contentPadding: const EdgeInsets.all(0), - category: moderatedObjectCategoryChangedLog.changedFrom), + category: moderatedObjectCategoryChangedLog.changedFrom!), OBText( 'To:', style: TextStyle(fontWeight: FontWeight.bold), ), OBModerationCategoryTile( contentPadding: const EdgeInsets.all(0), - category: moderatedObjectCategoryChangedLog.changedTo), + category: moderatedObjectCategoryChangedLog.changedTo!), ], ), ); diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_description_changed_log_tile.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_description_changed_log_tile.dart index c6cc18276..459dac5ae 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_description_changed_log_tile.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_description_changed_log_tile.dart @@ -9,12 +9,12 @@ class OBModeratedObjectDescriptionChangedLogTile extends StatelessWidget { final ModeratedObjectLog log; final ModeratedObjectDescriptionChangedLog moderatedObjectDescriptionChangedLog; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBModeratedObjectDescriptionChangedLogTile( - {Key key, - @required this.log, - @required this.moderatedObjectDescriptionChangedLog, + {Key? key, + required this.log, + required this.moderatedObjectDescriptionChangedLog, this.onPressed}) : super(key: key); @@ -30,7 +30,7 @@ class OBModeratedObjectDescriptionChangedLogTile extends StatelessWidget { ), OBSecondaryText( moderatedObjectDescriptionChangedLog.changedFrom != null - ? moderatedObjectDescriptionChangedLog.changedFrom + ? moderatedObjectDescriptionChangedLog.changedFrom! : 'No description', style: TextStyle( fontStyle: @@ -45,7 +45,7 @@ class OBModeratedObjectDescriptionChangedLogTile extends StatelessWidget { 'To:', style: TextStyle(fontWeight: FontWeight.bold), ), - OBSecondaryText(moderatedObjectDescriptionChangedLog.changedTo), + OBSecondaryText(moderatedObjectDescriptionChangedLog.changedTo!), ], ), ); diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_log_actor.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_log_actor.dart index ed028f5e3..16de41355 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_log_actor.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_log_actor.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; class OBModeratedObjectLogActor extends StatelessWidget { final User actor; - const OBModeratedObjectLogActor({Key key, @required this.actor}) + const OBModeratedObjectLogActor({Key? key, required this.actor}) : super(key: key); Widget build(BuildContext context) { @@ -32,7 +32,7 @@ class OBModeratedObjectLogActor extends StatelessWidget { width: 6, ), OBSecondaryText( - '@' + actor.username, + '@' + actor.username!, style: TextStyle(fontWeight: FontWeight.bold), ), ], diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_status_changed_log_tile.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_status_changed_log_tile.dart index ac6cefb1a..d97b3b7a3 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_status_changed_log_tile.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_status_changed_log_tile.dart @@ -9,12 +9,12 @@ import 'moderated_object_log_actor.dart'; class OBModeratedObjectStatusChangedLogTile extends StatelessWidget { final ModeratedObjectLog log; final ModeratedObjectStatusChangedLog moderatedObjectStatusChangedLog; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBModeratedObjectStatusChangedLogTile( - {Key key, - @required this.log, - @required this.moderatedObjectStatusChangedLog, + {Key? key, + required this.log, + required this.moderatedObjectStatusChangedLog, this.onPressed}) : super(key: key); @@ -31,7 +31,7 @@ class OBModeratedObjectStatusChangedLogTile extends StatelessWidget { OBSecondaryText(ModeratedObject.factory .convertStatusToHumanReadableString( moderatedObjectStatusChangedLog.changedFrom, - capitalize: true)), + capitalize: true)!), const SizedBox( height: 10, ), @@ -42,7 +42,7 @@ class OBModeratedObjectStatusChangedLogTile extends StatelessWidget { OBSecondaryText(ModeratedObject.factory .convertStatusToHumanReadableString( moderatedObjectStatusChangedLog.changedTo, - capitalize: true)), + capitalize: true)!), ], ), ); diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_verified_changed_log_tile.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_verified_changed_log_tile.dart index d109d5223..d6dbc8a66 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_verified_changed_log_tile.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_logs/widgets/moderated_object_log_tile/widgets/moderated_object_verified_changed_log_tile.dart @@ -8,12 +8,12 @@ import 'moderated_object_log_actor.dart'; class OBModeratedObjectVerifiedChangedLogTile extends StatelessWidget { final ModeratedObjectLog log; final ModeratedObjectVerifiedChangedLog moderatedObjectVerifiedChangedLog; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBModeratedObjectVerifiedChangedLogTile( - {Key key, - @required this.log, - @required this.moderatedObjectVerifiedChangedLog, + {Key? key, + required this.log, + required this.moderatedObjectVerifiedChangedLog, this.onPressed}) : super(key: key); diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/moderated_object_reports_preview.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/moderated_object_reports_preview.dart index e8d51ccae..d0986a0eb 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/moderated_object_reports_preview.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/moderated_object_reports_preview.dart @@ -24,7 +24,7 @@ class OBModeratedObjectReportsPreview extends StatefulWidget { final ModeratedObject moderatedObject; const OBModeratedObjectReportsPreview( - {Key key, @required this.moderatedObject, @required this.isEditable}) + {Key? key, required this.moderatedObject, required this.isEditable}) : super(key: key); @override @@ -37,15 +37,15 @@ class OBModeratedObjectReportsPreviewState extends State { static int reportsPreviewsCount = 5; - bool _needsBootstrap; - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; - LocalizationService _localizationService; + late bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - CancelableOperation _refreshReportsOperation; - bool _refreshInProgress; - List _reports; + CancelableOperation? _refreshReportsOperation; + late bool _refreshInProgress; + late List _reports; @override void initState() { @@ -58,7 +58,7 @@ class OBModeratedObjectReportsPreviewState @override void dispose() { super.dispose(); - if (_refreshReportsOperation != null) _refreshReportsOperation.cancel(); + if (_refreshReportsOperation != null) _refreshReportsOperation!.cancel(); } @override @@ -103,7 +103,7 @@ class OBModeratedObjectReportsPreviewState OBDivider(), OBSeeAllButton( previewedResourcesCount: _reports.length, - resourcesCount: widget.moderatedObject.reportsCount, + resourcesCount: widget.moderatedObject.reportsCount ?? 0, resourceName: _localizationService.moderation__reports_preview_resource_reports, onPressed: _onWantsToSeeAllReports, ) @@ -123,9 +123,9 @@ class OBModeratedObjectReportsPreviewState _refreshReportsOperation = CancelableOperation.fromFuture(_userService .getModeratedObjectReports(widget.moderatedObject, count: 5)); - ModerationReportsList moderationReportsList = - await _refreshReportsOperation.value; - _setReports(moderationReportsList.moderationReports); + ModerationReportsList? moderationReportsList = + await _refreshReportsOperation?.value; + _setReports(moderationReportsList?.moderationReports ?? []); } catch (error) { _onError(error); } @@ -154,8 +154,8 @@ class OBModeratedObjectReportsPreviewState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/moderation_report_tile.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/moderation_report_tile.dart index a9d08841a..9b6a1751b 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/moderation_report_tile.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/moderation_report_tile.dart @@ -9,7 +9,7 @@ import 'package:flutter/material.dart'; class OBModerationReportTile extends StatelessWidget { final ModerationReport report; - const OBModerationReportTile({Key key, @required this.report}) + const OBModerationReportTile({Key? key, required this.report}) : super(key: key); @override @@ -41,13 +41,13 @@ class OBModerationReportTile extends StatelessWidget { } Widget _buildReportReporter( - {@required ModerationReport report, @required BuildContext context}) { + {required ModerationReport report, required BuildContext context}) { LocalizationService _localizationService = OpenbookProvider.of(context).localizationService; return GestureDetector( onTap: () { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService - .navigateToUserProfile(user: report.reporter, context: context); + .navigateToUserProfile(user: report.reporter!, context: context); }, child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -63,13 +63,13 @@ class OBModerationReportTile extends StatelessWidget { OBAvatar( borderRadius: 4, customSize: 16, - avatarUrl: report.reporter.getProfileAvatar(), + avatarUrl: report.reporter!.getProfileAvatar(), ), const SizedBox( width: 6, ), OBSecondaryText( - '@' + report.reporter.username, + '@' + report.reporter!.username!, style: TextStyle(fontWeight: FontWeight.bold), ), ], @@ -88,7 +88,7 @@ class OBModerationReportTile extends StatelessWidget { style: TextStyle(fontWeight: FontWeight.bold), ), OBSecondaryText( - report.description != null ? report.description : _localizationService.moderation__no_description_text, + report.description != null ? report.description! : _localizationService.moderation__no_description_text, style: TextStyle( fontStyle: report.description == null ? FontStyle.italic @@ -108,7 +108,7 @@ class OBModerationReportTile extends StatelessWidget { style: TextStyle(fontWeight: FontWeight.bold), ), OBSecondaryText( - report.category.title, + report.category!.title!, ), ], ); diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/pages/moderated_object_reports.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/pages/moderated_object_reports.dart index 646383739..bf85ef2e7 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/pages/moderated_object_reports.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_reports_preview/pages/moderated_object_reports.dart @@ -13,7 +13,7 @@ import '../moderation_report_tile.dart'; class OBModeratedObjectReportsPage extends StatefulWidget { final ModeratedObject moderatedObject; - const OBModeratedObjectReportsPage({Key key, @required this.moderatedObject}) + const OBModeratedObjectReportsPage({Key? key, required this.moderatedObject}) : super(key: key); @override @@ -24,13 +24,13 @@ class OBModeratedObjectReportsPage extends StatefulWidget { class OBModeratedObjectReportsPageState extends State { - bool _needsBootstrap; - UserService _userService; - ToastService _toastService; + late bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; - CancelableOperation _refreshReportsOperation; - bool _refreshInProgress; - List _reports; + CancelableOperation? _refreshReportsOperation; + late bool _refreshInProgress; + late List _reports; @override void initState() { @@ -43,7 +43,7 @@ class OBModeratedObjectReportsPageState @override void dispose() { super.dispose(); - if (_refreshReportsOperation != null) _refreshReportsOperation.cancel(); + if (_refreshReportsOperation != null) _refreshReportsOperation!.cancel(); } @override @@ -84,9 +84,9 @@ class OBModeratedObjectReportsPageState _refreshReportsOperation = CancelableOperation.fromFuture(_userService .getModeratedObjectReports(widget.moderatedObject, count: 5)); - ModerationReportsList moderationReportsList = - await _refreshReportsOperation.value; - _setReports(moderationReportsList.moderationReports); + ModerationReportsList? moderationReportsList = + await _refreshReportsOperation?.value; + _setReports(moderationReportsList?.moderationReports ?? []); } catch (error) { _onError(error); } @@ -110,8 +110,8 @@ class OBModeratedObjectReportsPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_status/modals/moderated_object_update_status.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_status/modals/moderated_object_update_status.dart index c91e2e237..d00d46ae1 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_status/modals/moderated_object_update_status.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_status/modals/moderated_object_update_status.dart @@ -19,7 +19,7 @@ class OBModeratedObjectUpdateStatusModal extends StatefulWidget { final ModeratedObject moderatedObject; const OBModeratedObjectUpdateStatusModal( - {Key key, @required this.moderatedObject}) + {Key? key, required this.moderatedObject}) : super(key: key); @override @@ -30,25 +30,25 @@ class OBModeratedObjectUpdateStatusModal extends StatefulWidget { class OBModeratedObjectUpdateStatusModalState extends State { - UserService _userService; - LocalizationService _localizationService; - ToastService _toastService; + late UserService _userService; + late LocalizationService _localizationService; + late ToastService _toastService; List _moderationStatuses = [ ModeratedObjectStatus.rejected, ModeratedObjectStatus.approved, ]; - ModeratedObjectStatus _selectedModerationStatus; - bool _needsBootstrap; - bool _requestInProgress; + late ModeratedObjectStatus _selectedModerationStatus; + late bool _needsBootstrap; + late bool _requestInProgress; - CancelableOperation _updateStatusOperation; + CancelableOperation? _updateStatusOperation; @override void initState() { super.initState(); _needsBootstrap = true; _requestInProgress = false; - _selectedModerationStatus = widget.moderatedObject.status; + _selectedModerationStatus = widget.moderatedObject.status!; } @override @@ -78,7 +78,7 @@ class OBModeratedObjectUpdateStatusModalState @override void dispose() { super.dispose(); - if (_updateStatusOperation != null) _updateStatusOperation.cancel(); + if (_updateStatusOperation != null) _updateStatusOperation!.cancel(); } Widget _buildProgressIndicator() { @@ -105,7 +105,7 @@ class OBModeratedObjectUpdateStatusModalState Widget _buildModerationStatusTile(context, index) { ModeratedObjectStatus status = _moderationStatuses[index]; String statusString = ModeratedObject.factory - .convertStatusToHumanReadableString(status, capitalize: true); + .convertStatusToHumanReadableString(status, capitalize: true)!; return GestureDetector( key: Key(statusString), @@ -168,7 +168,7 @@ class OBModeratedObjectUpdateStatusModalState default: throw 'Unsuppported update type'; } - await _updateStatusOperation.value; + await _updateStatusOperation?.value; Navigator.of(context).pop(_selectedModerationStatus); widget.moderatedObject.setStatus(_selectedModerationStatus); } catch (error) { @@ -184,15 +184,15 @@ class OBModeratedObjectUpdateStatusModalState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; } } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: _localizationService.trans('moderation__update_status_title'), trailing: OBButton( diff --git a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_status/moderated_object_status.dart b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_status/moderated_object_status.dart index 1b6169c05..366f912f7 100644 --- a/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_status/moderated_object_status.dart +++ b/lib/pages/home/pages/moderated_objects/pages/widgets/moderated_object_status/moderated_object_status.dart @@ -10,12 +10,12 @@ import 'package:flutter/material.dart'; class OBModeratedObjectStatus extends StatelessWidget { final bool isEditable; final ModeratedObject moderatedObject; - final ValueChanged onStatusChanged; + final ValueChanged? onStatusChanged; const OBModeratedObjectStatus( - {Key key, - @required this.moderatedObject, - @required this.isEditable, + {Key? key, + required this.moderatedObject, + required this.isEditable, this.onStatusChanged}) : super(key: key); @@ -46,12 +46,12 @@ class OBModeratedObjectStatus extends StatelessWidget { if (!isEditable) return; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - ModeratedObjectStatus newModerationStatus = + ModeratedObjectStatus? newModerationStatus = await openbookProvider.modalService .openModeratedObjectUpdateStatus( context: context, moderatedObject: moderatedObject); if (newModerationStatus != null && onStatusChanged != null) - onStatusChanged(newModerationStatus); + onStatusChanged!(newModerationStatus); }, ); }, diff --git a/lib/pages/home/pages/moderated_objects/widgets/moderated_object/moderated_object.dart b/lib/pages/home/pages/moderated_objects/widgets/moderated_object/moderated_object.dart index af3db9ef6..4a5cbf5ee 100644 --- a/lib/pages/home/pages/moderated_objects/widgets/moderated_object/moderated_object.dart +++ b/lib/pages/home/pages/moderated_objects/widgets/moderated_object/moderated_object.dart @@ -16,10 +16,10 @@ import '../../../../../../provider.dart'; class OBModeratedObject extends StatelessWidget { final ModeratedObject moderatedObject; - final Community community; + final Community? community; const OBModeratedObject( - {Key key, @required this.moderatedObject, this.community}) + {Key? key, required this.moderatedObject, this.community}) : super(key: key); @override @@ -86,7 +86,7 @@ class OBModeratedObject extends StatelessWidget { child: Row( children: [ OBIcon( - moderatedObject.verified + moderatedObject.verified == true ? OBIcons.verify : OBIcons.unverify, size: OBIconSize.small, @@ -95,7 +95,7 @@ class OBModeratedObject extends StatelessWidget { width: 10, ), OBText( - moderatedObject.verified ? _localizationService.moderation__moderated_object_true_text : _localizationService.moderation__moderated_object_false_text, + moderatedObject.verified == true ? _localizationService.moderation__moderated_object_true_text : _localizationService.moderation__moderated_object_false_text, ) ], ), diff --git a/lib/pages/home/pages/moderated_objects/widgets/moderated_object/widgets/moderated_object_actions.dart b/lib/pages/home/pages/moderated_objects/widgets/moderated_object/widgets/moderated_object_actions.dart index 312b55a07..68085d414 100644 --- a/lib/pages/home/pages/moderated_objects/widgets/moderated_object/widgets/moderated_object_actions.dart +++ b/lib/pages/home/pages/moderated_objects/widgets/moderated_object/widgets/moderated_object_actions.dart @@ -8,11 +8,11 @@ import 'package:Okuna/widgets/theming/text.dart'; import 'package:flutter/material.dart'; class OBModeratedObjectActions extends StatelessWidget { - final Community community; + final Community? community; final ModeratedObject moderatedObject; OBModeratedObjectActions( - {@required this.community, @required this.moderatedObject}); + {required this.community, required this.moderatedObject}); @override Widget build(BuildContext context) { diff --git a/lib/pages/home/pages/moderated_objects/widgets/moderated_object/widgets/moderated_object_preview.dart b/lib/pages/home/pages/moderated_objects/widgets/moderated_object/widgets/moderated_object_preview.dart index 88ed1f4d6..129785034 100644 --- a/lib/pages/home/pages/moderated_objects/widgets/moderated_object/widgets/moderated_object_preview.dart +++ b/lib/pages/home/pages/moderated_objects/widgets/moderated_object/widgets/moderated_object_preview.dart @@ -14,7 +14,7 @@ import 'package:flutter/material.dart'; class OBModeratedObjectPreview extends StatelessWidget { final ModeratedObject moderatedObject; - const OBModeratedObjectPreview({Key key, @required this.moderatedObject}) + const OBModeratedObjectPreview({Key? key, required this.moderatedObject}) : super(key: key); @override diff --git a/lib/pages/home/pages/moderated_objects/widgets/no_moderated_objects.dart b/lib/pages/home/pages/moderated_objects/widgets/no_moderated_objects.dart index f5cdd6531..b0392b28a 100644 --- a/lib/pages/home/pages/moderated_objects/widgets/no_moderated_objects.dart +++ b/lib/pages/home/pages/moderated_objects/widgets/no_moderated_objects.dart @@ -5,7 +5,7 @@ import 'package:flutter/material.dart'; class OBNoModeratedObjects extends StatelessWidget { final VoidCallback onWantsToRefreshModeratedObjects; - OBNoModeratedObjects({@required this.onWantsToRefreshModeratedObjects}); + OBNoModeratedObjects({required this.onWantsToRefreshModeratedObjects}); @override Widget build(BuildContext context) { diff --git a/lib/pages/home/pages/notifications/notifications.dart b/lib/pages/home/pages/notifications/notifications.dart index 593931c6a..9ecdb39e2 100644 --- a/lib/pages/home/pages/notifications/notifications.dart +++ b/lib/pages/home/pages/notifications/notifications.dart @@ -28,7 +28,7 @@ import 'package:flutter/material.dart'; import 'package:async/async.dart'; class OBNotificationsPage extends StatefulWidget { - final OBNotificationsPageController controller; + final OBNotificationsPageController? controller; final OBNotificationsPageTab selectedTab; OBNotificationsPage( @@ -62,35 +62,35 @@ class OBNotificationsPageState extends State NotificationType.followRequest, ]; - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; - LocalizationService _localizationService; - PushNotificationsService _pushNotificationsService; - OBHttpListController _generalNotificationsListController; - OBHttpListController _requestsNotificationsListController; - StreamSubscription _pushNotificationSubscription; - OBNotificationsPageController _controller; - TabController _tabController; - - CancelableOperation _getUnreadGeneralNotificationsCountOperation; - CancelableOperation _getUnreadRequestNotificationsCountOperation; - - bool _needsBootstrap; - bool _isActivePage; - int _unreadRequestNotificationsCount; - int _unreadGeneralNotificationsCount; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late PushNotificationsService _pushNotificationsService; + late OBHttpListController _generalNotificationsListController; + late OBHttpListController _requestsNotificationsListController; + late StreamSubscription _pushNotificationSubscription; + late OBNotificationsPageController _controller; + late TabController _tabController; + + CancelableOperation? _getUnreadGeneralNotificationsCountOperation; + CancelableOperation? _getUnreadRequestNotificationsCountOperation; + + late bool _needsBootstrap; + bool? _isActivePage; + late int? _unreadRequestNotificationsCount; + late int? _unreadGeneralNotificationsCount; // Should be the case when the page is visible to the user - bool _shouldMarkNotificationsAsRead; + late bool _shouldMarkNotificationsAsRead; @override void initState() { super.initState(); - WidgetsBinding.instance.addObserver(this); + WidgetsBinding.instance?.addObserver(this); _generalNotificationsListController = OBHttpListController(); _requestsNotificationsListController = OBHttpListController(); - _controller = widget.controller ?? OBNotificationsPage(); + _controller = widget.controller ?? OBNotificationsPageController(); _controller.attach(state: this, context: context); _tabController = new TabController(length: 2, vsync: this); @@ -160,7 +160,7 @@ class OBNotificationsPageState extends State OBText(_localizationService .notifications__tab_general()), _unreadGeneralNotificationsCount != null && - _unreadGeneralNotificationsCount > 0 + _unreadGeneralNotificationsCount! > 0 ? Positioned( right: -15, child: OBBadge( @@ -180,7 +180,7 @@ class OBNotificationsPageState extends State OBText( _localizationService.notifications__tab_requests()), _unreadRequestNotificationsCount != null && - _unreadRequestNotificationsCount > 0 + _unreadRequestNotificationsCount! > 0 ? Positioned( right: -15, child: OBBadge( @@ -235,12 +235,12 @@ class OBNotificationsPageState extends State super.dispose(); if (_getUnreadGeneralNotificationsCountOperation != null) - _getUnreadGeneralNotificationsCountOperation.cancel(); + _getUnreadGeneralNotificationsCountOperation!.cancel(); if (_getUnreadRequestNotificationsCountOperation != null) - _getUnreadRequestNotificationsCountOperation.cancel(); + _getUnreadRequestNotificationsCountOperation!.cancel(); - WidgetsBinding.instance.removeObserver(this); + WidgetsBinding.instance?.removeObserver(this); _pushNotificationSubscription.cancel(); } @@ -293,19 +293,19 @@ class OBNotificationsPageState extends State } Future> _refreshNotifications( - [List types]) async { + [List? types]) async { await _readNotifications(types: types); NotificationsList notificationsList = await _userService.getNotifications(types: types); - return notificationsList.notifications; + return notificationsList.notifications!; } Future _refreshUnreadGeneralNotificationsCount() async { _getUnreadGeneralNotificationsCountOperation = CancelableOperation.fromFuture( _userService.getUnreadNotificationsCount(types: _generalTypes)); - int unreadCount = await _getUnreadGeneralNotificationsCountOperation.value; + int unreadCount = await _getUnreadGeneralNotificationsCountOperation!.value; setUnreadGeneralNotificationsCount(unreadCount); } @@ -313,11 +313,11 @@ class OBNotificationsPageState extends State _getUnreadRequestNotificationsCountOperation = CancelableOperation.fromFuture( _userService.getUnreadNotificationsCount(types: _requestTypes)); - int unreadCount = await _getUnreadRequestNotificationsCountOperation.value; + int unreadCount = await _getUnreadRequestNotificationsCountOperation!.value; setUnreadRequestNotificationsCount(unreadCount); } - Future _readNotifications({List types}) async { + Future _readNotifications({List? types}) async { if (!_shouldMarkNotificationsAsRead) return; OBNotification firstItem; @@ -331,7 +331,7 @@ class OBNotificationsPageState extends State return; } - int maxId = firstItem.id; + int maxId = firstItem.id!; await _userService.readNotifications(maxId: maxId, types: types); } @@ -347,12 +347,12 @@ class OBNotificationsPageState extends State Future> _loadMoreNotifications( List currentNotifications, - [List types]) async { + [List? types]) async { OBNotification lastNotification = currentNotifications.last; - int lastNotificationId = lastNotification.id; + int lastNotificationId = lastNotification.id!; NotificationsList moreNotifications = await _userService.getNotifications( maxId: lastNotificationId, types: types); - return moreNotifications.notifications; + return moreNotifications.notifications!; } void _onNotificationTileDeleted(OBNotification notification) async { @@ -374,8 +374,8 @@ class OBNotificationsPageState extends State _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; @@ -396,7 +396,7 @@ class OBNotificationsPageState extends State void _onPushNotification(PushNotification pushNotification) { bool isNavigating = _controller.canPop(); - if (!_isActivePage || isNavigating) { + if (_isActivePage == null || !_isActivePage! || isNavigating) { _triggerRefreshNotifications(shouldScrollToTop: true); } else { _showRefreshNotificationsToast(); @@ -406,6 +406,7 @@ class OBNotificationsPageState extends State void _showRefreshNotificationsToast() { _toastService.info( duration: Duration(seconds: 2), + message: '', child: Row( children: [ const OBIcon( @@ -436,7 +437,7 @@ class OBNotificationsPageState extends State void didChangeAppLifecycleState(AppLifecycleState state) async { if (state == AppLifecycleState.resumed) { _triggerRefreshNotifications( - shouldScrollToTop: true, shouldUseRefreshIndicator: _isActivePage); + shouldScrollToTop: true, shouldUseRefreshIndicator: _isActivePage ?? false); } } @@ -446,10 +447,10 @@ class OBNotificationsPageState extends State bool shouldMarkNotificationsAsRead = false, }) async { _setShouldMarkNotificationsAsRead(shouldMarkNotificationsAsRead); - await _generalNotificationsListController?.refresh( + await _generalNotificationsListController.refresh( shouldScrollToTop: shouldScrollToTop, shouldUseRefreshIndicator: shouldUseRefreshIndicator); - await _requestsNotificationsListController?.refresh( + await _requestsNotificationsListController.refresh( shouldScrollToTop: shouldScrollToTop, shouldUseRefreshIndicator: shouldUseRefreshIndicator); _setShouldMarkNotificationsAsRead(true); @@ -467,10 +468,10 @@ class OBNotificationsPageState extends State notification.markNotificationAsRead(); if (_generalTypes.contains(notification.type)) { setUnreadGeneralNotificationsCount( - _unreadGeneralNotificationsCount - 1); + _unreadGeneralNotificationsCount! - 1); } else if (_requestTypes.contains(notification.type)) { setUnreadRequestNotificationsCount( - _unreadRequestNotificationsCount - 1); + _unreadRequestNotificationsCount! - 1); } } on HttpieRequestError { // Nothing @@ -482,32 +483,32 @@ class OBNotificationsPageState extends State } class OBNotificationsPageController extends PoppablePageController { - OBNotificationsPageState _state; - bool _markNotificationsAsRead; - bool _isActivePage; + OBNotificationsPageState? _state; + bool? _markNotificationsAsRead; + bool? _isActivePage; void attach( - {@required BuildContext context, OBNotificationsPageState state}) { + {required BuildContext context, OBNotificationsPageState? state}) { super.attach(context: context); _state = state; if (_markNotificationsAsRead != null) - _state._setShouldMarkNotificationsAsRead(_markNotificationsAsRead); + _state?._setShouldMarkNotificationsAsRead(_markNotificationsAsRead!); - if (_isActivePage != null) _state.setIsActivePage(_isActivePage); + if (_isActivePage != null) _state?.setIsActivePage(_isActivePage!); } void scrollToTop() { - _state.scrollToTop(); + _state?.scrollToTop(); } void setIsActivePage(bool isActivePage) { - if (_state != null) _state.setIsActivePage(isActivePage); + if (_state != null) _state!.setIsActivePage(isActivePage); _isActivePage = isActivePage; } void setShouldMarkNotificationsAsRead(bool markNotificationsAsRead) { if (_state != null) - _state._setShouldMarkNotificationsAsRead(markNotificationsAsRead); + _state!._setShouldMarkNotificationsAsRead(markNotificationsAsRead); _markNotificationsAsRead = markNotificationsAsRead; } diff --git a/lib/pages/home/pages/notifications/pages/general_notifications.dart b/lib/pages/home/pages/notifications/pages/general_notifications.dart index 6747ed07a..3bff61510 100644 --- a/lib/pages/home/pages/notifications/pages/general_notifications.dart +++ b/lib/pages/home/pages/notifications/pages/general_notifications.dart @@ -11,13 +11,13 @@ class OBGeneralNotifications extends StatefulWidget { final String resourcePluralName; const OBGeneralNotifications( - {Key key, - @required @required this.controller, - @required this.refresher, - @required this.onScrollLoader, - @required this.itemBuilder, - @required this.resourceSingularName, - @required this.resourcePluralName}) + {Key? key, + required this.controller, + required this.refresher, + required this.onScrollLoader, + required this.itemBuilder, + required this.resourceSingularName, + required this.resourcePluralName}) : super(key: key); @override diff --git a/lib/pages/home/pages/notifications/pages/notifications_settings.dart b/lib/pages/home/pages/notifications/pages/notifications_settings.dart index 9747bde79..ba69f727d 100644 --- a/lib/pages/home/pages/notifications/pages/notifications_settings.dart +++ b/lib/pages/home/pages/notifications/pages/notifications_settings.dart @@ -23,35 +23,36 @@ class OBNotificationsSettingsPage extends StatefulWidget { class OBNotificationsSettingsPageState extends State { - UserService _userService; - PushNotificationsService _pushNotificationsService; - ToastService _toastService; - LocalizationService _localizationService; - - bool _needsBootstrap; - bool _bootstrapInProgress; - - UserNotificationsSettings currentNotificationsSettings; - - bool _pushNotifications; - - bool _postCommentNotifications; - bool _postCommentReactionNotifications; - bool _postCommentReplyNotifications; - bool _postCommentUserMentionNotifications; - bool _postUserMentionNotifications; - bool _postReactionNotifications; - bool _followNotifications; - bool _followRequestNotifications; - bool _followRequestApprovedNotifications; - bool _connectionRequestNotifications; - bool _communityInviteNotifications; - bool _communityNewPostNotifications; - bool _userNewPostNotifications; + late UserService _userService; + late PushNotificationsService _pushNotificationsService; + late ToastService _toastService; + late LocalizationService _localizationService; + + late bool _needsBootstrap; + late bool _bootstrapInProgress; + + UserNotificationsSettings? currentNotificationsSettings; + + late bool _pushNotifications; + + late bool _postCommentNotifications; + late bool _postCommentReactionNotifications; + late bool _postCommentReplyNotifications; + late bool _postCommentUserMentionNotifications; + late bool _postUserMentionNotifications; + late bool _postReactionNotifications; + late bool _followNotifications; + late bool _followRequestNotifications; + late bool _followRequestApprovedNotifications; + late bool _connectionRequestNotifications; + late bool _communityInviteNotifications; + late bool _communityNewPostNotifications; + late bool _userNewPostNotifications; @override void initState() { super.initState(); + _pushNotifications = true; _needsBootstrap = true; _bootstrapInProgress = true; _postCommentNotifications = true; @@ -506,8 +507,8 @@ class OBNotificationsSettingsPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error( message: _localizationService.trans('error__unknown_error'), @@ -520,27 +521,27 @@ class OBNotificationsSettingsPageState UserNotificationsSettings notificationSettings) { setState(() { _connectionRequestNotifications = - notificationSettings.connectionRequestNotifications; - _postCommentNotifications = notificationSettings.postCommentNotifications; + notificationSettings.connectionRequestNotifications ?? false; + _postCommentNotifications = notificationSettings.postCommentNotifications ?? false; _postCommentReactionNotifications = - notificationSettings.postCommentReactionNotifications; + notificationSettings.postCommentReactionNotifications ?? false; _postCommentUserMentionNotifications = - notificationSettings.postCommentUserMentionNotifications; + notificationSettings.postCommentUserMentionNotifications ?? false; _postUserMentionNotifications = - notificationSettings.postUserMentionNotifications; + notificationSettings.postUserMentionNotifications ?? false; _postCommentReplyNotifications = - notificationSettings.postCommentReplyNotifications; + notificationSettings.postCommentReplyNotifications ?? false; _postReactionNotifications = - notificationSettings.postReactionNotifications; - _followNotifications = notificationSettings.followNotifications; - _followRequestNotifications = notificationSettings.followRequestNotifications; - _followRequestApprovedNotifications = notificationSettings.followRequestApprovedNotifications; + notificationSettings.postReactionNotifications ?? false; + _followNotifications = notificationSettings.followNotifications ?? false; + _followRequestNotifications = notificationSettings.followRequestNotifications ?? false; + _followRequestApprovedNotifications = notificationSettings.followRequestApprovedNotifications ?? false; _communityInviteNotifications = - notificationSettings.communityInviteNotifications; + notificationSettings.communityInviteNotifications ?? false; _communityNewPostNotifications = - notificationSettings.communityNewPostNotifications; + notificationSettings.communityNewPostNotifications ?? false; _userNewPostNotifications = - notificationSettings.userNewPostNotifications; + notificationSettings.userNewPostNotifications ?? false; }); } diff --git a/lib/pages/home/pages/notifications/pages/request_notifications.dart b/lib/pages/home/pages/notifications/pages/request_notifications.dart index 642136dc2..b360c6a5e 100644 --- a/lib/pages/home/pages/notifications/pages/request_notifications.dart +++ b/lib/pages/home/pages/notifications/pages/request_notifications.dart @@ -11,13 +11,13 @@ class OBRequestNotifications extends StatefulWidget { final String resourcePluralName; const OBRequestNotifications( - {Key key, - @required @required this.controller, - @required this.refresher, - @required this.onScrollLoader, - @required this.itemBuilder, - @required this.resourceSingularName, - @required this.resourcePluralName}) + {Key? key, + required this.controller, + required this.refresher, + required this.onScrollLoader, + required this.itemBuilder, + required this.resourceSingularName, + required this.resourcePluralName}) : super(key: key); @override diff --git a/lib/pages/home/pages/own_profile.dart b/lib/pages/home/pages/own_profile.dart index 3e6e377e9..0b527469b 100644 --- a/lib/pages/home/pages/own_profile.dart +++ b/lib/pages/home/pages/own_profile.dart @@ -6,7 +6,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBOwnProfilePage extends StatefulWidget { - final OBOwnProfilePageController controller; + final OBOwnProfilePageController? controller; OBOwnProfilePage({ this.controller, @@ -19,14 +19,14 @@ class OBOwnProfilePage extends StatefulWidget { } class OBOwnProfilePageState extends State { - OBProfilePageController _profilePageController; + late OBProfilePageController _profilePageController; @override void initState() { super.initState(); _profilePageController = OBProfilePageController(); if (widget.controller != null) - widget.controller.attach(context: context, state: this); + widget.controller!.attach(context: context, state: this); } @override @@ -36,7 +36,7 @@ class OBOwnProfilePageState extends State { return StreamBuilder( stream: userService.loggedInUserChange, - builder: (BuildContext context, AsyncSnapshot snapshot) { + builder: (BuildContext context, AsyncSnapshot snapshot) { var data = snapshot.data; if (data == null) return const SizedBox(); return OBProfilePage( @@ -53,14 +53,14 @@ class OBOwnProfilePageState extends State { } class OBOwnProfilePageController extends PoppablePageController { - OBOwnProfilePageState _state; + OBOwnProfilePageState? _state; - void attach({@required BuildContext context, OBOwnProfilePageState state}) { + void attach({required BuildContext context, OBOwnProfilePageState? state}) { super.attach(context: context); _state = state; } void scrollToTop() { - if (_state != null) _state.scrollToTop(); + if (_state != null) _state!.scrollToTop(); } } diff --git a/lib/pages/home/pages/post/post.dart b/lib/pages/home/pages/post/post.dart index 4c0eaba34..9c853109f 100644 --- a/lib/pages/home/pages/post/post.dart +++ b/lib/pages/home/pages/post/post.dart @@ -22,11 +22,11 @@ class OBPostPage extends StatefulWidget { } class OBPostPageState extends State { - UserService _userService; - ToastService _toastService; + late UserService _userService; + late ToastService _toastService; - GlobalKey _refreshIndicatorKey; - bool _needsBootstrap; + late GlobalKey _refreshIndicatorKey; + late bool _needsBootstrap; @override void initState() { @@ -74,7 +74,7 @@ class OBPostPageState extends State { } Widget _buildPost(BuildContext context, AsyncSnapshot snapshot) { - Post latestPost = snapshot.data; + Post latestPost = snapshot.data!; return OBPost( latestPost, @@ -94,7 +94,7 @@ class OBPostPageState extends State { Future _refreshPost() async { try { // This will trigger the updateSubject of the post - await _userService.getPostWithUuid(widget.post.uuid); + await _userService.getPostWithUuid(widget.post.uuid!); } catch (error) { _onError(error); } @@ -105,8 +105,8 @@ class OBPostPageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/home/pages/post_comments/post_comments_page.dart b/lib/pages/home/pages/post_comments/post_comments_page.dart index cec469d22..eea46a88e 100644 --- a/lib/pages/home/pages/post_comments/post_comments_page.dart +++ b/lib/pages/home/pages/post_comments/post_comments_page.dart @@ -28,17 +28,17 @@ import 'package:Okuna/widgets/load_more.dart'; import 'package:Okuna/services/httpie.dart'; class OBPostCommentsPage extends StatefulWidget { - final PostComment linkedPostComment; - final Post post; + final PostComment? linkedPostComment; + final Post? post; final PostCommentsPageType pageType; final bool autofocusCommentInput; - final bool showPostPreview; - final PostComment postComment; - final ValueChanged onCommentDeleted; - final ValueChanged onCommentAdded; + final bool? showPostPreview; + final PostComment? postComment; + final ValueChanged? onCommentDeleted; + final ValueChanged? onCommentAdded; OBPostCommentsPage({ - @required this.pageType, + required this.pageType, this.post, this.linkedPostComment, this.postComment, @@ -57,33 +57,33 @@ class OBPostCommentsPage extends StatefulWidget { class OBPostCommentsPageState extends OBContextualSearchBoxState with SingleTickerProviderStateMixin { - UserService _userService; - UserPreferencesService _userPreferencesService; - ToastService _toastService; - ThemeService _themeService; - DraftService _draftService; - UtilsService _utilsService; - LocalizationService _localizationService; - ThemeValueParserService _themeValueParserService; - Post _post; - AnimationController _animationController; - Animation _animation; - - double _positionTopCommentSection; - ScrollController _postCommentsScrollController; + late UserService _userService; + late UserPreferencesService _userPreferencesService; + late ToastService _toastService; + late ThemeService _themeService; + late DraftService _draftService; + late UtilsService _utilsService; + late LocalizationService _localizationService; + late ThemeValueParserService _themeValueParserService; + late Post _post; + late AnimationController _animationController; + late Animation _animation; + + late double _positionTopCommentSection; + ScrollController? _postCommentsScrollController; List _postComments = []; - bool _noMoreBottomItemsToLoad; - bool _noMoreTopItemsToLoad; - bool _needsBootstrap; - bool _shouldHideStackedLoadingScreen; - bool _startScrollWasInitialised; - PostCommentsSortType _currentSort; - FocusNode _commentInputFocusNode; - GlobalKey _refreshIndicatorKey; - OBPostCommentsPageController _commentsPageController; - Map _pageTextMap; - - DraftTextEditingController _postCommenterTextController; + late bool _noMoreBottomItemsToLoad; + late bool _noMoreTopItemsToLoad; + late bool _needsBootstrap; + late bool _shouldHideStackedLoadingScreen; + late bool _startScrollWasInitialised; + late PostCommentsSortType _currentSort; + late FocusNode _commentInputFocusNode; + late GlobalKey _refreshIndicatorKey; + late OBPostCommentsPageController _commentsPageController; + late Map _pageTextMap; + + late DraftTextEditingController _postCommenterTextController; static const int MAX_POST_TEXT_LENGTH_LIMIT = 1300; static const int MAX_COMMENT_TEXT_LENGTH_LIMIT = 500; @@ -108,14 +108,14 @@ class OBPostCommentsPageState HEIGHT_SIZED_BOX + HEIGHT_POST_DIVIDER; - CancelableOperation _refreshPostOperation; - CancelableOperation _refreshPostCommentOperation; + CancelableOperation? _refreshPostOperation; + CancelableOperation? _refreshPostCommentOperation; @override void initState() { super.initState(); - if (widget.linkedPostComment != null) _post = widget.linkedPostComment.post; - if (widget.post != null) _post = widget.post; + if (widget.linkedPostComment != null) _post = widget.linkedPostComment!.post!; + if (widget.post != null) _post = widget.post!; _needsBootstrap = true; _postComments = []; _noMoreBottomItemsToLoad = true; @@ -139,7 +139,7 @@ class OBPostCommentsPageState _bootstrapAsync(); _postCommenterTextController = DraftTextEditingController.comment( - widget.post.id, + widget.post!.id!, commentId: widget.postComment?.id, draftService: _draftService); @@ -218,7 +218,7 @@ class OBPostCommentsPageState void dispose() { super.dispose(); _animation.removeStatusListener(_onAnimationStatusChanged); - if (_refreshPostOperation != null) _refreshPostOperation.cancel(); + if (_refreshPostOperation != null) _refreshPostOperation!.cancel(); _commentsPageController.dispose(); } @@ -366,7 +366,7 @@ class OBPostCommentsPageState _commentsPageController .refreshCommentsWithCreatedPostCommentVisible(createdPostComment); if (widget.onCommentAdded != null) { - widget.onCommentAdded(createdPostComment); + widget.onCommentAdded!(createdPostComment); } } @@ -376,7 +376,7 @@ class OBPostCommentsPageState widget.showPostPreview == true) { Future.delayed(Duration(milliseconds: 0), () { if (_positionTopCommentSection == 0.0) _setPositionTopCommentSection(); - _postCommentsScrollController.animateTo( + _postCommentsScrollController?.animateTo( _positionTopCommentSection - 100.0, duration: Duration(milliseconds: 5), curve: Curves.easeIn); @@ -427,11 +427,11 @@ class OBPostCommentsPageState var postComment = _postComments[commentIndex]; var onPostCommentDeletedCallback = (PostComment comment) { _removePostCommentAtIndex(commentIndex); - if (widget.onCommentDeleted != null) widget.onCommentDeleted(postComment); + if (widget.onCommentDeleted != null) widget.onCommentDeleted!(postComment); }; if (widget.linkedPostComment != null && - postComment.id == widget.linkedPostComment.id) { + postComment.id == widget.linkedPostComment!.id) { var theme = _themeService.getActiveTheme(); var primaryColor = _themeValueParserService.parseColor(theme.primaryColor); @@ -462,7 +462,7 @@ class OBPostCommentsPageState } Widget _getPostPreview() { - if (widget.post == null || !widget.showPostPreview) { + if (widget.post == null || !(widget.showPostPreview ?? false)) { return SizedBox(); } @@ -482,9 +482,9 @@ class OBPostCommentsPageState } void _scrollToTop() { - if (!_postCommentsScrollController.hasListeners) return; + if (!_postCommentsScrollController!.hasListeners) return; Future.delayed(Duration(milliseconds: 0), () { - _postCommentsScrollController.animateTo( + _postCommentsScrollController!.animateTo( 0.0, curve: Curves.easeOut, duration: const Duration(milliseconds: 300), @@ -499,13 +499,13 @@ class OBPostCommentsPageState } Future _refreshPost() async { - if (_refreshPostOperation != null) _refreshPostOperation.cancel(); + if (_refreshPostOperation != null) _refreshPostOperation!.cancel(); try { // This will trigger the updateSubject of the post _refreshPostOperation = CancelableOperation.fromFuture( - _userService.getPostWithUuid(_post.uuid)); + _userService.getPostWithUuid(_post.uuid!)); - await _refreshPostOperation.value; + await _refreshPostOperation?.value; } catch (error) { _onError(error); } finally { @@ -515,13 +515,13 @@ class OBPostCommentsPageState Future _refreshPostComment() async { if (_refreshPostCommentOperation != null) - _refreshPostCommentOperation.cancel(); + _refreshPostCommentOperation!.cancel(); try { // This will trigger the updateSubject of the postComment _refreshPostCommentOperation = CancelableOperation.fromFuture(_userService - .getPostComment(post: widget.post, postComment: widget.postComment)); + .getPostComment(post: widget.post!, postComment: widget.postComment!)); - await _refreshPostCommentOperation.value; + await _refreshPostCommentOperation?.value; _setPositionTopCommentSection(); } catch (error) { _onError(error); @@ -588,7 +588,7 @@ class OBPostCommentsPageState void _showNoMoreTopItemsToLoadToast() { _toastService.info( - context: context, message: _pageTextMap['NO_MORE_TO_LOAD']); + context: context, message: _pageTextMap['NO_MORE_TO_LOAD']!); } void _setCurrentSortValue(PostCommentsSortType newSortValue) { @@ -599,12 +599,12 @@ class OBPostCommentsPageState void _scrollToNewComment() { if (_currentSort == PostCommentsSortType.asc) { - _postCommentsScrollController.animateTo( - _postCommentsScrollController.position.maxScrollExtent, + _postCommentsScrollController?.animateTo( + _postCommentsScrollController!.position.maxScrollExtent, duration: const Duration(milliseconds: 50), curve: Curves.easeIn); } else if (_currentSort == PostCommentsSortType.dec) { - _postCommentsScrollController.animateTo( + _postCommentsScrollController?.animateTo( _positionTopCommentSection - 100.0, duration: Duration(milliseconds: 5), curve: Curves.easeIn); @@ -616,8 +616,8 @@ class OBPostCommentsPageState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; @@ -657,15 +657,15 @@ class OBPostCommentsPageState double screenWidth = MediaQuery.of(context).size.width; - if (widget.showPostPreview && widget.post != null) { + if (widget.showPostPreview == true && widget.post != null) { if (_post.hasMediaThumbnail()) { - aspectRatio = _post.mediaWidth / _post.mediaHeight; + aspectRatio = _post.mediaWidth! / _post.mediaHeight!; finalMediaScreenHeight = screenWidth / aspectRatio; } if (_post.hasText()) { TextStyle style = TextStyle(fontSize: 16.0); - String postText = _post.text; + String postText = _post.text ?? ''; if (postText.length > MAX_POST_TEXT_LENGTH_LIMIT) postText = postText.substring(0, MAX_POST_TEXT_LENGTH_LIMIT); TextSpan text = new TextSpan(text: postText, style: style); @@ -679,13 +679,13 @@ class OBPostCommentsPageState maxWidth: screenWidth - 40.0); //padding is 20 in OBPostBodyText finalTextHeight = textPainter.size.height + TOTAL_PADDING_POST_TEXT; - if (_post.text.length > MAX_POST_TEXT_LENGTH_LIMIT) { + if (_post.text!.length > MAX_POST_TEXT_LENGTH_LIMIT) { finalTextHeight = finalTextHeight + HEIGHT_SHOW_MORE_TEXT; } } if (_post.hasCircles() || - (_post.isEncircled != null && _post.isEncircled)) { + (_post.isEncircled != null && _post.isEncircled!)) { finalPostHeight = finalPostHeight + HEIGHT_POST_CIRCLES; } @@ -694,8 +694,8 @@ class OBPostCommentsPageState finalMediaScreenHeight + TOTAL_FIXED_OFFSET_Y; - if (widget.post.text != null && - _utilsService.hasLinkToPreview(widget.post.text)) { + if (widget.post!.text != null && + _utilsService.hasLinkToPreview(widget.post!.text)) { // Approx height of link preview without image.. finalPostHeight += OBLinkPreviewState.linkPreviewHeight; } @@ -705,7 +705,7 @@ class OBPostCommentsPageState if (widget.postComment != null) { TextStyle style = TextStyle(fontSize: 16.0); - String commentText = widget.postComment.text; + String commentText = widget.postComment?.text ?? ''; if (commentText.length > MAX_COMMENT_TEXT_LENGTH_LIMIT) commentText = commentText.substring(0, MAX_COMMENT_TEXT_LENGTH_LIMIT); @@ -722,7 +722,7 @@ class OBPostCommentsPageState COMMENTS_MIN_HEIGHT + HEIGHT_COMMENTS_RELATIVE_TIMESTAMP_TEXT; - if (widget.postComment.text.length > MAX_COMMENT_TEXT_LENGTH_LIMIT) { + if (widget.postComment!.text!.length > MAX_COMMENT_TEXT_LENGTH_LIMIT) { finalCommentHeight = finalCommentHeight + HEIGHT_SHOW_MORE_TEXT; } } @@ -753,7 +753,7 @@ class OBInfinitePostCommentsLoadMoreDelegate extends LoadMoreDelegate { const SizedBox( width: 10.0, ), - Text(pageTextMap['TAP_TO_RETRY']) + Text(pageTextMap['TAP_TO_RETRY']!) ], ), ); diff --git a/lib/pages/home/pages/post_comments/post_comments_page_controller.dart b/lib/pages/home/pages/post_comments/post_comments_page_controller.dart index 1f897ac3f..f2fc933c4 100644 --- a/lib/pages/home/pages/post_comments/post_comments_page_controller.dart +++ b/lib/pages/home/pages/post_comments/post_comments_page_controller.dart @@ -26,8 +26,8 @@ class OBPostCommentsPageController { UserPreferencesService userPreferencesService; List postComments = []; - PostComment linkedPostComment; - PostComment postComment; + PostComment? linkedPostComment; + PostComment? postComment; static const LOAD_MORE_COMMENTS_COUNT = 5; static const COUNT_MIN_INCLUDING_LINKED_COMMENT = 3; @@ -35,31 +35,31 @@ class OBPostCommentsPageController { static const TOTAL_COMMENTS_IN_SLICE = COUNT_MIN_INCLUDING_LINKED_COMMENT + COUNT_MAX_AFTER_LINKED_COMMENT; - CancelableOperation _refreshCommentsOperation; - CancelableOperation _refreshCommentsSliceOperation; - CancelableOperation _refreshCommentsWithCreatedPostCommentVisibleOperation; - CancelableOperation _refreshPostOperation; - CancelableOperation _loadMoreBottomCommentsOperation; - CancelableOperation _loadMoreTopCommentsOperation; - CancelableOperation _toggleSortCommentsOperation; + CancelableOperation? _refreshCommentsOperation; + CancelableOperation? _refreshCommentsSliceOperation; + CancelableOperation? _refreshCommentsWithCreatedPostCommentVisibleOperation; + CancelableOperation? _refreshPostOperation; + CancelableOperation? _loadMoreBottomCommentsOperation; + CancelableOperation? _loadMoreTopCommentsOperation; + CancelableOperation? _toggleSortCommentsOperation; OBPostCommentsPageController({ - @required this.post, - @required this.pageType, - @required this.currentSort, - @required this.userService, - @required this.userPreferencesService, - @required this.setPostComments, - @required this.setCurrentSortValue, - @required this.setNoMoreBottomItemsToLoad, - @required this.setNoMoreTopItemsToLoad, - @required this.addPostComments, - @required this.addToStartPostComments, - @required this.showNoMoreTopItemsToLoadToast, - @required this.scrollToTop, - @required this.scrollToNewComment, - @required this.unfocusCommentInput, - @required this.onError, + required this.post, + required this.pageType, + required this.currentSort, + required this.userService, + required this.userPreferencesService, + required this.setPostComments, + required this.setCurrentSortValue, + required this.setNoMoreBottomItemsToLoad, + required this.setNoMoreTopItemsToLoad, + required this.addPostComments, + required this.addToStartPostComments, + required this.showNoMoreTopItemsToLoadToast, + required this.scrollToTop, + required this.scrollToNewComment, + required this.unfocusCommentInput, + required this.onError, this.linkedPostComment, this.postComment }) { @@ -74,8 +74,8 @@ class OBPostCommentsPageController { } } - CancelableOperation retrieveObjects({int minId, int maxId, int countMax, - int countMin, PostCommentsSortType sort}) { + CancelableOperation retrieveObjects({int? minId, int? maxId, int? countMax, + int? countMin, PostCommentsSortType? sort}) { if (this.pageType == PostCommentsPageType.comments) { return CancelableOperation.fromFuture( @@ -88,7 +88,7 @@ class OBPostCommentsPageController { } else { return CancelableOperation.fromFuture( - this.userService.getCommentRepliesForPostComment(this.post, this.postComment, + this.userService.getCommentRepliesForPostComment(this.post, this.postComment!, sort: sort, minId: minId, maxId: maxId, @@ -110,10 +110,10 @@ class OBPostCommentsPageController { } Future onWantsToRefreshComments() async { - if (_refreshCommentsOperation != null) _refreshCommentsOperation.cancel(); + if (_refreshCommentsOperation != null) _refreshCommentsOperation!.cancel(); try { _refreshCommentsOperation = this.retrieveObjects(sort: this.currentSort); - this.postComments = (await _refreshCommentsOperation.value).comments; + this.postComments = (await _refreshCommentsOperation!.value).comments; this.setPostComments(this.postComments); this.setNoMoreBottomItemsToLoad(false); this.setNoMoreTopItemsToLoad(true); @@ -131,12 +131,12 @@ class OBPostCommentsPageController { Future loadMoreTopComments() async { if (_loadMoreTopCommentsOperation != null) - _loadMoreTopCommentsOperation.cancel(); + _loadMoreTopCommentsOperation!.cancel(); if (this.postComments.length == 0) return true; List topComments; PostComment firstPost = this.postComments.first; - int firstPostId = firstPost.id; + int firstPostId = firstPost.id!; try { if (this.currentSort == PostCommentsSortType.dec) { _loadMoreTopCommentsOperation = this.retrieveObjects( @@ -150,7 +150,7 @@ class OBPostCommentsPageController { maxId: firstPostId); } - topComments = (await _loadMoreTopCommentsOperation.value).comments; + topComments = (await _loadMoreTopCommentsOperation!.value).comments; if (topComments.length < LOAD_MORE_COMMENTS_COUNT && topComments.length != 0) { @@ -174,11 +174,11 @@ class OBPostCommentsPageController { Future loadMoreBottomComments() async { if (_loadMoreBottomCommentsOperation != null) - _loadMoreBottomCommentsOperation.cancel(); + _loadMoreBottomCommentsOperation!.cancel(); if (this.postComments.length == 0 || _refreshCommentsWithCreatedPostCommentVisibleOperation != null) return true; PostComment lastPost = this.postComments.last; - int lastPostId = lastPost.id; + int lastPostId = lastPost.id!; List moreComments; try { if (this.currentSort == PostCommentsSortType.dec) { @@ -193,7 +193,7 @@ class OBPostCommentsPageController { sort: this.currentSort); } - moreComments = (await _loadMoreBottomCommentsOperation.value).comments; + moreComments = (await _loadMoreBottomCommentsOperation!.value).comments; if (moreComments.length == 0) { this.setNoMoreBottomItemsToLoad(true); @@ -212,16 +212,16 @@ class OBPostCommentsPageController { Future refreshCommentsSlice() async { if (_refreshCommentsSliceOperation != null) - _refreshCommentsSliceOperation.cancel(); + _refreshCommentsSliceOperation!.cancel(); try { _refreshCommentsSliceOperation = this.retrieveObjects( - minId: this.linkedPostComment.id, - maxId: this.linkedPostComment.id, + minId: this.linkedPostComment?.id, + maxId: this.linkedPostComment?.id, countMax: COUNT_MAX_AFTER_LINKED_COMMENT, countMin: COUNT_MIN_INCLUDING_LINKED_COMMENT, sort: this.currentSort); - this.postComments = (await _refreshCommentsSliceOperation.value).comments; + this.postComments = (await _refreshCommentsSliceOperation!.value).comments; this.setPostComments(this.postComments); this.checkIfMoreTopItemsToLoad(); this.setNoMoreBottomItemsToLoad(false); @@ -233,14 +233,14 @@ class OBPostCommentsPageController { } void checkIfMoreTopItemsToLoad() { - int linkedCommentId = this.linkedPostComment.id; + int linkedCommentId = this.linkedPostComment!.id!; Iterable listBeforeLinkedComment = []; if (this.currentSort == PostCommentsSortType.dec) { listBeforeLinkedComment = - postComments.where((comment) => comment.id > linkedCommentId); + postComments.where((comment) => comment.id! > linkedCommentId); } else if (this.currentSort == PostCommentsSortType.asc) { listBeforeLinkedComment = - postComments.where((comment) => comment.id < linkedCommentId); + postComments.where((comment) => comment.id! < linkedCommentId); } if (listBeforeLinkedComment.length < 2) { this.setNoMoreTopItemsToLoad(true); @@ -250,10 +250,10 @@ class OBPostCommentsPageController { void refreshCommentsWithCreatedPostCommentVisible( PostComment createdPostComment) async { if (_refreshCommentsWithCreatedPostCommentVisibleOperation != null) - _refreshCommentsWithCreatedPostCommentVisibleOperation.cancel(); + _refreshCommentsWithCreatedPostCommentVisibleOperation!.cancel(); this.unfocusCommentInput(); List comments; - int createdCommentId = createdPostComment.id; + int createdCommentId = createdPostComment.id!; try { if (this.currentSort == PostCommentsSortType.dec) { _refreshCommentsWithCreatedPostCommentVisibleOperation = this.retrieveObjects( @@ -271,7 +271,7 @@ class OBPostCommentsPageController { this.setNoMoreBottomItemsToLoad(false); } comments = - (await _refreshCommentsWithCreatedPostCommentVisibleOperation.value) + (await _refreshCommentsWithCreatedPostCommentVisibleOperation!.value) .comments; this.postComments = comments; this.setPostComments(this.postComments); @@ -293,19 +293,19 @@ class OBPostCommentsPageController { } void dispose() { - if (_refreshCommentsOperation != null) _refreshCommentsOperation.cancel(); + if (_refreshCommentsOperation != null) _refreshCommentsOperation!.cancel(); if (_refreshCommentsSliceOperation != null) - _refreshCommentsSliceOperation.cancel(); + _refreshCommentsSliceOperation!.cancel(); if (_loadMoreBottomCommentsOperation != null) - _loadMoreBottomCommentsOperation.cancel(); - if (_refreshPostOperation != null) _refreshPostOperation.cancel(); + _loadMoreBottomCommentsOperation!.cancel(); + if (_refreshPostOperation != null) _refreshPostOperation!.cancel(); if (_toggleSortCommentsOperation != null) - _toggleSortCommentsOperation.cancel(); + _toggleSortCommentsOperation!.cancel(); if (_loadMoreTopCommentsOperation != null) - _loadMoreTopCommentsOperation.cancel(); + _loadMoreTopCommentsOperation!.cancel(); if (_refreshCommentsWithCreatedPostCommentVisibleOperation != null) - _refreshCommentsWithCreatedPostCommentVisibleOperation.cancel(); + _refreshCommentsWithCreatedPostCommentVisibleOperation!.cancel(); } } -enum PostCommentsPageType { replies, comments } \ No newline at end of file +enum PostCommentsPageType { replies, comments } diff --git a/lib/pages/home/pages/post_comments/widgets/post_comment/post_comment.dart b/lib/pages/home/pages/post_comments/widgets/post_comment/post_comment.dart index e6cdbc14b..31c24e01a 100644 --- a/lib/pages/home/pages/post_comments/widgets/post_comment/post_comment.dart +++ b/lib/pages/home/pages/post_comments/widgets/post_comment/post_comment.dart @@ -14,10 +14,10 @@ import 'package:async/async.dart'; import 'package:flutter/material.dart'; class OBPostComment extends StatefulWidget { - final PostComment postComment; - final Post post; - final ValueChanged onPostCommentDeleted; - final ValueChanged onPostCommentReported; + final PostComment? postComment; + final Post? post; + final ValueChanged? onPostCommentDeleted; + final ValueChanged? onPostCommentReported; final bool showReplies; final bool showActions; final bool showReplyAction; @@ -25,11 +25,11 @@ class OBPostComment extends StatefulWidget { final EdgeInsets padding; OBPostComment({ - @required this.post, - @required this.postComment, + required this.post, + required this.postComment, this.onPostCommentDeleted, this.onPostCommentReported, - Key key, + Key? key, this.showReplies = true, this.showActions = true, this.showReactions = true, @@ -44,24 +44,24 @@ class OBPostComment extends StatefulWidget { } class OBPostCommentState extends State { - NavigationService _navigationService; - UserPreferencesService _userPreferencesService; - int _repliesCount; - List _replies; + late NavigationService _navigationService; + late UserPreferencesService _userPreferencesService; + int? _repliesCount; + late List _replies; - CancelableOperation _requestOperation; + CancelableOperation? _requestOperation; @override void initState() { super.initState(); - _repliesCount = widget.postComment.repliesCount; - _replies = widget.postComment.getPostCommentReplies(); + _repliesCount = widget.postComment?.repliesCount ?? 0; + _replies = widget.postComment?.getPostCommentReplies() ?? []; } @override void dispose() { super.dispose(); - if (_requestOperation != null) _requestOperation.cancel(); + if (_requestOperation != null) _requestOperation!.cancel(); } @override @@ -71,28 +71,28 @@ class OBPostCommentState extends State { _userPreferencesService = provider.userPreferencesService; return StreamBuilder( - key: Key('OBPostCommentTile#${widget.postComment.id}'), - stream: widget.postComment.updateSubject, + key: Key('OBPostCommentTile#${widget.postComment!.id}'), + stream: widget.postComment!.updateSubject, initialData: widget.postComment, builder: (BuildContext context, AsyncSnapshot snapshot) { - PostComment postComment = snapshot.data; - User commenter = postComment.commenter; + PostComment postComment = snapshot.data!; + User commenter = postComment.commenter!; List commentBodyColumnItems = [ OBPostCommentCommenterIdentifier( - post: widget.post, - postComment: widget.postComment, + post: widget.post!, + postComment: widget.postComment!, onUsernamePressed: _onPostCommenterPressed, ), const SizedBox( height: 5, ), OBPostCommentText( - widget.postComment, - widget.post, + widget.postComment!, + widget.post!, onUsernamePressed: () { _navigationService.navigateToUserProfile( - user: widget.postComment.commenter, context: context); + user: widget.postComment!.commenter!, context: context); }, ), ]; @@ -100,8 +100,8 @@ class OBPostCommentState extends State { if (widget.showReactions) { commentBodyColumnItems.add( OBPostCommentReactions( - postComment: widget.postComment, - post: widget.post, + postComment: widget.postComment!, + post: widget.post!, ), ); } @@ -109,8 +109,8 @@ class OBPostCommentState extends State { if (widget.showActions) { commentBodyColumnItems.addAll([ OBPostCommentActions( - post: widget.post, - postComment: widget.postComment, + post: widget.post!, + postComment: widget.postComment!, onReplyDeleted: _onReplyDeleted, onReplyAdded: _onReplyAdded, onPostCommentReported: widget.onPostCommentReported, @@ -120,7 +120,7 @@ class OBPostCommentState extends State { ]); } - if (widget.showReplies && _repliesCount != null && _repliesCount > 0) + if (widget.showReplies && _repliesCount != null && _repliesCount! > 0) commentBodyColumnItems.add(_buildPostCommentReplies()); return Column( @@ -161,10 +161,10 @@ class OBPostCommentState extends State { shrinkWrap: true, physics: const ClampingScrollPhysics(), padding: EdgeInsets.all(0), - itemCount: widget.postComment.getPostCommentReplies().length, + itemCount: widget.postComment!.getPostCommentReplies().length, itemBuilder: (context, index) { PostComment reply = - widget.postComment.getPostCommentReplies()[index]; + widget.postComment!.getPostCommentReplies()[index]; return OBPostComment( key: Key('postCommentReply#${reply.id}'), @@ -180,7 +180,7 @@ class OBPostCommentState extends State { } Widget _buildViewAllReplies() { - if (!widget.postComment.hasReplies() || + if (!widget.postComment!.hasReplies() || (_repliesCount == _replies.length)) { return SizedBox(); } @@ -196,8 +196,8 @@ class OBPostCommentState extends State { void _onWantsToViewAllReplies() { _navigationService.navigateToPostCommentReplies( - post: widget.post, - postComment: widget.postComment, + post: widget.post!, + postComment: widget.postComment!, context: context, onReplyDeleted: _onReplyDeleted, onReplyAdded: _onReplyAdded); @@ -205,7 +205,10 @@ class OBPostCommentState extends State { void _onReplyDeleted(PostComment postCommentReply) async { setState(() { - _repliesCount -= 1; + if (_repliesCount != null) { + _repliesCount = _repliesCount! - 1; + } + _replies.removeWhere((reply) => reply.id == postCommentReply.id); }); } @@ -219,13 +222,16 @@ class OBPostCommentState extends State { } else if (_repliesCount == _replies.length) { _replies.add(postCommentReply); } - _repliesCount += 1; + + if (_repliesCount != null) { + _repliesCount = _repliesCount! + 1; + } }); } void _onPostCommenterPressed() { _navigationService.navigateToUserProfile( - user: widget.postComment.commenter, context: context); + user: widget.postComment!.commenter!, context: context); } } diff --git a/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_actions.dart b/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_actions.dart index df788bc9d..222be8f69 100644 --- a/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_actions.dart +++ b/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_actions.dart @@ -18,18 +18,18 @@ import 'package:async/async.dart'; import 'package:flutter/material.dart'; class OBPostCommentActions extends StatefulWidget { - final ValueChanged onReplyDeleted; - final ValueChanged onReplyAdded; - final ValueChanged onPostCommentDeleted; - final ValueChanged onPostCommentReported; + final ValueChanged? onReplyDeleted; + final ValueChanged? onReplyAdded; + final ValueChanged? onPostCommentDeleted; + final ValueChanged? onPostCommentReported; final Post post; final PostComment postComment; final bool showReplyAction; const OBPostCommentActions( - {Key key, - @required this.post, - @required this.postComment, + {Key? key, + required this.post, + required this.postComment, this.onReplyDeleted, this.onReplyAdded, this.onPostCommentDeleted, @@ -44,19 +44,19 @@ class OBPostCommentActions extends StatefulWidget { } class OBPostCommentActionsState extends State { - ModalService _modalService; - NavigationService _navigationService; - BottomSheetService _bottomSheetService; - UserService _userService; - ToastService _toastService; - ThemeService _themeService; - LocalizationService _localizationService; - ThemeValueParserService _themeValueParserService; + late ModalService _modalService; + late NavigationService _navigationService; + late BottomSheetService _bottomSheetService; + late UserService _userService; + late ToastService _toastService; + late ThemeService _themeService; + late LocalizationService _localizationService; + late ThemeValueParserService _themeValueParserService; - bool _requestInProgress; - CancelableOperation _requestOperation; + late bool _requestInProgress; + CancelableOperation? _requestOperation; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -86,7 +86,7 @@ class OBPostCommentActionsState extends State { if (widget.showReplyAction && _userService - .getLoggedInUser() + .getLoggedInUser()! .canReplyPostComment(widget.postComment)) { actionItems.add(_buildReplyButton()); } @@ -126,16 +126,16 @@ class OBPostCommentActionsState extends State { initialData: widget.postComment, builder: (BuildContext context, AsyncSnapshot snapshot) { - PostComment postComment = snapshot.data; + PostComment postComment = snapshot.data!; - PostCommentReaction reaction = postComment.reaction; + PostCommentReaction? reaction = postComment.reaction; bool hasReaction = reaction != null; OBTheme activeTheme = _themeService.getActiveTheme(); return hasReaction ? OBText( - reaction.getEmojiKeyword(), + reaction.getEmojiKeyword()!, textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, @@ -171,11 +171,11 @@ class OBPostCommentActionsState extends State { @override void dispose() { super.dispose(); - if (_requestOperation != null) _requestOperation.cancel(); + if (_requestOperation != null) _requestOperation!.cancel(); } void _replyToPostComment() async { - PostComment comment = await _modalService.openExpandedReplyCommenter( + PostComment? comment = await _modalService.openExpandedReplyCommenter( context: context, post: widget.post, postComment: widget.postComment, @@ -208,10 +208,10 @@ class OBPostCommentActionsState extends State { _requestOperation = CancelableOperation.fromFuture( _userService.deletePostCommentReaction( postComment: widget.postComment, - postCommentReaction: widget.postComment.reaction, + postCommentReaction: widget.postComment.reaction!, post: widget.post)); - await _requestOperation.value; + await _requestOperation?.value; widget.postComment.clearReaction(); } catch (error) { _onError(error); @@ -241,8 +241,8 @@ class OBPostCommentActionsState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_commenter_identifier.dart b/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_commenter_identifier.dart index b0ea4865a..acff2b4de 100644 --- a/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_commenter_identifier.dart +++ b/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_commenter_identifier.dart @@ -17,10 +17,10 @@ class OBPostCommentCommenterIdentifier extends StatelessWidget { static int postCommentMaxVisibleLength = 500; OBPostCommentCommenterIdentifier({ - Key key, - @required this.onUsernamePressed, - @required this.postComment, - @required this.post, + Key? key, + required this.onUsernamePressed, + required this.postComment, + required this.post, }) : super(key: key); @override @@ -35,14 +35,14 @@ class OBPostCommentCommenterIdentifier extends StatelessWidget { stream: themeService.themeChange, initialData: themeService.getActiveTheme(), builder: (BuildContext context, AsyncSnapshot snapshot) { - OBTheme theme = snapshot.data; + OBTheme theme = snapshot.data!; Color secondaryTextColor = themeValueParserService.parseColor(theme.secondaryTextColor); - String commenterUsername = postComment.commenter.username; - String commenterName = postComment.commenter.getProfileName(); - String created = utilsService.timeAgo(postComment.created, localizationService); + String commenterUsername = postComment.commenter!.username!; + String commenterName = postComment.commenter!.getProfileName()!; + String created = utilsService.timeAgo(postComment.created!, localizationService); return Opacity( opacity: 0.8, @@ -80,14 +80,14 @@ class OBPostCommentCommenterIdentifier extends StatelessWidget { } Widget _buildBadge() { - User postCommenter = postComment.commenter; + User postCommenter = postComment.commenter!; List badges = []; if (postCommenter.hasProfileBadges()) badges.add(_buildProfileBadge()); if (post.hasCommunity()) { - Community postCommunity = post.community; + Community postCommunity = post.community!; bool isCommunityAdministrator = postCommenter.isAdministratorOfCommunity(postCommunity); @@ -132,7 +132,7 @@ class OBPostCommentCommenterIdentifier extends StatelessWidget { return Padding( padding: const EdgeInsets.symmetric(horizontal: 1), child: OBUserBadge( - badge: postComment.commenter.getDisplayedProfileBadge(), + badge: postComment.commenter!.getDisplayedProfileBadge(), size: OBUserBadgeSize.small), ); } diff --git a/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_reactions.dart b/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_reactions.dart index 58e35b3e0..a6863b5d8 100644 --- a/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_reactions.dart +++ b/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_reactions.dart @@ -15,7 +15,7 @@ class OBPostCommentReactions extends StatefulWidget { final PostComment postComment; final Post post; - OBPostCommentReactions({@required this.post, @required this.postComment}); + OBPostCommentReactions({required this.post, required this.postComment}); @override State createState() { @@ -24,9 +24,9 @@ class OBPostCommentReactions extends StatefulWidget { } class OBPostCommentReactionsState extends State { - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; @override void initState() { @@ -46,8 +46,8 @@ class OBPostCommentReactionsState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var postComment = snapshot.data; - List emojiCounts = - postComment.reactionsEmojiCounts?.counts ?? []; + List emojiCounts = + postComment?.reactionsEmojiCounts?.counts ?? []; if (emojiCounts.isEmpty) return const SizedBox(); @@ -64,12 +64,12 @@ class OBPostCommentReactionsState extends State { ); }, itemBuilder: (BuildContext context, int index) { - ReactionsEmojiCount emojiCount = emojiCounts[index]; + ReactionsEmojiCount emojiCount = emojiCounts[index]!; return OBEmojiReactionButton( emojiCount, size: OBEmojiReactionButtonSize.small, - reacted: widget.postComment.isReactionEmoji(emojiCount.emoji), + reacted: widget.postComment.isReactionEmoji(emojiCount.emoji!), onPressed: _onEmojiReactionCountPressed, onLongPressed: (pressedEmojiCount) { _navigationService.navigateToPostCommentReactions( @@ -89,22 +89,23 @@ class OBPostCommentReactionsState extends State { void _onEmojiReactionCountPressed( ReactionsEmojiCount pressedEmojiCount) async { - bool isReactionEmoji = - widget.postComment.isReactionEmoji(pressedEmojiCount.emoji); + bool isReactionEmoji = pressedEmojiCount.emoji == null + ? false + : widget.postComment.isReactionEmoji(pressedEmojiCount.emoji!); if (isReactionEmoji) { await _deleteReaction(); widget.postComment.clearReaction(); } else { // React - PostCommentReaction newPostCommentReaction = - await _reactToPostComment(pressedEmojiCount.emoji); + PostCommentReaction? newPostCommentReaction = + await _reactToPostComment(pressedEmojiCount.emoji!); widget.postComment.setReaction(newPostCommentReaction); } } - Future _reactToPostComment(Emoji emoji) async { - PostCommentReaction postCommentReaction; + Future _reactToPostComment(Emoji emoji) async { + PostCommentReaction? postCommentReaction; try { postCommentReaction = await _userService.reactToPostComment( post: widget.post, postComment: widget.postComment, emoji: emoji); @@ -118,7 +119,7 @@ class OBPostCommentReactionsState extends State { Future _deleteReaction() async { try { await _userService.deletePostCommentReaction( - postCommentReaction: widget.postComment.reaction, + postCommentReaction: widget.postComment.reaction!, post: widget.post, postComment: widget.postComment); } catch (error) { @@ -131,8 +132,8 @@ class OBPostCommentReactionsState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_text.dart b/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_text.dart index 7d6e3317a..774750489 100644 --- a/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_text.dart +++ b/lib/pages/home/pages/post_comments/widgets/post_comment/widgets/post_comment_text.dart @@ -15,11 +15,11 @@ import 'package:flutter/services.dart'; class OBPostCommentText extends StatefulWidget { final PostComment postComment; final Post post; - final VoidCallback onUsernamePressed; + final VoidCallback? onUsernamePressed; final int postCommentMaxVisibleLength = 500; OBPostCommentText(this.postComment, this.post, - {Key key, this.onUsernamePressed}) + {Key? key, this.onUsernamePressed}) : super(key: key); @override @@ -29,11 +29,11 @@ class OBPostCommentText extends StatefulWidget { } class OBPostCommentTextState extends State { - String _translatedText; - bool _requestInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + String? _translatedText; + late bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; @override void initState() { @@ -66,7 +66,7 @@ class OBPostCommentTextState extends State { context: context, type: ToastType.info); }, - child: _getActionableSmartText(widget.postComment.isEdited), + child: _getActionableSmartText(widget.postComment.isEdited ?? false), ), ), ], @@ -86,7 +86,7 @@ class OBPostCommentTextState extends State { )); } - User loggedInUser = _userService.getLoggedInUser(); + User? loggedInUser = _userService.getLoggedInUser(); if (loggedInUser != null && loggedInUser.canTranslatePostComment(widget.postComment, widget.post)) { return GestureDetector( @@ -135,7 +135,7 @@ class OBPostCommentTextState extends State { maxlength: widget.postCommentMaxVisibleLength, getChild: _getPostCommentTranslateButton, hashtagsMap: widget.postComment.hashtagsMap, - links: widget.post.postLinksList.postLinks, + links: widget.post.postLinksList?.postLinks, ); } else { return OBCollapsibleSmartText( @@ -144,7 +144,7 @@ class OBPostCommentTextState extends State { maxlength: widget.postCommentMaxVisibleLength, getChild: _getPostCommentTranslateButton, hashtagsMap: widget.postComment.hashtagsMap, - links: widget.post.postLinksList.postLinks, + links: widget.post.postLinksList?.postLinks, ); } } @@ -154,8 +154,8 @@ class OBPostCommentTextState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; @@ -168,7 +168,7 @@ class OBPostCommentTextState extends State { }); } - void _setPostCommentTranslatedText(String newText) { + void _setPostCommentTranslatedText(String? newText) { setState(() { _translatedText = newText; }); diff --git a/lib/pages/home/pages/post_comments/widgets/post_commenter.dart b/lib/pages/home/pages/post_comments/widgets/post_commenter.dart index bdf4d35c8..b7ef9b409 100644 --- a/lib/pages/home/pages/post_comments/widgets/post_commenter.dart +++ b/lib/pages/home/pages/post_comments/widgets/post_commenter.dart @@ -18,11 +18,11 @@ import 'package:Okuna/services/httpie.dart'; class OBPostCommenter extends StatefulWidget { final Post post; - final PostComment postComment; + final PostComment? postComment; final bool autofocus; - final FocusNode commentTextFieldFocusNode; - final ValueChanged onPostCommentCreated; - final VoidCallback onPostCommentWillBeCreated; + final FocusNode? commentTextFieldFocusNode; + final ValueChanged? onPostCommentCreated; + final VoidCallback? onPostCommentWillBeCreated; final DraftTextEditingController textController; OBPostCommenter(this.post, @@ -31,7 +31,7 @@ class OBPostCommenter extends StatefulWidget { this.commentTextFieldFocusNode, this.onPostCommentCreated, this.onPostCommentWillBeCreated, - @required this.textController}); + required this.textController}); @override State createState() { @@ -40,19 +40,19 @@ class OBPostCommenter extends StatefulWidget { } class OBPostCommenterState extends State { - bool _commentInProgress; - bool _formWasSubmitted; - bool _needsBootstrap; + late bool _commentInProgress; + late bool _formWasSubmitted; + late bool _needsBootstrap; - int _charactersCount; - bool _isMultiline; + late int _charactersCount; + late bool _isMultiline; - UserService _userService; - ToastService _toastService; - ValidationService _validationService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late ValidationService _validationService; + late LocalizationService _localizationService; - CancelableOperation _submitFormOperation; + CancelableOperation? _submitFormOperation; final _formKey = GlobalKey(); @@ -69,7 +69,7 @@ class OBPostCommenterState extends State { @override void dispose() { super.dispose(); - if (_submitFormOperation != null) _submitFormOperation.cancel(); + if (_submitFormOperation != null) _submitFormOperation!.cancel(); } @override @@ -158,12 +158,12 @@ class OBPostCommenterState extends State { ); } - Widget _buildTextFormField(int maxLines, TextStyle style) { + Widget _buildTextFormField(int? maxLines, TextStyle style) { EdgeInsetsGeometry inputContentPadding = EdgeInsets.symmetric(vertical: 8.0, horizontal: 10); bool autofocus = widget.autofocus; - FocusNode focusNode = widget.commentTextFieldFocusNode ?? null; + FocusNode? focusNode = widget.commentTextFieldFocusNode ?? null; return OBTextFormField( controller: widget.textController, @@ -180,7 +180,7 @@ class OBPostCommenterState extends State { hasBorder: false, autofocus: autofocus, autocorrect: true, - validator: (String comment) { + validator: (String? comment) { if (!_formWasSubmitted) return null; return _validationService.validatePostComment(widget.textController.text); }, @@ -188,7 +188,7 @@ class OBPostCommenterState extends State { } void _submitForm() async { - if (_submitFormOperation != null) _submitFormOperation.cancel(); + if (_submitFormOperation != null) _submitFormOperation!.cancel(); _setFormWasSubmitted(true); bool formIsValid = _validateForm(); @@ -197,22 +197,25 @@ class OBPostCommenterState extends State { _setCommentInProgress(true); try { - await (widget.onPostCommentWillBeCreated != null - ? widget.onPostCommentWillBeCreated() - : Future.value()); + if (widget.onPostCommentWillBeCreated != null) { + widget.onPostCommentWillBeCreated!(); + } else { + await Future.value(); + } + String commentText = widget.textController.text; if (widget.postComment != null) { _submitFormOperation = CancelableOperation.fromFuture( _userService.replyPostComment( text: commentText, post: widget.post, - postComment: widget.postComment)); + postComment: widget.postComment!)); } else { _submitFormOperation = CancelableOperation.fromFuture( _userService.commentPost(text: commentText, post: widget.post)); } - PostComment createdPostComment = await _submitFormOperation.value; + PostComment createdPostComment = await _submitFormOperation?.value; if (createdPostComment.parentComment == null) widget.post.incrementCommentsCount(); widget.textController.clear(); @@ -220,7 +223,7 @@ class OBPostCommenterState extends State { _validateForm(); _setCommentInProgress(false); if (widget.onPostCommentCreated != null) - widget.onPostCommentCreated(createdPostComment); + widget.onPostCommentCreated!(createdPostComment); } catch (error) { _onError(error); } finally { @@ -239,7 +242,7 @@ class OBPostCommenterState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } void _onError(error) async { @@ -247,8 +250,8 @@ class OBPostCommenterState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error( message: _localizationService.trans('error__unknown_error'), diff --git a/lib/pages/home/pages/post_comments/widgets/post_comments_header_bar.dart b/lib/pages/home/pages/post_comments/widgets/post_comments_header_bar.dart index cee72b59f..abd2925bc 100644 --- a/lib/pages/home/pages/post_comments/widgets/post_comments_header_bar.dart +++ b/lib/pages/home/pages/post_comments/widgets/post_comments_header_bar.dart @@ -20,13 +20,13 @@ class OBPostCommentsHeaderBar extends StatelessWidget { VoidCallback onWantsToRefreshComments; OBPostCommentsHeaderBar({ - @required this.pageType, - @required this.noMoreTopItemsToLoad, - @required this.postComments, - @required this.currentSort, - @required this.onWantsToToggleSortComments, - @required this.loadMoreTopComments, - @required this.onWantsToRefreshComments, + required this.pageType, + required this.noMoreTopItemsToLoad, + required this.postComments, + required this.currentSort, + required this.onWantsToToggleSortComments, + required this.loadMoreTopComments, + required this.onWantsToRefreshComments, }); @override @@ -36,7 +36,7 @@ class OBPostCommentsHeaderBar extends StatelessWidget { LocalizationService _localizationService = provider.localizationService; ThemeValueParserService _themeValueParserService = provider.themeValueParserService; var theme = _themeService.getActiveTheme(); - Map _pageTextMap; + late Map _pageTextMap; if (this.pageType == PostCommentsPageType.comments) { _pageTextMap = this.getPageCommentsMap(_localizationService); } else { @@ -56,9 +56,9 @@ class OBPostCommentsHeaderBar extends StatelessWidget { child: OBSecondaryText( this.postComments.length > 0 ? this.currentSort == PostCommentsSortType.dec - ? _pageTextMap['NEWEST'] - : _pageTextMap['OLDEST'] - : _pageTextMap['BE_THE_FIRST'], + ? _pageTextMap['NEWEST']! + : _pageTextMap['OLDEST']! + : _pageTextMap['BE_THE_FIRST']!, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0), ), ), @@ -68,8 +68,8 @@ class OBPostCommentsHeaderBar extends StatelessWidget { child: OBText( this.postComments.length > 0 ? this.currentSort == PostCommentsSortType.dec - ? _pageTextMap['SEE_OLDEST'] - : _pageTextMap['SEE_NEWEST'] + ? _pageTextMap['SEE_OLDEST']! + : _pageTextMap['SEE_NEWEST']! : '', overflow: TextOverflow.ellipsis, style: TextStyle( @@ -98,8 +98,8 @@ class OBPostCommentsHeaderBar extends StatelessWidget { const SizedBox(width: 10.0), OBText( this.currentSort == PostCommentsSortType.dec - ? _pageTextMap['NEWER'] - : _pageTextMap['OLDER'], + ? _pageTextMap['NEWER']! + : _pageTextMap['OLDER']!, style: TextStyle(fontWeight: FontWeight.bold), ), ], @@ -111,8 +111,8 @@ class OBPostCommentsHeaderBar extends StatelessWidget { child: FlatButton( child: OBText( this.currentSort == PostCommentsSortType.dec - ? _pageTextMap['VIEW_NEWEST'] - : _pageTextMap['VIEW_OLDEST'], + ? _pageTextMap['VIEW_NEWEST']! + : _pageTextMap['VIEW_OLDEST']!, style: TextStyle( color: _themeValueParserService .parseGradient(theme.primaryAccentColor) diff --git a/lib/pages/home/pages/post_comments/widgets/post_preview.dart b/lib/pages/home/pages/post_comments/widgets/post_preview.dart index 4bb18a53b..fffef36af 100644 --- a/lib/pages/home/pages/post_comments/widgets/post_preview.dart +++ b/lib/pages/home/pages/post_comments/widgets/post_preview.dart @@ -11,12 +11,12 @@ import 'package:flutter/material.dart'; class OBPostPreview extends StatelessWidget { final Post post; - final Function(Post) onPostDeleted; - final VoidCallback focusCommentInput; + final Function(Post)? onPostDeleted; + final VoidCallback? focusCommentInput; final bool showViewAllCommentsAction; OBPostPreview( - {this.post, + {required this.post, this.onPostDeleted, this.focusCommentInput, this.showViewAllCommentsAction = true}); diff --git a/lib/pages/home/pages/profile/pages/edit_profile/manage_profile.dart b/lib/pages/home/pages/profile/pages/edit_profile/manage_profile.dart index 74c4baae0..20ce067b4 100644 --- a/lib/pages/home/pages/profile/pages/edit_profile/manage_profile.dart +++ b/lib/pages/home/pages/profile/pages/edit_profile/manage_profile.dart @@ -18,12 +18,12 @@ import 'package:flutter/material.dart'; class OBManageProfilePage extends StatefulWidget { final User user; - final VoidCallback onUserProfileUpdated; - final ValueChanged onExcludedCommunityRemoved; - final ValueChanged> onExcludedCommunitiesAdded; + final VoidCallback? onUserProfileUpdated; + final ValueChanged? onExcludedCommunityRemoved; + final ValueChanged>? onExcludedCommunitiesAdded; const OBManageProfilePage(this.user, - {Key key, + {Key? key, this.onUserProfileUpdated, this.onExcludedCommunityRemoved, this.onExcludedCommunitiesAdded}) @@ -40,12 +40,12 @@ class OBManageProfilePageState extends State { static EdgeInsetsGeometry inputContentPadding = EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0); - LocalizationService _localizationService; - NavigationService _navigationService; - UserService _userService; + late LocalizationService _localizationService; + late NavigationService _navigationService; + late UserService _userService; - bool _communityPostsVisible; - bool _isFirstBuild; + late bool _communityPostsVisible; + late bool _isFirstBuild; @override void initState() { @@ -54,7 +54,7 @@ class OBManageProfilePageState extends State { _communityPostsVisible = widget.user.getProfileCommunityPostsVisible(); - WidgetsBinding.instance.addPostFrameCallback((_) => _isFirstBuild = false); + WidgetsBinding.instance?.addPostFrameCallback((_) => _isFirstBuild = false); } @override @@ -110,7 +110,7 @@ class OBManageProfilePageState extends State { height: 20, ), StreamBuilder( - stream: _userService.getLoggedInUser().updateSubject, + stream: _userService.getLoggedInUser()?.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data?.visibility != UserVisibility.private) @@ -144,7 +144,7 @@ class OBManageProfilePageState extends State { }); } - Widget _buildNavigationBar() { + PreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: _localizationService.user__manage_profile_title, ); diff --git a/lib/pages/home/pages/profile/pages/edit_profile/modals/edit_profile.dart b/lib/pages/home/pages/profile/pages/edit_profile/modals/edit_profile.dart index db4efed7e..0c0b6e0d1 100644 --- a/lib/pages/home/pages/profile/pages/edit_profile/modals/edit_profile.dart +++ b/lib/pages/home/pages/profile/pages/edit_profile/modals/edit_profile.dart @@ -20,9 +20,9 @@ import 'package:flutter/material.dart'; class OBEditProfileModal extends StatefulWidget { final User user; - final VoidCallback onUserProfileUpdated; + final VoidCallback? onUserProfileUpdated; - const OBEditProfileModal(this.user, {Key key, this.onUserProfileUpdated}) + const OBEditProfileModal(this.user, {Key? key, this.onUserProfileUpdated}) : super(key: key); @override @@ -36,27 +36,27 @@ class OBEditProfileModalState extends State { static EdgeInsetsGeometry inputContentPadding = EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0); - UserService _userService; - ToastService _toastService; - MediaService _imagePickerService; - ValidationService _validationService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late MediaService _imagePickerService; + late ValidationService _validationService; + late LocalizationService _localizationService; - bool _requestInProgress; - bool _formWasSubmitted; - String _takenUsername; + late bool _requestInProgress; + late bool _formWasSubmitted; + String? _takenUsername; final _formKey = GlobalKey(); - TextEditingController _usernameController; - TextEditingController _nameController; - TextEditingController _urlController; - TextEditingController _locationController; - TextEditingController _bioController; - String _avatarUrl; - String _coverUrl; - File _avatarFile; - File _coverFile; + late TextEditingController _usernameController; + late TextEditingController _nameController; + late TextEditingController _urlController; + late TextEditingController _locationController; + late TextEditingController _bioController; + String? _avatarUrl; + String? _coverUrl; + File? _avatarFile; + File? _coverFile; @override void initState() { @@ -131,13 +131,13 @@ class OBEditProfileModalState extends State { children: [ OBTextFormField( controller: _usernameController, - validator: (String username) { + validator: (String? username) { if (!_formWasSubmitted) return null; if (_takenUsername != null && _takenUsername == username) return _localizationService .user__edit_profile_user_name_taken( - _takenUsername); + _takenUsername!); return _validationService .validateUserUsername(username); }, @@ -149,7 +149,7 @@ class OBEditProfileModalState extends State { ), OBTextFormField( controller: _nameController, - validator: (String profileName) { + validator: (String? profileName) { if (!_formWasSubmitted) return null; return _validationService .validateUserProfileName(profileName); @@ -162,7 +162,7 @@ class OBEditProfileModalState extends State { ), OBTextFormField( controller: _urlController, - validator: (String profileUrl) { + validator: (String? profileUrl) { if (!_formWasSubmitted) return null; return _validationService .validateUserProfileUrl(profileUrl); @@ -175,7 +175,7 @@ class OBEditProfileModalState extends State { ), OBTextFormField( controller: _locationController, - validator: (String profileLocation) { + validator: (String? profileLocation) { if (!_formWasSubmitted) return null; return _validationService .validateUserProfileLocation(profileLocation); @@ -188,7 +188,7 @@ class OBEditProfileModalState extends State { ), OBTextFormField( controller: _bioController, - validator: (String profileBio) { + validator: (String? profileBio) { if (!_formWasSubmitted) return null; return _validationService .validateUserProfileBio(profileBio); @@ -214,7 +214,7 @@ class OBEditProfileModalState extends State { )); } - Widget _buildNavigationBar() { + PreferredSizeWidget _buildNavigationBar() { bool newPostButtonIsEnabled = true; return OBThemedNavigationBar( @@ -304,7 +304,7 @@ class OBEditProfileModalState extends State { ); } - void _showImageBottomSheet({@required OBImageType imageType}) { + void _showImageBottomSheet({required OBImageType imageType}) { ToastService toastService = OpenbookProvider.of(context).toastService; showModalBottomSheet( @@ -368,7 +368,7 @@ class OBEditProfileModalState extends State { }); } - void _onUserImageSelected({File image, OBImageType imageType}) { + void _onUserImageSelected({File? image, OBImageType? imageType}) { if (image != null) { switch (imageType) { case OBImageType.avatar: @@ -384,7 +384,7 @@ class OBEditProfileModalState extends State { } bool _validateForm() { - return _formKey.currentState.validate(); + return _formKey.currentState?.validate() ?? false; } void _submitForm() async { @@ -408,7 +408,7 @@ class OBEditProfileModalState extends State { bio: _bioController.text, location: _locationController.text, ); - if (widget.onUserProfileUpdated != null) widget.onUserProfileUpdated(); + if (widget.onUserProfileUpdated != null) widget.onUserProfileUpdated!(); Navigator.of(context).pop(); } catch (error) { _onError(error); @@ -422,8 +422,8 @@ class OBEditProfileModalState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -452,31 +452,31 @@ class OBEditProfileModalState extends State { }); } - void _setAvatarUrl(String avatarUrl) { + void _setAvatarUrl(String? avatarUrl) { setState(() { _avatarUrl = avatarUrl; }); } - void _setCoverUrl(String coverUrl) { + void _setCoverUrl(String? coverUrl) { setState(() { _coverUrl = coverUrl; }); } - void _setAvatarFile(File avatarFile) { + void _setAvatarFile(File? avatarFile) { setState(() { _avatarFile = avatarFile; }); } - void _setCoverFile(File coverFile) { + void _setCoverFile(File? coverFile) { setState(() { _coverFile = coverFile; }); } - void _setTakenUsername(String takenUsername) { + void _setTakenUsername(String? takenUsername) { setState(() { _takenUsername = takenUsername; }); diff --git a/lib/pages/home/pages/profile/pages/edit_profile/pages/profile_posts_excluded_communities/modals/exclude_community_from_profile_posts.dart b/lib/pages/home/pages/profile/pages/edit_profile/pages/profile_posts_excluded_communities/modals/exclude_community_from_profile_posts.dart index 4b40f7750..39da96952 100644 --- a/lib/pages/home/pages/profile/pages/edit_profile/pages/profile_posts_excluded_communities/modals/exclude_community_from_profile_posts.dart +++ b/lib/pages/home/pages/profile/pages/edit_profile/pages/profile_posts_excluded_communities/modals/exclude_community_from_profile_posts.dart @@ -21,11 +21,11 @@ class OBExcludeCommunitiesFromProfilePostsModal extends StatefulWidget { class OBProfilePostsExcludedCommunitiesState extends State { - UserService _userService; - LocalizationService _localizationService; + late UserService _userService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -91,7 +91,7 @@ class OBProfilePostsExcludedCommunitiesState Future> _refreshJoinedCommunities() async { CommunitiesList joinedCommunities = await _userService.getJoinedCommunities( excludedFromProfilePosts: false); - return joinedCommunities.communities; + return joinedCommunities.communities ?? []; } Future> _loadMoreJoinedCommunities( @@ -101,13 +101,13 @@ class OBProfilePostsExcludedCommunitiesState )) .communities; - return moreJoinedCommunities; + return moreJoinedCommunities ?? []; } Future> _searchCommunities(String query) async { CommunitiesList results = await _userService .searchCommunitiesWithQuery(query, excludedFromProfilePosts: false); - return results.communities; + return results.communities ?? []; } } diff --git a/lib/pages/home/pages/profile/pages/edit_profile/pages/profile_posts_excluded_communities/profile_posts_excluded_communities.dart b/lib/pages/home/pages/profile/pages/edit_profile/pages/profile_posts_excluded_communities/profile_posts_excluded_communities.dart index 99cdb6654..510156c9a 100644 --- a/lib/pages/home/pages/profile/pages/edit_profile/pages/profile_posts_excluded_communities/profile_posts_excluded_communities.dart +++ b/lib/pages/home/pages/profile/pages/edit_profile/pages/profile_posts_excluded_communities/profile_posts_excluded_communities.dart @@ -19,11 +19,11 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBProfilePostsExcludedCommunitiesPage extends StatefulWidget { - final ValueChanged onExcludedCommunityRemoved; - final ValueChanged> onExcludedCommunitiesAdded; + final ValueChanged? onExcludedCommunityRemoved; + final ValueChanged>? onExcludedCommunitiesAdded; const OBProfilePostsExcludedCommunitiesPage( - {Key key, + {Key? key, this.onExcludedCommunityRemoved, this.onExcludedCommunitiesAdded}) : super(key: key); @@ -36,14 +36,14 @@ class OBProfilePostsExcludedCommunitiesPage extends StatefulWidget { class OBProfilePostsExcludedCommunitiesState extends State { - UserService _userService; - NavigationService _navigationService; - ModalService _modalService; - LocalizationService _localizationService; - ToastService _toastService; - OBHttpListController _httpListController; + late UserService _userService; + late NavigationService _navigationService; + late ModalService _modalService; + late LocalizationService _localizationService; + late ToastService _toastService; + late OBHttpListController _httpListController; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { @@ -117,18 +117,18 @@ class OBProfilePostsExcludedCommunitiesState .undoExcludeCommunityFromProfilePosts(excludedCommunity); _httpListController.removeListItem(excludedCommunity); if (widget.onExcludedCommunityRemoved != null) - widget.onExcludedCommunityRemoved(excludedCommunity); + widget.onExcludedCommunityRemoved!(excludedCommunity); } catch (error) { _onError(error); } } void _onWantsToExcludeCommunityFromProfilePosts() async { - List excludedCommunities = await _modalService + List? excludedCommunities = await _modalService .openExcludeCommunitiesFromProfilePosts(context: context); if (excludedCommunities != null && excludedCommunities.isNotEmpty) { if (widget.onExcludedCommunitiesAdded != null) - widget.onExcludedCommunitiesAdded(excludedCommunities); + widget.onExcludedCommunitiesAdded!(excludedCommunities); excludedCommunities.forEach((excludedCommunity) => _httpListController .insertListItem(excludedCommunity, shouldScrollToTop: true)); @@ -140,8 +140,8 @@ class OBProfilePostsExcludedCommunitiesState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -152,7 +152,7 @@ class OBProfilePostsExcludedCommunitiesState Future> _refreshExcludedCommunities() async { CommunitiesList excludedCommunities = await _userService.getProfilePostsExcludedCommunities(); - return excludedCommunities.communities; + return excludedCommunities.communities ?? []; } Future> _loadMoreExcludedCommunities( @@ -164,13 +164,13 @@ class OBProfilePostsExcludedCommunitiesState )) .communities; - return moreExcludedCommunities; + return moreExcludedCommunities ?? []; } Future> _searchExcludedCommunities(String query) async { CommunitiesList results = await _userService.searchProfilePostsExcludedCommunities(query: query); - return results.communities; + return results.communities ?? []; } } diff --git a/lib/pages/home/pages/profile/pages/follow_requests.dart b/lib/pages/home/pages/profile/pages/follow_requests.dart index 315740c09..a25ca1a18 100644 --- a/lib/pages/home/pages/profile/pages/follow_requests.dart +++ b/lib/pages/home/pages/profile/pages/follow_requests.dart @@ -23,11 +23,11 @@ class OBFollowRequestsPage extends StatefulWidget { class OBFollowRequestsPageState extends State { - UserService _userService; - LocalizationService _localizationService; + late UserService _userService; + late LocalizationService _localizationService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -64,10 +64,13 @@ class OBFollowRequestsPageState Widget _buildFollowRequestListItem(BuildContext context, FollowRequest followRequest) { return StreamBuilder( - stream: followRequest.creator.updateSubject, + stream: followRequest.creator?.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot){ // In case the request was approved elsewhere, make sure we dont render it - if((snapshot.data != null && snapshot.data.isFollowed != null && snapshot.data.isFollowed) || (snapshot.data != null && snapshot.data.isPendingFollowRequestApproval != null && !snapshot.data.isPendingFollowRequestApproval)) return const SizedBox(); + if ( + (snapshot.data != null && snapshot.data!.isFollowed != null && snapshot.data!.isFollowed!) + || (snapshot.data != null && snapshot.data!.isPendingFollowRequestApproval != null && !snapshot.data!.isPendingFollowRequestApproval!) + ) return const SizedBox(); return OBReceivedFollowRequestTile( followRequest, @@ -85,7 +88,7 @@ class OBFollowRequestsPageState Future> _refreshFollowRequests() async { FollowRequestList followRequests = await _userService.getReceivedFollowRequests(); - return followRequests.followRequests; + return followRequests.followRequests ?? []; } Future> _loadMoreFollowRequests( @@ -98,7 +101,7 @@ class OBFollowRequestsPageState count: 20, )) .followRequests; - return moreFollowRequests; + return moreFollowRequests ?? []; } } diff --git a/lib/pages/home/pages/profile/profile.dart b/lib/pages/home/pages/profile/profile.dart index 6d1e323ab..b81f44858 100644 --- a/lib/pages/home/pages/profile/profile.dart +++ b/lib/pages/home/pages/profile/profile.dart @@ -19,7 +19,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBProfilePage extends StatefulWidget { - final OBProfilePageController controller; + final OBProfilePageController? controller; final User user; OBProfilePage( @@ -34,18 +34,18 @@ class OBProfilePage extends StatefulWidget { } class OBProfilePageState extends State { - User _user; - bool _needsBootstrap; - UserService _userService; - LocalizationService _localizationService; - OBPostsStreamController _obPostsStreamController; - bool _profileCommunityPostsVisible; - OBPostDisplayContext _postsDisplayContext; - - List _recentlyExcludedCommunities; + late User _user; + late bool _needsBootstrap; + late UserService _userService; + late LocalizationService _localizationService; + late OBPostsStreamController _obPostsStreamController; + late bool _profileCommunityPostsVisible; + late OBPostDisplayContext _postsDisplayContext; + + late List _recentlyExcludedCommunities; GlobalKey _protectedProfileRefreshIndicatorKey = GlobalKey(); - bool _needsProtectedProfileBootstrap; + late bool _needsProtectedProfileBootstrap; @override void initState() { @@ -54,7 +54,7 @@ class OBProfilePageState extends State { _needsBootstrap = true; _needsProtectedProfileBootstrap = true; _user = widget.user; - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); _profileCommunityPostsVisible = widget.user.getProfileCommunityPostsVisible(); _recentlyExcludedCommunities = []; @@ -81,13 +81,13 @@ class OBProfilePageState extends State { initialData: widget.user, stream: widget.user.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot) { - User user = snapshot.data; + User? user = snapshot.data; if (user == null) return const SizedBox(); if (_postsDisplayContext == OBPostDisplayContext.ownProfilePosts || user.visibility != UserVisibility.private || - (user.isFollowing != null && user.isFollowing)) { + (user.isFollowing != null && user.isFollowing!)) { return _buildVisibleProfileContent(); } @@ -107,7 +107,7 @@ class OBProfilePageState extends State { displayContext: _postsDisplayContext, prependedItems: _buildProfileContentDetails(), controller: _obPostsStreamController, - postBuilder: _buildPostsStreamPost, + postBuilder: _buildPostsStreamPost as OBPostsStreamPostBuilder, // TODO: I don't understand why I have to do this. secondaryRefresher: _refreshUser, refresher: _refreshPosts, onScrollLoader: _loadMorePosts, @@ -121,7 +121,7 @@ class OBProfilePageState extends State { Widget _buildProtectedProfileContent() { if (_needsProtectedProfileBootstrap) { Future.delayed(Duration(milliseconds: 100), () { - _protectedProfileRefreshIndicatorKey.currentState.show(); + _protectedProfileRefreshIndicatorKey.currentState?.show(); }); _needsProtectedProfileBootstrap = false; } @@ -171,7 +171,7 @@ class OBProfilePageState extends State { ), OBSecondaryText( _localizationService - .user__protected_account_desc(widget.user.username), + .user__protected_account_desc(widget.user.username!), style: TextStyle(fontWeight: FontWeight.bold), ), const SizedBox( @@ -181,10 +181,10 @@ class OBProfilePageState extends State { stream: widget.user.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data == null || - snapshot.data.isFollowRequested == null) + snapshot.data!.isFollowRequested == null) return const SizedBox(); - User user = snapshot.data; - return OBSecondaryText((user.isFollowRequested + User user = snapshot.data!; + return OBSecondaryText((user.isFollowRequested == true ? _localizationService .user__protected_account_instructions_complete : _localizationService @@ -212,23 +212,23 @@ class OBProfilePageState extends State { } Widget _buildPostsStreamStatusIndicator( - {BuildContext context, - OBPostsStreamStatus streamStatus, - List streamPrependedItems, - Function streamRefresher}) { + {required BuildContext context, + required OBPostsStreamStatus streamStatus, + required List streamPrependedItems, + required Function streamRefresher}) { return OBProfilePostsStreamStatusIndicator( user: widget.user, - streamRefresher: streamRefresher, + streamRefresher: streamRefresher as VoidCallback, streamPrependedItems: streamPrependedItems, streamStatus: streamStatus); } Widget _buildPostsStreamPost({ - BuildContext context, - Post post, - String postIdentifier, - OBPostDisplayContext displayContext, - ValueChanged onPostDeleted, + required BuildContext context, + required Post post, + required String postIdentifier, + required OBPostDisplayContext displayContext, + required ValueChanged onPostDeleted, }) { return _recentlyExcludedCommunities.contains(post.community) ? const SizedBox() @@ -244,7 +244,7 @@ class OBProfilePageState extends State { } String getFollowButtonText() { - return widget.user.isFollowed != null && widget.user.isFollowed + return widget.user.isFollowed != null && widget.user.isFollowed! ? _localizationService.user__follow_button_follow_back_text : _localizationService.user__follow_button_follow_text; } @@ -275,13 +275,13 @@ class OBProfilePageState extends State { } Future _refreshUser() async { - var user = await _userService.getUserWithUsername(_user.username); + var user = await _userService.getUserWithUsername(_user.username!); _setUser(user); } Future> _refreshPosts() async { return (await _userService.getTimelinePosts(username: _user.username)) - .posts; + .posts ?? []; } Future> _loadMorePosts(List posts) async { @@ -289,7 +289,7 @@ class OBProfilePageState extends State { return (await _userService.getTimelinePosts( maxId: lastPost.id, username: _user.username)) - .posts; + .posts ?? []; } void _onPostsRefreshed(List posts) { @@ -316,15 +316,15 @@ class OBProfilePageState extends State { } class OBProfilePageController { - OBProfilePageState _timelinePageState; + OBProfilePageState? _timelinePageState; - void attach(OBProfilePageState profilePageState) { + void attach(OBProfilePageState? profilePageState) { assert(profilePageState != null, 'Cannot attach to empty state'); _timelinePageState = profilePageState; } void scrollToTop() { - if (_timelinePageState != null) _timelinePageState.scrollToTop(); + if (_timelinePageState != null) _timelinePageState!.scrollToTop(); } } diff --git a/lib/pages/home/pages/profile/widgets/profile_card/profile_card.dart b/lib/pages/home/pages/profile/widgets/profile_card/profile_card.dart index cb3edd57a..9e6e3f5b8 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/profile_card.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/profile_card.dart @@ -20,13 +20,13 @@ import 'package:flutter/material.dart'; class OBProfileCard extends StatelessWidget { final User user; - final VoidCallback onUserProfileUpdated; - final ValueChanged onExcludedCommunityRemoved; - final ValueChanged> onExcludedCommunitiesAdded; + final VoidCallback? onUserProfileUpdated; + final ValueChanged? onExcludedCommunityRemoved; + final ValueChanged>? onExcludedCommunitiesAdded; const OBProfileCard( this.user, { - Key key, + Key? key, this.onUserProfileUpdated, this.onExcludedCommunityRemoved, this.onExcludedCommunitiesAdded, @@ -95,7 +95,7 @@ class OBProfileCard extends StatelessWidget { width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: themeValueParserService - .parseColor(theme.primaryColor), + .parseColor(theme!.primaryColor), borderRadius: BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(50))), @@ -125,10 +125,10 @@ class OBProfileCard extends StatelessWidget { } Widget _buildNameRow( - {@required User user, - @required BuildContext context, - @required ToastService toastService}) { - if (user.hasProfileBadges() && user.getProfileBadges().length > 0) { + {required User user, + required BuildContext context, + required ToastService toastService}) { + if (user.hasProfileBadges() && user.getProfileBadges()!.length > 0) { return Row(children: [ OBProfileName(user), _getUserBadge(user: user, toastService: toastService, context: context) @@ -138,10 +138,10 @@ class OBProfileCard extends StatelessWidget { } Widget _getUserBadge( - {@required User user, - @required ToastService toastService, - @required BuildContext context}) { - Badge badge = user.getProfileBadges()[0]; + {required User user, + required ToastService toastService, + required BuildContext context}) { + Badge badge = user.getProfileBadges()![0]; return GestureDetector( onTap: () { toastService.info( @@ -152,7 +152,7 @@ class OBProfileCard extends StatelessWidget { } String _getUserBadgeDescription(User user) { - Badge badge = user.getProfileBadges()[0]; - return badge.getKeywordDescription(); + Badge badge = user.getProfileBadges()![0]; + return badge.getKeywordDescription()!; } } diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_actions/profile_inline_actions.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_actions/profile_inline_actions.dart index 27f3f84dd..7649032c9 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_actions/profile_inline_actions.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_actions/profile_inline_actions.dart @@ -11,12 +11,12 @@ import 'package:flutter/material.dart'; class OBProfileInlineActions extends StatelessWidget { final User user; - final VoidCallback onUserProfileUpdated; - final ValueChanged onExcludedCommunityRemoved; - final ValueChanged> onExcludedCommunitiesAdded; + final VoidCallback? onUserProfileUpdated; + final ValueChanged? onExcludedCommunityRemoved; + final ValueChanged>? onExcludedCommunitiesAdded; const OBProfileInlineActions(this.user, - {@required this.onUserProfileUpdated, + {required this.onUserProfileUpdated, this.onExcludedCommunityRemoved, this.onExcludedCommunitiesAdded}); diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_actions/widgets/profile_inline_action_more_button.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_actions/widgets/profile_inline_action_more_button.dart index 3a10e72ce..c584e0f68 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_actions/widgets/profile_inline_action_more_button.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_actions/widgets/profile_inline_action_more_button.dart @@ -15,7 +15,7 @@ class OBProfileInlineActionsMoreButton extends StatelessWidget { stream: user.updateSubject, initialData: user, builder: (BuildContext context, AsyncSnapshot snapshot) { - var user = snapshot.data; + var user = snapshot.data!; return IconButton( icon: const OBIcon( diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_connected_in.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_connected_in.dart index acc0e8df3..6dedcda15 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_connected_in.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_connected_in.dart @@ -22,7 +22,7 @@ class OBProfileConnectedIn extends StatelessWidget { var user = snapshot.data; var connectedCircles = user?.connectedCircles?.circles; bool isFullyConnected = - user?.isFullyConnected != null && user.isFullyConnected; + user?.isFullyConnected != null && user!.isFullyConnected!; if (connectedCircles == null || connectedCircles.length == 0 || diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_connection_request.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_connection_request.dart index b01246808..89315212f 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_connection_request.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_connection_request.dart @@ -27,7 +27,7 @@ class OBProfileConnectionRequest extends StatelessWidget { if (isPendingConnectionConfirmation == null || !isPendingConnectionConfirmation) return const SizedBox(); - String userName = user.getProfileName(); + String userName = user!.getProfileName()!; return Column( children: [ diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/profile_counts.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/profile_counts.dart index c81d58627..a2ced94f6 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/profile_counts.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/profile_counts.dart @@ -15,7 +15,7 @@ class OBProfileCounts extends StatelessWidget { stream: user.updateSubject, initialData: user, builder: (BuildContext context, AsyncSnapshot snapshot) { - var user = snapshot.data; + var user = snapshot.data!; return Padding( padding: EdgeInsets.only(top: 20.0), diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/widgets/profile_followers_count.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/widgets/profile_followers_count.dart index 498dfe1b4..c199d397c 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/widgets/profile_followers_count.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/widgets/profile_followers_count.dart @@ -12,7 +12,7 @@ class OBProfileFollowersCount extends StatelessWidget { @override Widget build(BuildContext context) { - int followersCount = user.followersCount; + int? followersCount = user.followersCount; if (followersCount == null || followersCount == 0 || @@ -51,7 +51,7 @@ class OBProfileFollowersCount extends StatelessWidget { style: TextStyle( fontWeight: FontWeight.bold, color: themeValueParserService - .parseColor(theme.primaryTextColor))), + .parseColor(theme!.primaryTextColor))), TextSpan( text: followersCount == 1 ? _localizationService.post__profile_counts_follower : _localizationService.post__profile_counts_followers, style: TextStyle( diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/widgets/profile_following_count.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/widgets/profile_following_count.dart index a6f1b33a2..723c6291b 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/widgets/profile_following_count.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_counts/widgets/profile_following_count.dart @@ -12,7 +12,7 @@ class OBProfileFollowingCount extends StatelessWidget { @override Widget build(BuildContext context) { - int followingCount = user.followingCount; + int? followingCount = user.followingCount; LocalizationService localizationService = OpenbookProvider.of(context).localizationService; if (followingCount == null || followingCount == 0) return const SizedBox(); @@ -49,7 +49,7 @@ class OBProfileFollowingCount extends StatelessWidget { style: TextStyle( fontWeight: FontWeight.bold, color: themeValueParserService - .parseColor(theme.primaryTextColor))), + .parseColor(theme!.primaryTextColor))), TextSpan( text: localizationService.post__profile_counts_following, style: TextStyle( diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/profile_details.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/profile_details.dart index bf393d4c6..e98cfea94 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/profile_details.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/profile_details.dart @@ -15,7 +15,7 @@ class OBProfileDetails extends StatelessWidget { stream: user.updateSubject, initialData: user, builder: (BuildContext context, AsyncSnapshot snapshot) { - var user = snapshot.data; + var user = snapshot.data!; if ((!user.hasProfileLocation() && !user.hasProfileUrl()) && !user.hasAge()) return const SizedBox(); diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_age.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_age.dart index 092af3908..1c577a312 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_age.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_age.dart @@ -20,10 +20,10 @@ class OBProfileAge extends StatefulWidget { } class OBProfileAgeState extends State { - LocalizationService _localizationService; - ToastService _toastService; - UtilsService _utilsService; - bool _needsBootstrap; + late LocalizationService _localizationService; + late ToastService _toastService; + late UtilsService _utilsService; + late bool _needsBootstrap; static const MIN_AGE_IN_YEARS_FOR_ADULT = 1; @override @@ -34,7 +34,7 @@ class OBProfileAgeState extends State { @override Widget build(BuildContext context) { - DateTime age = widget.user.dateJoined; + DateTime? age = widget.user.dateJoined; if (age == null) { return const SizedBox(); @@ -81,7 +81,7 @@ class OBProfileAgeState extends State { bool _getIsUserBaby() { DateTime now = DateTime.now(); - Duration difference = now.difference(widget.user.dateJoined); + Duration difference = now.difference(widget.user.dateJoined!); if ((difference.inDays / 365).floor() >= MIN_AGE_IN_YEARS_FOR_ADULT) { return false; } diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_location.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_location.dart index cd28707ab..f7c6e1f59 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_location.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_location.dart @@ -10,7 +10,7 @@ class OBProfileLocation extends StatelessWidget { @override Widget build(BuildContext context) { - String location = user.getProfileLocation(); + String? location = user.getProfileLocation(); if (location == null) { return const SizedBox(); diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_url.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_url.dart index 0dc3dc90d..105c68412 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_url.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_details/widgets/profile_url.dart @@ -11,7 +11,7 @@ class OBProfileUrl extends StatelessWidget { @override Widget build(BuildContext context) { - String url = user.getProfileUrl(); + String? url = user.getProfileUrl(); if (url == null) { return const SizedBox(); diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_follow_request.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_follow_request.dart index a4f67b4d2..f8738380c 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_follow_request.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_follow_request.dart @@ -29,7 +29,7 @@ class OBProfileFollowRequest extends StatelessWidget { if (isPendingFollowRequestApproval == null || !isPendingFollowRequestApproval) return const SizedBox(); - String userName = user.username; + String userName = user!.username!; return Column( children: [ diff --git a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_in_lists.dart b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_in_lists.dart index 486376065..6dabdab59 100644 --- a/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_in_lists.dart +++ b/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_in_lists.dart @@ -15,9 +15,9 @@ class OBProfileInLists extends StatelessWidget { stream: user.updateSubject, initialData: user, builder: (BuildContext context, AsyncSnapshot snapshot) { - var user = snapshot.data; + var user = snapshot.data!; if (!user.hasFollowLists()) return const SizedBox(); - var followsLists = user.followLists.lists; + var followsLists = user.followLists?.lists ?? []; List connectionItems = [ const OBText( @@ -30,14 +30,14 @@ class OBProfileInLists extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ OBEmojiPreview( - followsList.emoji, + followsList.emoji!, size: OBEmojiPreviewSize.small, ), const SizedBox( width: 5, ), OBText( - followsList.name, + followsList.name!, ) ], )); diff --git a/lib/pages/home/pages/profile/widgets/profile_cover.dart b/lib/pages/home/pages/profile/widgets/profile_cover.dart index 02a7d49dd..2f63e41f4 100644 --- a/lib/pages/home/pages/profile/widgets/profile_cover.dart +++ b/lib/pages/home/pages/profile/widgets/profile_cover.dart @@ -3,17 +3,17 @@ import 'package:Okuna/widgets/cover.dart'; import 'package:flutter/cupertino.dart'; class OBProfileCover extends StatelessWidget { - final User user; + final User? user; OBProfileCover(this.user); @override Widget build(BuildContext context) { return StreamBuilder( - stream: user.updateSubject, + stream: user?.updateSubject, initialData: user, builder: (BuildContext context, AsyncSnapshot snapshot) { - String profileCover = user?.getProfileCover(); + String? profileCover = user?.getProfileCover(); return OBCover( coverUrl: profileCover, diff --git a/lib/pages/home/pages/profile/widgets/profile_nav_bar.dart b/lib/pages/home/pages/profile/widgets/profile_nav_bar.dart index eceacc446..0bd4c0a02 100644 --- a/lib/pages/home/pages/profile/widgets/profile_nav_bar.dart +++ b/lib/pages/home/pages/profile/widgets/profile_nav_bar.dart @@ -15,9 +15,9 @@ class OBProfileNavBar extends StatelessWidget stream: user.updateSubject, initialData: user, builder: (BuildContext context, AsyncSnapshot snapshot) { - var user = snapshot.data; + var user = snapshot.data!; return OBThemedNavigationBar( - title: '@' + user.username, + title: '@' + user.username!, ); }); } diff --git a/lib/pages/home/pages/profile/widgets/profile_posts_stream_status_indicator.dart b/lib/pages/home/pages/profile/widgets/profile_posts_stream_status_indicator.dart index 153467ef6..182999443 100644 --- a/lib/pages/home/pages/profile/widgets/profile_posts_stream_status_indicator.dart +++ b/lib/pages/home/pages/profile/widgets/profile_posts_stream_status_indicator.dart @@ -10,13 +10,13 @@ import 'package:Okuna/widgets/tiles/retry_tile.dart'; import 'package:flutter/material.dart'; class OBProfilePostsStreamStatusIndicator extends StatelessWidget { - final User user; + final User? user; final VoidCallback streamRefresher; - final OBPostsStreamStatus streamStatus; - final List streamPrependedItems; + final OBPostsStreamStatus? streamStatus; + final List? streamPrependedItems; OBProfilePostsStreamStatusIndicator({ - @required this.streamRefresher, + required this.streamRefresher, this.streamStatus, this.streamPrependedItems, this.user, @@ -54,15 +54,15 @@ class OBProfilePostsStreamStatusIndicator extends StatelessWidget { Widget _buildEmptyIndicator(BuildContext context) { var provider = OpenbookProvider.of(context); UserService _userService = provider.userService; - bool isLoggedInUser = _userService.isLoggedInUser(user); + bool isLoggedInUser = _userService.isLoggedInUser(user!); LocalizationService localizationService = provider.localizationService; - String name = user.getProfileName(); + String? name = user?.getProfileName(); return OBButtonAlert( text: isLoggedInUser ? localizationService.post__have_not_shared_anything - : localizationService.post__user_has_not_shared_anything(name), + : localizationService.post__user_has_not_shared_anything(name ?? ''), onPressed: streamRefresher, buttonText: localizationService.post__trending_posts_refresh, buttonIcon: OBIcons.refresh, diff --git a/lib/pages/home/pages/report_object/pages/confirm_report_object.dart b/lib/pages/home/pages/report_object/pages/confirm_report_object.dart index b849fe120..23105e7f6 100644 --- a/lib/pages/home/pages/report_object/pages/confirm_report_object.dart +++ b/lib/pages/home/pages/report_object/pages/confirm_report_object.dart @@ -23,11 +23,11 @@ import 'package:flutter/material.dart'; class OBConfirmReportObject extends StatefulWidget { final dynamic object; - final Map extraData; + final Map? extraData; final ModerationCategory category; const OBConfirmReportObject( - {Key key, @required this.object, @required this.category, this.extraData}) + {Key? key, required this.object, required this.category, this.extraData}) : super(key: key); @override @@ -37,16 +37,16 @@ class OBConfirmReportObject extends StatefulWidget { } class OBConfirmReportObjectState extends State { - bool _confirmationInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _needsBootstrap; - TextEditingController _descriptionController; + late bool _confirmationInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _needsBootstrap; + late TextEditingController _descriptionController; - String description; + String? description; - CancelableOperation _submitReportOperation; + CancelableOperation? _submitReportOperation; @override void initState() { @@ -59,7 +59,7 @@ class OBConfirmReportObjectState extends State { @override void dispose() { super.dispose(); - if (_submitReportOperation != null) _submitReportOperation.cancel(); + if (_submitReportOperation != null) _submitReportOperation!.cancel(); } @override @@ -170,7 +170,7 @@ class OBConfirmReportObjectState extends State { _submitReportOperation = CancelableOperation.fromFuture( _userService.reportPostComment( description: _descriptionController.text, - post: widget.extraData['post'], + post: widget.extraData?['post'], postComment: widget.object, moderationCategory: widget.category)); } else if (widget.object is Community) { @@ -194,7 +194,7 @@ class OBConfirmReportObjectState extends State { } else { throw 'Object type not supported'; } - await _submitReportOperation.value; + await _submitReportOperation!.value; if (widget.object is User || widget.object is Community || widget.object is Post || @@ -236,8 +236,8 @@ class OBConfirmReportObjectState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/pages/home/pages/report_object/report_object.dart b/lib/pages/home/pages/report_object/report_object.dart index 9a15fcb08..0e02a9d3d 100644 --- a/lib/pages/home/pages/report_object/report_object.dart +++ b/lib/pages/home/pages/report_object/report_object.dart @@ -15,11 +15,11 @@ import 'package:flutter/material.dart'; class OBReportObjectPage extends StatefulWidget { final dynamic object; - final OnObjectReported onObjectReported; - final Map extraData; + final OnObjectReported? onObjectReported; + final Map? extraData; const OBReportObjectPage({ - Key key, + Key? key, this.object, this.onObjectReported, this.extraData, @@ -32,10 +32,10 @@ class OBReportObjectPage extends StatefulWidget { } class OBReportObjectPageState extends State { - NavigationService _navigationService; - UserService _userService; - List _moderationCategories = []; - bool _needsBootstrap; + late NavigationService _navigationService; + late UserService _userService; + late List _moderationCategories = []; + late bool _needsBootstrap; @override void initState() { @@ -110,20 +110,20 @@ class OBReportObjectPageState extends State { context: context); if (result != null && result) { if (widget.onObjectReported != null) - widget.onObjectReported(widget.object); + widget.onObjectReported!(widget.object); Navigator.pop(context); } }, title: OBText( - category.title, + category.title ?? '', style: TextStyle(fontWeight: FontWeight.bold), ), - subtitle: OBSecondaryText(category.description), + subtitle: OBSecondaryText(category.description ?? ''), //trailing: OBIcon(OBIcons.chevronRight), ); } - Widget _buildNavigationBar() { + ObstructingPreferredSizeWidget _buildNavigationBar() { return OBThemedNavigationBar( title: 'Report ' + modelTypeToString(widget.object), ); @@ -136,7 +136,7 @@ class OBReportObjectPageState extends State { _setModerationCategories(ModerationCategoriesList moderationCategoriesList) { setState(() { - _moderationCategories = moderationCategoriesList.moderationCategories; + _moderationCategories = moderationCategoriesList.moderationCategories!; }); } } diff --git a/lib/pages/home/pages/search/search.dart b/lib/pages/home/pages/search/search.dart index 970b8e13e..767ce0b0c 100644 --- a/lib/pages/home/pages/search/search.dart +++ b/lib/pages/home/pages/search/search.dart @@ -28,11 +28,11 @@ import 'package:flutter/rendering.dart'; import 'package:throttling/throttling.dart'; class OBMainSearchPage extends StatefulWidget { - final OBMainSearchPageController controller; + final OBMainSearchPageController? controller; final OBSearchPageTab selectedTab; const OBMainSearchPage( - {Key key, this.controller, this.selectedTab = OBSearchPageTab.trending}) + {Key? key, this.controller, this.selectedTab = OBSearchPageTab.trending}) : super(key: key); @override @@ -43,37 +43,37 @@ class OBMainSearchPage extends StatefulWidget { class OBMainSearchPageState extends State with WidgetsBindingObserver, TickerProviderStateMixin { - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; - LocalizationService _localizationService; - ThemeService _themeService; - ThemeValueParserService _themeValueParserService; - - bool _hasSearch; - bool _userSearchRequestInProgress; - bool _communitySearchRequestInProgress; - bool _hashtagSearchRequestInProgress; - String _searchQuery; - List _userSearchResults; - List _communitySearchResults; - List _hashtagSearchResults; - OBTopPostsController _topPostsController; - OBTrendingPostsController _trendingPostsController; - TabController _tabController; - AnimationController _animationController; - Animation _offset; - double _heightTabs; - double _lastScrollPosition; - double _extraPaddingForSlidableSection; - - OBUserSearchResultsTab _selectedSearchResultsTab; - - StreamSubscription _getUsersWithQuerySubscription; - StreamSubscription _getCommunitiesWithQuerySubscription; - StreamSubscription _getHashtagsWithQuerySubscription; - - Throttling _setScrollPositionThrottler; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late ThemeService _themeService; + late ThemeValueParserService _themeValueParserService; + + late bool _hasSearch; + late bool _userSearchRequestInProgress; + late bool _communitySearchRequestInProgress; + late bool _hashtagSearchRequestInProgress; + String? _searchQuery; + late List _userSearchResults; + late List _communitySearchResults; + late List _hashtagSearchResults; + late OBTopPostsController _topPostsController; + late OBTrendingPostsController _trendingPostsController; + late TabController _tabController; + late AnimationController _animationController; + late Animation _offset; + late double _heightTabs; + double? _lastScrollPosition; + double? _extraPaddingForSlidableSection; + + late OBUserSearchResultsTab _selectedSearchResultsTab; + + StreamSubscription? _getUsersWithQuerySubscription; + StreamSubscription? _getCommunitiesWithQuerySubscription; + StreamSubscription? _getHashtagsWithQuerySubscription; + + late Throttling _setScrollPositionThrottler; static const double OB_BOTTOM_TAB_BAR_HEIGHT = 50.0; static const double HEIGHT_SEARCH_BAR = 76.0; @@ -84,7 +84,7 @@ class OBMainSearchPageState extends State void initState() { super.initState(); if (widget.controller != null) - widget.controller.attach(context: context, state: this); + widget.controller!.attach(context: context, state: this); _topPostsController = OBTopPostsController(); _trendingPostsController = OBTrendingPostsController(); _userSearchRequestInProgress = false; @@ -166,9 +166,9 @@ class OBMainSearchPageState extends State ), Padding( padding: EdgeInsets.only( - top: HEIGHT_SEARCH_BAR + _extraPaddingForSlidableSection), + top: HEIGHT_SEARCH_BAR + (_extraPaddingForSlidableSection ?? 0)), child: OBSearchResults( - searchQuery: _searchQuery, + searchQuery: _searchQuery ?? '', userResults: _userSearchResults, userSearchInProgress: _userSearchRequestInProgress, communityResults: _communitySearchResults, @@ -204,7 +204,7 @@ class OBMainSearchPageState extends State left: 0, top: 0, height: - HEIGHT_SEARCH_BAR + _heightTabs + _extraPaddingForSlidableSection, + HEIGHT_SEARCH_BAR + _heightTabs + (_extraPaddingForSlidableSection ?? 0), width: existingMediaQuery.size.width, child: OBCupertinoPageScaffold( backgroundColor: Colors.transparent, @@ -267,7 +267,7 @@ class OBMainSearchPageState extends State void _handleScrollThrottle(double scrollPixels, bool isScrollingUp) { if (_lastScrollPosition != null) { - double offset = (scrollPixels - _lastScrollPosition).abs(); + double offset = (scrollPixels - (_lastScrollPosition ?? 0)).abs(); if (offset > MIN_SCROLL_OFFSET_TO_ANIMATE_TABS) _checkScrollDirectionAndAnimateTabs(isScrollingUp); } _setScrollPosition(scrollPixels); @@ -309,7 +309,7 @@ class OBMainSearchPageState extends State FocusScope.of(context).requestFocus(new FocusNode()); } - Future _searchWithQuery(String query) { + Future? _searchWithQuery(String query) { String cleanedUpQuery = _cleanUpQuery(query); if(cleanedUpQuery.isEmpty) return null; @@ -334,7 +334,7 @@ class OBMainSearchPageState extends State Future _searchForUsersWithQuery(String query) async { if (_getUsersWithQuerySubscription != null) - _getUsersWithQuerySubscription.cancel(); + _getUsersWithQuerySubscription!.cancel(); _setUserSearchRequestInProgress(true); @@ -342,7 +342,7 @@ class OBMainSearchPageState extends State _userService.getUsersWithQuery(query).asStream().listen( (UsersList usersList) { _getUsersWithQuerySubscription = null; - _setUserSearchResults(usersList.users); + _setUserSearchResults(usersList.users ?? []); }, onError: _onError, onDone: () { @@ -352,14 +352,14 @@ class OBMainSearchPageState extends State Future _searchForCommunitiesWithQuery(String query) async { if (_getCommunitiesWithQuerySubscription != null) - _getCommunitiesWithQuerySubscription.cancel(); + _getCommunitiesWithQuerySubscription!.cancel(); _setCommunitySearchRequestInProgress(true); _getCommunitiesWithQuerySubscription = _userService.searchCommunitiesWithQuery(query).asStream().listen( (CommunitiesList communitiesList) { - _setCommunitySearchResults(communitiesList.communities); + _setCommunitySearchResults(communitiesList.communities ?? []); }, onError: _onError, onDone: () { @@ -369,14 +369,14 @@ class OBMainSearchPageState extends State Future _searchForHashtagsWithQuery(String query) async { if (_getHashtagsWithQuerySubscription != null) - _getHashtagsWithQuerySubscription.cancel(); + _getHashtagsWithQuerySubscription!.cancel(); _setHashtagSearchRequestInProgress(true); _getHashtagsWithQuerySubscription = _userService.getHashtagsWithQuery(query).asStream().listen( (HashtagsList hashtagsList) { - _setHashtagSearchResults(hashtagsList.hashtags); + _setHashtagSearchResults(hashtagsList.hashtags ?? []); }, onError: _onError, onDone: () { @@ -389,8 +389,8 @@ class OBMainSearchPageState extends State _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -491,15 +491,15 @@ class OBMainSearchPageState extends State } class OBMainSearchPageController extends PoppablePageController { - OBMainSearchPageState _state; + OBMainSearchPageState? _state; - void attach({@required BuildContext context, OBMainSearchPageState state}) { + void attach({required BuildContext context, OBMainSearchPageState? state}) { super.attach(context: context); _state = state; } void scrollToTop() { - _state.scrollToTop(); + _state?.scrollToTop(); } } diff --git a/lib/pages/home/pages/search/widgets/search_results.dart b/lib/pages/home/pages/search/widgets/search_results.dart index 081b380d0..20539c043 100644 --- a/lib/pages/home/pages/search/widgets/search_results.dart +++ b/lib/pages/home/pages/search/widgets/search_results.dart @@ -30,20 +30,20 @@ class OBSearchResults extends StatefulWidget { final bool hashtagSearchInProgress; const OBSearchResults( - {Key key, - @required this.userResults, + {Key? key, + required this.userResults, this.selectedTab = OBUserSearchResultsTab.users, - @required this.communityResults, - @required this.hashtagResults, + required this.communityResults, + required this.hashtagResults, this.userSearchInProgress = false, this.communitySearchInProgress = false, this.hashtagSearchInProgress = false, - @required this.searchQuery, - @required this.onUserPressed, - @required this.onScroll, - @required this.onCommunityPressed, - @required this.onHashtagPressed, - @required this.onTabSelectionChanged}) + required this.searchQuery, + required this.onUserPressed, + required this.onScroll, + required this.onCommunityPressed, + required this.onHashtagPressed, + required this.onTabSelectionChanged}) : super(key: key); @override @@ -54,8 +54,8 @@ class OBSearchResults extends StatefulWidget { class OBSearchResultsState extends State with TickerProviderStateMixin { - TabController _tabController; - LocalizationService _localizationService; + late TabController _tabController; + late LocalizationService _localizationService; @override void initState() { @@ -263,7 +263,7 @@ class OBSearchResultsState extends State return OBHashtagTile( hashtag, - key: Key(hashtag.name), + key: Key(hashtag.name!), onHashtagTilePressed: widget.onHashtagPressed, ); }), diff --git a/lib/pages/home/pages/search/widgets/top_posts/pages/top_posts_settings/pages/top_posts_excluded_communities.dart b/lib/pages/home/pages/search/widgets/top_posts/pages/top_posts_settings/pages/top_posts_excluded_communities.dart index 1316cc2b2..28e611e06 100644 --- a/lib/pages/home/pages/search/widgets/top_posts/pages/top_posts_settings/pages/top_posts_excluded_communities.dart +++ b/lib/pages/home/pages/search/widgets/top_posts/pages/top_posts_settings/pages/top_posts_excluded_communities.dart @@ -23,13 +23,13 @@ class OBTopPostsExcludedCommunitiesPage extends StatefulWidget { } class OBTopPostsExcludedCommunitiesState extends State { - UserService _userService; - NavigationService _navigationService; - LocalizationService _localizationService; - ToastService _toastService; + late UserService _userService; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late ToastService _toastService; - OBHttpListController _httpListController; - bool _needsBootstrap; + late OBHttpListController _httpListController; + late bool _needsBootstrap; @override void initState() { @@ -100,8 +100,8 @@ class OBTopPostsExcludedCommunitiesState extends State> _refreshExcludedCommunities() async { CommunitiesList excludedCommunities = await _userService.getTopPostsExcludedCommunities(); - return excludedCommunities.communities; + return excludedCommunities.communities ?? []; } Future> _loadMoreExcludedCommunities(List excludedCommunitiesList) async { @@ -121,12 +121,12 @@ class OBTopPostsExcludedCommunitiesState extends State> _searchExcludedCommunities(String query) async { CommunitiesList results = await _userService.searchTopPostsExcludedCommunities(query: query); - return results.communities; + return results.communities ?? []; } } diff --git a/lib/pages/home/pages/search/widgets/top_posts/pages/top_posts_settings/top_posts_settings.dart b/lib/pages/home/pages/search/widgets/top_posts/pages/top_posts_settings/top_posts_settings.dart index 823bb77fb..be66ed636 100644 --- a/lib/pages/home/pages/search/widgets/top_posts/pages/top_posts_settings/top_posts_settings.dart +++ b/lib/pages/home/pages/search/widgets/top_posts/pages/top_posts_settings/top_posts_settings.dart @@ -20,10 +20,10 @@ class OBTopPostsSettingsPage extends StatefulWidget { } class OBTopPostsSettingsState extends State { - NavigationService _navigationService; - LocalizationService _localizationService; + late NavigationService _navigationService; + late LocalizationService _localizationService; - bool _needsBootstrap; + late bool _needsBootstrap; @override void initState() { diff --git a/lib/pages/home/pages/search/widgets/top_posts/top_posts.dart b/lib/pages/home/pages/search/widgets/top_posts/top_posts.dart index 8afd40158..b302ea471 100644 --- a/lib/pages/home/pages/search/widgets/top_posts/top_posts.dart +++ b/lib/pages/home/pages/search/widgets/top_posts/top_posts.dart @@ -18,8 +18,8 @@ import 'package:flutter/material.dart'; import 'package:throttling/throttling.dart'; class OBTopPosts extends StatefulWidget { - final OBTopPostsController controller; - final Function(ScrollPosition) onScrollCallback; + final OBTopPostsController? controller; + final Function(ScrollPosition)? onScrollCallback; final double extraTopPadding; OBTopPosts({ @@ -36,20 +36,20 @@ class OBTopPosts extends StatefulWidget { class OBTopPostsState extends State with AutomaticKeepAliveClientMixin { - UserService _userService; - LocalizationService _localizationService; - NavigationService _navigationService; - ExploreTimelinePreferencesService _exploreTimelinePreferencesService; - OBPostsStreamController _obPostsStreamController; - StreamSubscription _excludeJoinedCommunitiesChangeSubscription; - - bool _needsBootstrap; - bool _excludeJoinedCommunitiesEnabled; - List _currentTopPosts; - List _currentPosts; + late UserService _userService; + late LocalizationService _localizationService; + late NavigationService _navigationService; + late ExploreTimelinePreferencesService _exploreTimelinePreferencesService; + late OBPostsStreamController _obPostsStreamController; + StreamSubscription? _excludeJoinedCommunitiesChangeSubscription; + + late bool _needsBootstrap; + late bool _excludeJoinedCommunitiesEnabled; + List _currentTopPosts = []; + List? _currentPosts; List _excludedCommunities = []; - int _topPostLastViewedId; - Debouncing _storeLastViewedIdAndCachablePostsDebouncer; + int? _topPostLastViewedId; + late Debouncing _storeLastViewedIdAndCachablePostsDebouncer; @override void initState() { @@ -58,7 +58,7 @@ class OBTopPostsState extends State _storeLastViewedIdAndCachablePostsDebouncer = new Debouncing(duration: Duration(milliseconds: 500)); _obPostsStreamController = OBPostsStreamController(); - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); } @override @@ -68,7 +68,7 @@ class OBTopPostsState extends State _excludeJoinedCommunitiesChangeSubscription?.cancel(); } - Future refresh() { + Future? refresh() { return _obPostsStreamController.refresh(); } @@ -134,11 +134,11 @@ class OBTopPostsState extends State .listen(_onExcludeJoinedCommunitiesEnabledChanged); _topPostLastViewedId = await _userService.getStoredTopPostsLastViewedId(); - TopPostsList topPostsList = await _userService.getStoredTopPosts(); + TopPostsList? topPostsList = await _userService.getStoredTopPosts(); if (topPostsList.posts != null) { - _currentTopPosts = topPostsList.posts; + _currentTopPosts = topPostsList.posts!; List posts = - topPostsList.posts.map((topPost) => topPost.post).toList(); + topPostsList.posts!.map((topPost) => topPost.post!).toList(); _currentPosts = posts; } @@ -157,12 +157,16 @@ class OBTopPostsState extends State } Widget _topPostBuilder( - {BuildContext context, - Post post, - OBPostDisplayContext displayContext, - String postIdentifier, - ValueChanged onPostDeleted}) { - if (_excludedCommunities.contains(post.community.id)) { + {BuildContext? context, + Post? post, + OBPostDisplayContext? displayContext, + String? postIdentifier, + ValueChanged? onPostDeleted}) { + if (post == null || displayContext == null || postIdentifier == null || onPostDeleted == null) { + return SizedBox(); + } + + if (post.community != null && _excludedCommunities.contains(post.community!.id)) { post.updateIsExcludedFromTopPosts(true); } else { post.updateIsExcludedFromTopPosts(false); @@ -188,14 +192,14 @@ class OBTopPostsState extends State void _storeLastViewedIdAndCachedPosts(Post post) async { List _cachablePosts = []; int indexTopPost = _currentTopPosts.indexWhere((topPost) { - return topPost.post.id == post.id; + return topPost.post!.id == post.id; }); int lastIndexTopPosts = _currentTopPosts.length - 1; int cacheFromIndex = 0; int cacheToIndex = min(indexTopPost + 2, lastIndexTopPosts); if (indexTopPost >= 4) cacheFromIndex = indexTopPost - 4; _cachablePosts = _currentTopPosts.sublist(cacheFromIndex, cacheToIndex); - _userService.setTopPostsLastViewedId(post.id); + _userService.setTopPostsLastViewedId(post.id!); _userService.setStoredTopPosts(_cachablePosts); } @@ -209,9 +213,9 @@ class OBTopPostsState extends State } void _onCommunityExcluded(Community community) { - _excludedCommunities.add(community.id); - _currentPosts.forEach((post) { - if (post.community.id == community.id) { + _excludedCommunities.add(community.id!); + _currentPosts?.forEach((post) { + if (post.community?.id == community.id) { post.updateIsExcludedFromTopPosts(true); } }); @@ -219,8 +223,8 @@ class OBTopPostsState extends State void _onUndoCommunityExcluded(Community community) { _excludedCommunities.remove(community.id); - _currentPosts.forEach((post) { - if (post.community.id == community.id) { + _currentPosts?.forEach((post) { + if (post.community?.id == community.id) { post.updateIsExcludedFromTopPosts(false); } }); @@ -230,8 +234,8 @@ class OBTopPostsState extends State List topPosts = (await _userService.getTopPosts( count: 10, excludeJoinedCommunities: _excludeJoinedCommunitiesEnabled)) - .posts; - List posts = topPosts.map((topPost) => topPost.post).toList(); + .posts ?? []; + List posts = topPosts.map((topPost) => topPost.post!).toList(); _setTopPosts(topPosts); _setPosts(posts); _clearExcludedCommunities(); @@ -241,15 +245,15 @@ class OBTopPostsState extends State Future> _postsStreamOnScrollLoader(List posts) async { TopPost lastTopPost = _currentTopPosts.last; - int lastTopPostId = lastTopPost.id; + int lastTopPostId = lastTopPost.id!; List moreTopPosts = (await _userService.getTopPosts( maxId: lastTopPostId, excludeJoinedCommunities: _excludeJoinedCommunitiesEnabled, count: 10)) - .posts; + .posts ?? []; - List morePosts = moreTopPosts.map((topPost) => topPost.post).toList(); + List morePosts = moreTopPosts.map((topPost) => topPost.post!).toList(); _appendCurrentTopPosts(moreTopPosts); _appendCurrentPosts(morePosts); @@ -281,7 +285,7 @@ class OBTopPostsState extends State } void _appendCurrentPosts(List posts) { - List newPosts = _currentPosts + posts; + List newPosts = (_currentPosts ?? []) + posts; setState(() { _currentPosts = newPosts; }); @@ -292,17 +296,17 @@ class OBTopPostsState extends State } class OBTopPostsController { - OBTopPostsState _state; + OBTopPostsState? _state; - void attach(OBTopPostsState state) { + void attach(OBTopPostsState? state) { _state = state; } - Future refresh() { - return _state.refresh(); + Future? refresh() { + return _state?.refresh(); } void scrollToTop() { - _state.scrollToTop(); + _state?.scrollToTop(); } } diff --git a/lib/pages/home/pages/search/widgets/trending_posts.dart b/lib/pages/home/pages/search/widgets/trending_posts.dart index 0637e7149..6caea5c51 100644 --- a/lib/pages/home/pages/search/widgets/trending_posts.dart +++ b/lib/pages/home/pages/search/widgets/trending_posts.dart @@ -13,8 +13,8 @@ import 'package:async/async.dart'; import 'package:flutter/material.dart'; class OBTrendingPosts extends StatefulWidget { - final OBTrendingPostsController controller; - final Function(ScrollPosition) onScrollCallback; + final OBTrendingPostsController? controller; + final Function(ScrollPosition)? onScrollCallback; final double extraTopPadding; const OBTrendingPosts({ @@ -31,20 +31,20 @@ class OBTrendingPosts extends StatefulWidget { class OBTrendingPostsState extends State with AutomaticKeepAliveClientMixin { - UserService _userService; - LocalizationService _localizationService; + late UserService _userService; + late LocalizationService _localizationService; - CancelableOperation _getTrendingPostsOperation; + CancelableOperation? _getTrendingPostsOperation; - OBPostsStreamController _obPostsStreamController; - List _currentTrendingPosts; - List _currentPosts; + late OBPostsStreamController _obPostsStreamController; + List _currentTrendingPosts = []; + late List _currentPosts = []; @override void initState() { super.initState(); _obPostsStreamController = OBPostsStreamController(); - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); } @override @@ -53,10 +53,10 @@ class OBTrendingPostsState extends State @override void dispose() { super.dispose(); - if (_getTrendingPostsOperation != null) _getTrendingPostsOperation.cancel(); + if (_getTrendingPostsOperation != null) _getTrendingPostsOperation!.cancel(); } - Future refresh() { + Future? refresh() { return _obPostsStreamController.refreshPosts(); } @@ -95,9 +95,9 @@ class OBTrendingPostsState extends State Future> _postsStreamRefresher() async { List trendingPosts = - (await _userService.getTrendingPosts(count: 10)).posts; + (await _userService.getTrendingPosts(count: 10)).posts ?? []; List posts = - trendingPosts.map((trendingPost) => trendingPost.post).toList(); + trendingPosts.map((trendingPost) => trendingPost.post!).toList(); _setTrendingPosts(trendingPosts); _setPosts(posts); @@ -107,14 +107,14 @@ class OBTrendingPostsState extends State Future> _postsStreamOnScrollLoader(List posts) async { TrendingPost lastTrendingPost = _currentTrendingPosts.last; - int lastTrendingPostId = lastTrendingPost.id; + int lastTrendingPostId = lastTrendingPost.id!; List moreTrendingPosts = (await _userService.getTrendingPosts( maxId: lastTrendingPostId, count: 10)) - .posts; + .posts ?? []; List morePosts = - moreTrendingPosts.map((trendingPost) => trendingPost.post).toList(); + moreTrendingPosts.map((trendingPost) => trendingPost.post!).toList(); _appendCurrentTrendingPosts(moreTrendingPosts); _appendCurrentPosts(morePosts); @@ -123,11 +123,17 @@ class OBTrendingPostsState extends State } Widget _trendingPostBuilder( - {BuildContext context, - Post post, - OBPostDisplayContext displayContext, - String postIdentifier, - ValueChanged onPostDeleted}) { + {BuildContext? context, + Post? post, + OBPostDisplayContext? displayContext, + String? postIdentifier, + ValueChanged? onPostDeleted}) { + + if (context == null || post == null || displayContext == null || postIdentifier == null || onPostDeleted == null) { + // TODO: very ugly, should probably refactor + return SizedBox(); + } + return OBPost( post, key: Key(postIdentifier), @@ -163,17 +169,17 @@ class OBTrendingPostsState extends State } class OBTrendingPostsController { - OBTrendingPostsState _state; + OBTrendingPostsState? _state; - void attach(OBTrendingPostsState state) { + void attach(OBTrendingPostsState? state) { _state = state; } - Future refresh() { - return _state.refresh(); + Future? refresh() { + return _state?.refresh(); } void scrollToTop() { - _state.scrollToTop(); + _state?.scrollToTop(); } } diff --git a/lib/pages/home/pages/timeline/timeline.dart b/lib/pages/home/pages/timeline/timeline.dart index 3d7fd39e1..2a36a74a5 100644 --- a/lib/pages/home/pages/timeline/timeline.dart +++ b/lib/pages/home/pages/timeline/timeline.dart @@ -29,7 +29,7 @@ class OBTimelinePage extends StatefulWidget { final OBTimelinePageController controller; OBTimelinePage({ - @required this.controller, + required this.controller, }); @override @@ -40,27 +40,27 @@ class OBTimelinePage extends StatefulWidget { class OBTimelinePageState extends State with TickerProviderStateMixin { - OBPostsStreamController _timelinePostsStreamController; - ScrollController _timelinePostsStreamScrollController; - ModalService _modalService; - UserService _userService; - LocalizationService _localizationService; - ThemeService _themeService; - ThemeValueParserService _themeValueParserService; + late OBPostsStreamController _timelinePostsStreamController; + late ScrollController _timelinePostsStreamScrollController; + late ModalService _modalService; + late UserService _userService; + late LocalizationService _localizationService; + late ThemeService _themeService; + late ThemeValueParserService _themeValueParserService; - List _initialPosts; - List _newPostsData; - List _filteredCircles; - List _filteredFollowsLists; + List? _initialPosts; + late List _newPostsData; + late List _filteredCircles; + late List _filteredFollowsLists; - StreamSubscription _loggedInUserChangeSubscription; + late StreamSubscription _loggedInUserChangeSubscription; - bool _needsBootstrap; - bool _loggedInUserBootstrapped; + late bool _needsBootstrap; + late bool _loggedInUserBootstrapped; double _hideFloatingButtonTolerance = 10; - AnimationController _hideFloatingButtonAnimation; - double _previousScrollPixels; + late AnimationController _hideFloatingButtonAnimation; + late double _previousScrollPixels; @override void initState() { @@ -199,9 +199,9 @@ class OBTimelinePageState extends State ); } - void _onLoggedInUserChange(User newUser) async { + void _onLoggedInUserChange(User? newUser) async { if (newUser == null) return; - List initialPosts = (await _userService.getStoredFirstPosts()).posts; + List? initialPosts = (await _userService.getStoredFirstPosts()).posts; setState(() { _loggedInUserBootstrapped = true; _initialPosts = initialPosts; @@ -212,32 +212,32 @@ class OBTimelinePageState extends State Future> _postsStreamRefresher() async { bool cachePosts = _filteredCircles.isEmpty && _filteredFollowsLists.isEmpty; - List posts = (await _userService.getTimelinePosts( + List? posts = (await _userService.getTimelinePosts( count: 10, circles: _filteredCircles, followsLists: _filteredFollowsLists, cachePosts: cachePosts)) .posts; - return posts; + return posts ?? []; } Future> _postsStreamOnScrollLoader(List posts) async { Post lastPost = posts.last; - int lastPostId = lastPost.id; + int lastPostId = lastPost.id!; - List morePosts = (await _userService.getTimelinePosts( + List? morePosts = (await _userService.getTimelinePosts( maxId: lastPostId, circles: _filteredCircles, count: 10, followsLists: _filteredFollowsLists)) .posts; - return morePosts; + return morePosts ?? []; } - Future _onCreatePost({String text, File image, File video}) async { - OBNewPostData createPostData = await _modalService.openCreatePost( + Future _onCreatePost({String? text, File? image, File? video}) async { + OBNewPostData? createPostData = await _modalService.openCreatePost( text: text, image: image, video: video, context: context); if (createPostData != null) { addNewPostData(createPostData); @@ -250,13 +250,19 @@ class OBTimelinePageState extends State } Future setFilters( - {List circles, List followsLists}) async { - _filteredCircles = circles; - _filteredFollowsLists = followsLists; + {List? circles, List? followsLists}) async { + if (circles != null) { + _filteredCircles = circles; + } + + if (followsLists != null) { + _filteredFollowsLists = followsLists; + } + return _timelinePostsStreamController.refreshPosts(); } - Future clearFilters() { + Future? clearFilters() { _filteredCircles = []; _filteredFollowsLists = []; return _timelinePostsStreamController.refreshPosts(); @@ -307,36 +313,40 @@ class OBTimelinePageState extends State } class OBTimelinePageController extends PoppablePageController { - OBTimelinePageState _state; + OBTimelinePageState? _state; - void attach({@required BuildContext context, OBTimelinePageState state}) { + void attach({required BuildContext context, OBTimelinePageState? state}) { super.attach(context: context); _state = state; } Future setPostFilters( - {List circles, List followsLists}) async { - return _state.setFilters(circles: circles, followsLists: followsLists); + {List? circles, List? followsLists}) async { + return _state?.setFilters(circles: circles, followsLists: followsLists); } Future clearPostFilters( - {List circles, List followsLists}) async { - return _state.setFilters(circles: circles, followsLists: followsLists); + {List? circles, List? followsLists}) async { + return _state?.setFilters(circles: circles, followsLists: followsLists); } List getFilteredCircles() { - return _state.getFilteredCircles(); + return _state?.getFilteredCircles() ?? []; } List getFilteredFollowsLists() { - return _state.getFilteredFollowsLists(); + return _state?.getFilteredFollowsLists() ?? []; } - Future createPost({String text, File image, File video}) { - return _state._onCreatePost(text: text, image: image, video: video); + Future createPost({String? text, File? image, File? video}) { + if (_state == null) { + return Future.value(false); + } + + return _state!._onCreatePost(text: text, image: image, video: video); } void scrollToTop() { - _state.scrollToTop(); + _state?.scrollToTop(); } } diff --git a/lib/pages/home/widgets/bottom-tab-bar.dart b/lib/pages/home/widgets/bottom-tab-bar.dart index d9d17e634..aae8a3a07 100644 --- a/lib/pages/home/widgets/bottom-tab-bar.dart +++ b/lib/pages/home/widgets/bottom-tab-bar.dart @@ -36,8 +36,8 @@ const Color _kDefaultTabBarBackgroundColor = Color(0xCCF8F8F8); class OBCupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { /// Creates a tab bar in the iOS style. OBCupertinoTabBar({ - Key key, - @required this.items, + Key? key, + required this.items, this.onTap, this.currentIndex = 0, this.backgroundColor = _kDefaultTabBarBackgroundColor, @@ -61,7 +61,7 @@ class OBCupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { /// The widget creating the bottom navigation bar needs to keep track of the /// current index and call `setState` to rebuild it with the newly provided /// index. - final ChangeIndexAllowed onTap; + final ChangeIndexAllowed? onTap; /// The index into [items] of the current active item. /// @@ -111,7 +111,7 @@ class OBCupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { final double bottomPadding = MediaQuery.of(context).padding.bottom; Widget result = DecoratedBox( decoration: BoxDecoration( - color: themeValueParserService.parseColor(theme.primaryColor), + color: themeValueParserService.parseColor(theme!.primaryColor), ), // TODO(xster): allow icons-only versions of the tab bar too. child: SizedBox( @@ -175,7 +175,7 @@ class OBCupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { onTap: onTap == null ? null : () { - onTap(index); + onTap!(index); }, child: Padding( padding: const EdgeInsets.only(bottom: 4.0), @@ -188,7 +188,7 @@ class OBCupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { ? items[index].activeIcon : items[index].icon), ), - items[index].title, + // items[index].label, // TODO(nullsafety): not sure what to do here ], ), ), @@ -204,7 +204,7 @@ class OBCupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { } /// Change the active tab item's icon and title colors to active. - Widget _wrapActiveItem(Widget item, {@required bool active}) { + Widget _wrapActiveItem(Widget item, {required bool active}) { if (!active) return item; return IconTheme.merge( @@ -219,14 +219,14 @@ class OBCupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { /// Create a clone of the current [OBCupertinoTabBar] but with provided /// parameters overridden. OBCupertinoTabBar copyWith({ - Key key, - List items, - Color backgroundColor, - Color activeColor, - Color inactiveColor, - Size iconSize, - int currentIndex, - ChangeIndexAllowed onTap, + Key? key, + List? items, + Color? backgroundColor, + Color? activeColor, + Color? inactiveColor, + double? iconSize, + int? currentIndex, + ChangeIndexAllowed? onTap, }) { return OBCupertinoTabBar( key: key ?? this.key, @@ -241,4 +241,4 @@ class OBCupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { } } -typedef ChangeIndexAllowed = bool Function(T value); +typedef ChangeIndexAllowed = bool? Function(T value); diff --git a/lib/pages/home/widgets/own_profile_active_icon.dart b/lib/pages/home/widgets/own_profile_active_icon.dart index e8cf5bb1e..917270cc3 100644 --- a/lib/pages/home/widgets/own_profile_active_icon.dart +++ b/lib/pages/home/widgets/own_profile_active_icon.dart @@ -4,10 +4,10 @@ import 'package:Okuna/widgets/avatars/avatar.dart'; import 'package:flutter/cupertino.dart'; class OBOwnProfileActiveIcon extends StatelessWidget { - final String avatarUrl; - final OBAvatarSize size; + final String? avatarUrl; + final OBAvatarSize? size; - const OBOwnProfileActiveIcon({Key key, this.avatarUrl, this.size}) : super(key: key); + const OBOwnProfileActiveIcon({Key? key, this.avatarUrl, this.size}) : super(key: key); @override Widget build(BuildContext context) { @@ -25,11 +25,11 @@ class OBOwnProfileActiveIcon extends StatelessWidget { borderRadius: BorderRadius.circular(500), border: Border.all( color: themeValueParserService - .parseGradient(theme.primaryAccentColor).colors[1])), + .parseGradient(theme!.primaryAccentColor).colors[1])), padding: EdgeInsets.all(2.0), child: OBAvatar( avatarUrl: avatarUrl, - size: size, + size: size ?? OBAvatarSize.medium, ), ); }); diff --git a/lib/pages/home/widgets/tab-scaffold.dart b/lib/pages/home/widgets/tab-scaffold.dart index 72cac4893..9c69746f1 100644 --- a/lib/pages/home/widgets/tab-scaffold.dart +++ b/lib/pages/home/widgets/tab-scaffold.dart @@ -92,9 +92,9 @@ class OBCupertinoTabScaffold extends StatefulWidget { /// The [currentTabIndex] argument can be used to programmatically change the /// currently selected tab. const OBCupertinoTabScaffold({ - Key key, - @required this.tabBar, - @required this.tabBuilder, + Key? key, + required this.tabBar, + required this.tabBuilder, }) : assert(tabBar != null), assert(tabBuilder != null), super(key: key); @@ -141,7 +141,7 @@ class OBCupertinoTabScaffold extends StatefulWidget { } class _OBCupertinoTabScaffoldState extends State { - int _currentPage; + late int _currentPage; @override void initState() { @@ -210,7 +210,7 @@ class _OBCupertinoTabScaffoldState extends State { var changeIndex = true; // Chain the user's original callback. if (widget.tabBar.onTap != null) { - bool changeIndexAllowed = widget.tabBar.onTap(newIndex); + bool? changeIndexAllowed = widget.tabBar.onTap!(newIndex); if (changeIndexAllowed != null && !changeIndexAllowed) changeIndex = false; } @@ -236,9 +236,9 @@ class _OBCupertinoTabScaffoldState extends State { /// at a time and on stage. Off stage tabs' animations are stopped. class _TabSwitchingView extends StatefulWidget { const _TabSwitchingView({ - @required this.currentTabIndex, - @required this.tabNumber, - @required this.tabBuilder, + required this.currentTabIndex, + required this.tabNumber, + required this.tabBuilder, }) : assert(currentTabIndex != null), assert(tabNumber != null && tabNumber > 0), assert(tabBuilder != null); @@ -252,13 +252,13 @@ class _TabSwitchingView extends StatefulWidget { } class _TabSwitchingViewState extends State<_TabSwitchingView> { - List tabs; - List tabFocusNodes; + late List tabs; + late List tabFocusNodes; @override void initState() { super.initState(); - tabs = List(widget.tabNumber); + tabs = List.filled(widget.tabNumber, null); tabFocusNodes = List.generate( widget.tabNumber, (int index) => FocusScopeNode(), diff --git a/lib/pages/waitlist/subscribe_done_step.dart b/lib/pages/waitlist/subscribe_done_step.dart index 49ec2401a..58e0ad97a 100644 --- a/lib/pages/waitlist/subscribe_done_step.dart +++ b/lib/pages/waitlist/subscribe_done_step.dart @@ -5,7 +5,7 @@ import 'package:Okuna/widgets/buttons/success_button.dart'; import 'package:flutter/material.dart'; class WaitlistSubscribeArguments { - int count; + int? count; WaitlistSubscribeArguments({this.count}); @@ -14,7 +14,7 @@ class WaitlistSubscribeArguments { class OBWaitlistSubscribeDoneStep extends StatefulWidget { final int count; - OBWaitlistSubscribeDoneStep({@required this.count}); + OBWaitlistSubscribeDoneStep({required this.count}); @override State createState() { @@ -23,7 +23,7 @@ class OBWaitlistSubscribeDoneStep extends StatefulWidget { } class OBWaitlistSubscribeDoneStepState extends State { - LocalizationService localizationService; + late LocalizationService localizationService; @override Widget build(BuildContext context) { @@ -93,7 +93,7 @@ class OBWaitlistSubscribeDoneStepState extends State { - bool _subscribeInProgress; + late bool _subscribeInProgress; final GlobalKey _formKey = GlobalKey(); - bool _isSubmitted; - UserService _userService; - LocalizationService _localizationService; - ValidationService _validationService; - ToastService _toastService; + late bool _isSubmitted; + late UserService _userService; + late LocalizationService _localizationService; + late ValidationService _validationService; + late ToastService _toastService; TextEditingController _emailController = TextEditingController(); @@ -81,17 +81,17 @@ class OBWaitlistSubscribePageState extends State { ); } - bool _validateForm() { + bool? _validateForm() { if (!_isSubmitted) return null; - return _formKey.currentState.validate(); + return _formKey.currentState?.validate(); } void onPressedNextStep(BuildContext context) async { if (_subscribeInProgress) return; _isSubmitted = true; - bool isEmailValid = _validateForm(); + bool? isEmailValid = _validateForm(); - if (!isEmailValid) return; + if (isEmailValid == null || !isEmailValid) return; _setSubscribeInProgress(true); try { @@ -122,7 +122,7 @@ class OBWaitlistSubscribePageState extends State { ); } - Widget _buildPreviousButton({@required BuildContext context}) { + Widget _buildPreviousButton({required BuildContext context}) { String buttonText = _localizationService.trans('auth__create_acc__previous'); return OBSecondaryButton( @@ -149,7 +149,7 @@ class OBWaitlistSubscribePageState extends State { ); } - Widget _buildSubscribeEmailText({@required BuildContext context}) { + Widget _buildSubscribeEmailText({required BuildContext context}) { String subscribeEmailText = _localizationService .trans('auth__create_acc__subscribe_to_waitlist_text'); @@ -185,9 +185,9 @@ class OBWaitlistSubscribePageState extends State { child: OBAuthTextField( autocorrect: false, hintText: emailInputPlaceholder, - validator: (String email) { - String validateEMail = - _validationService.validateUserEmail(email.trim()); + validator: (String? email) { + String? validateEMail = + _validationService.validateUserEmail(email?.trim()); if (validateEMail != null) return validateEMail; }, controller: _emailController, @@ -203,8 +203,8 @@ class OBWaitlistSubscribePageState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/plugins/share/share.dart b/lib/plugins/share/share.dart index afb7a367c..979a73380 100644 --- a/lib/plugins/share/share.dart +++ b/lib/plugins/share/share.dart @@ -4,10 +4,10 @@ class Share { static const String TEXT = 'text'; static const String ERROR = 'error'; - final String image; - final String video; - final String text; - final String error; + final String? image; + final String? video; + final String? text; + final String? error; const Share({ this.image, @@ -17,10 +17,11 @@ class Share { }); static Share fromReceived(Map received) { - String text; - String image; - String video; - String error; + String? text; + String? image; + String? video; + String? error; + if (received.containsKey(TEXT)) { text = received[TEXT]; } @@ -33,6 +34,7 @@ class Share { if (received.containsKey(ERROR)) { error = received[ERROR]; } + return Share(image: image, video: video, text: text, error: error); } } diff --git a/lib/provider.dart b/lib/provider.dart index fae3f9da0..a7d98618c 100644 --- a/lib/provider.dart +++ b/lib/provider.dart @@ -54,7 +54,7 @@ import 'package:sentry/sentry.dart'; class OpenbookProvider extends StatefulWidget { final Widget child; - const OpenbookProvider({Key key, @required this.child}) : super(key: key); + const OpenbookProvider({Key? key, required this.child}) : super(key: key); @override OpenbookProviderState createState() { @@ -64,7 +64,7 @@ class OpenbookProvider extends StatefulWidget { static OpenbookProviderState of(BuildContext context) { return (context.dependOnInheritedWidgetOfExactType<_OpenbookProvider>() as _OpenbookProvider) - .data; + .data!; } } @@ -105,7 +105,7 @@ class OpenbookProviderState extends State { NavigationService navigationService = NavigationService(); WaitlistApiService waitlistApiService = WaitlistApiService(); - LocalizationService localizationService; + late LocalizationService localizationService; UniversalLinksService universalLinksService = UniversalLinksService(); BottomSheetService bottomSheetService = BottomSheetService(); PushNotificationsService pushNotificationsService = @@ -120,13 +120,13 @@ class OpenbookProviderState extends State { ConnectivityService connectivityService = ConnectivityService(); DraftService draftService = DraftService(); - SentryClient sentryClient; + late SentryClient sentryClient; @override void initState() { super.initState(); initAsyncState(); - imageCache.maximumSize = 200 << 20; // 200MB + imageCache?.maximumSize = 200 << 20; // 200MB userPreferencesService.setStorageService(storageService); userPreferencesService.setConnectivityService(connectivityService); exploreTimelinePreferencesService.setStorageService(storageService); @@ -232,7 +232,9 @@ class OpenbookProviderState extends State { iosApiKey: environment.intercomIosKey, androidApiKey: environment.intercomAndroidKey, appId: environment.intercomAppId); - sentryClient = SentryClient(SentryOptions(dsn: environment.sentryDsn)); + if (environment.sentryDsn.isNotEmpty == true) { + sentryClient = SentryClient(SentryOptions(dsn: environment.sentryDsn)); + } utilsService.setTrustedProxyUrl(environment.linkPreviewsTrustedProxyUrl); await connectivityService.bootstrap(); @@ -275,9 +277,9 @@ class OpenbookProviderState extends State { } class _OpenbookProvider extends InheritedWidget { - final OpenbookProviderState data; + final OpenbookProviderState? data; - _OpenbookProvider({Key key, this.data, Widget child}) + _OpenbookProvider({Key? key, this.data, required Widget child}) : super(key: key, child: child); @override diff --git a/lib/services/auth_api.dart b/lib/services/auth_api.dart index 368442c88..839c996ed 100644 --- a/lib/services/auth_api.dart +++ b/lib/services/auth_api.dart @@ -6,10 +6,10 @@ import 'package:Okuna/services/string_template.dart'; import 'package:meta/meta.dart'; class AuthApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const CHECK_USERNAME_PATH = 'api/auth/username-check/'; static const CHECK_EMAIL_PATH = 'api/auth/email-check/'; @@ -55,23 +55,23 @@ class AuthApiService { apiURL = newApiURL; } - Future deleteUser({@required String password}) { + Future deleteUser({required String password}) { Map body = {'password': password}; return _httpService.post('$apiURL$DELETE_ACCOUNT_PATH', body: body, appendAuthorizationToken: true); } - Future checkUsernameIsAvailable({@required String username}) { + Future checkUsernameIsAvailable({required String username}) { return _httpService .postJSON('$apiURL$CHECK_USERNAME_PATH', body: {'username': username}); } - Future checkEmailIsAvailable({@required String email}) { + Future checkEmailIsAvailable({required String email}) { return _httpService .postJSON('$apiURL$CHECK_EMAIL_PATH', body: {'email': email}); } - Future updateUserEmail({@required String email}) { + Future updateUserEmail({required String email}) { Map body = {}; body['email'] = email; return _httpService.patchMultiform('$apiURL$UPDATE_EMAIL_PATH', @@ -79,7 +79,7 @@ class AuthApiService { } Future updateUserPassword( - {@required String currentPassword, @required String newPassword}) { + {required String currentPassword, required String newPassword}) { Map body = {}; body['current_password'] = currentPassword; body['new_password'] = newPassword; @@ -96,14 +96,14 @@ class AuthApiService { Future updateUser({ dynamic avatar, dynamic cover, - String name, - String username, - String url, - bool followersCountVisible, - bool communityPostsVisible, - String bio, - String location, - String visibility, + String? name, + String? username, + String? url, + bool? followersCountVisible, + bool? communityPostsVisible, + String? bio, + String? location, + String? visibility, }) { Map body = {}; @@ -144,14 +144,14 @@ class AuthApiService { } Future createUser( - {@required String email, - @required String token, - @required String name, - @required String username, - @required bool isOfLegalAge, - @required bool areGuidelinesAccepted, - @required String password, - File avatar}) { + {required String email, + required String token, + required String name, + required String username, + required bool isOfLegalAge, + required bool areGuidelinesAccepted, + required String password, + File? avatar}) { Map body = { 'email': email, 'token': token, @@ -171,7 +171,7 @@ class AuthApiService { } Future verifyRegisterToken( - {@required String token}) { + {required String token}) { Map body = {'token': token}; return _httpService.post('$apiURL$VERIFY_REGISTER_TOKEN', @@ -205,7 +205,7 @@ class AuthApiService { } Future searchLinkedUsers( - {@required String query, int count, String withCommunity}) { + {required String query, int? count, String? withCommunity}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -218,9 +218,9 @@ class AuthApiService { Future getLinkedUsers( {bool authenticatedRequest = true, - int maxId, - int count, - String withCommunity}) { + int? maxId, + int? count, + String? withCommunity}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -235,7 +235,7 @@ class AuthApiService { } Future searchBlockedUsers( - {@required String query, int count}) { + {required String query, int? count}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -246,8 +246,8 @@ class AuthApiService { Future getBlockedUsers({ bool authenticatedRequest = true, - int maxId, - int count, + int? maxId, + int? count, }) { Map queryParams = {}; @@ -280,7 +280,7 @@ class AuthApiService { return _httpService.delete(_makeApiUrl(path), appendAuthorizationToken: true); } - Future searchFollowers({@required String query, int count}) { + Future searchFollowers({required String query, int? count}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -290,7 +290,7 @@ class AuthApiService { } Future getFollowers( - {bool authenticatedRequest = true, int maxId, int count}) { + {bool authenticatedRequest = true, int? maxId, int? count}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -302,7 +302,7 @@ class AuthApiService { appendAuthorizationToken: authenticatedRequest); } - Future searchFollowings({@required String query, int count}) { + Future searchFollowings({required String query, int? count}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -313,8 +313,8 @@ class AuthApiService { Future getFollowings({ bool authenticatedRequest = true, - int maxId, - int count, + int? maxId, + int? count, }) { Map queryParams = {}; @@ -328,13 +328,13 @@ class AuthApiService { } Future loginWithCredentials( - {@required String username, @required String password}) { + {required String username, required String password}) { return this._httpService.postJSON('$apiURL$LOGIN_PATH', body: {'username': username, 'password': password}); } - Future requestPasswordReset({@required String email}) { + Future requestPasswordReset({required String email}) { var body = {}; if (email != null && email != '') { body['email'] = email; @@ -345,7 +345,7 @@ class AuthApiService { } Future verifyPasswordReset( - {String newPassword, String passwordResetToken}) { + {String? newPassword, String? passwordResetToken}) { return this._httpService.postJSON('$apiURL$VERIFY_RESET_PASSWORD_PATH', body: {'new_password': newPassword, 'token': passwordResetToken}); } @@ -357,20 +357,20 @@ class AuthApiService { } Future updateAuthenticatedUserNotificationsSettings({ - bool postCommentNotifications, - bool postCommentReplyNotifications, - bool postCommentReactionNotifications, - bool postCommentUserMentionNotifications, - bool postUserMentionNotifications, - bool postReactionNotifications, - bool followNotifications, - bool followRequestNotifications, - bool followRequestApprovedNotifications, - bool connectionRequestNotifications, - bool connectionConfirmedNotifications, - bool communityInviteNotifications, - bool communityNewPostNotifications, - bool userNewPostNotifications, + bool? postCommentNotifications, + bool? postCommentReplyNotifications, + bool? postCommentReactionNotifications, + bool? postCommentUserMentionNotifications, + bool? postUserMentionNotifications, + bool? postReactionNotifications, + bool? followNotifications, + bool? followRequestNotifications, + bool? followRequestApprovedNotifications, + bool? connectionRequestNotifications, + bool? connectionConfirmedNotifications, + bool? communityInviteNotifications, + bool? communityNewPostNotifications, + bool? userNewPostNotifications, }) { Map body = {}; @@ -443,9 +443,9 @@ class AuthApiService { } Future reportUserWithUsername( - {@required String userUsername, - @required int moderationCategoryId, - String description}) { + {required String userUsername, + required int moderationCategoryId, + String? description}) { String path = _makeReportUserPath(username: userUsername); Map body = {'category_id': moderationCategoryId.toString()}; @@ -473,7 +473,7 @@ class AuthApiService { .parse(ENABLE_NEW_POST_NOTIFICATIONS_FOR_USER_PATH, {'userUsername': username}); } - String _makeReportUserPath({@required username}) { + String _makeReportUserPath({required username}) { return _stringTemplateService .parse(REPORT_USER_PATH, {'userUsername': username}); } diff --git a/lib/services/bottom_sheet.dart b/lib/services/bottom_sheet.dart index 7c38c8e2d..2c2fc977e 100644 --- a/lib/services/bottom_sheet.dart +++ b/lib/services/bottom_sheet.dart @@ -39,7 +39,7 @@ class BottomSheetService { bool hasActiveBottomSheet = false; Future showReactToPost( - {@required Post post, @required BuildContext context}) async { + {required Post post, required BuildContext context}) async { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -50,9 +50,9 @@ class BottomSheetService { } Future showReactToPostComment( - {@required PostComment postComment, - @required Post post, - @required BuildContext context}) async { + {required PostComment postComment, + required Post post, + required BuildContext context}) async { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -64,11 +64,11 @@ class BottomSheetService { } void showConnectionsCirclesPicker( - {@required BuildContext context, - @required String title, - @required String actionLabel, - @required OnPickedCircles onPickedCircles, - List initialPickedCircles}) { + {required BuildContext context, + required String title, + required String actionLabel, + required OnPickedCircles onPickedCircles, + List? initialPickedCircles}) { _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -82,20 +82,20 @@ class BottomSheetService { } Future showCommunityTypePicker( - {@required BuildContext context, - ValueChanged onChanged, - CommunityType initialType}) { + {required BuildContext context, + ValueChanged? onChanged, + CommunityType? initialType}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { return OBCommunityTypePickerBottomSheet( - onTypeChanged: onChanged, initialType: initialType); + onTypeChanged: onChanged ?? (_) {}, initialType: initialType); }); } Future showUserVisibilityPicker( - {@required BuildContext context}) { + {required BuildContext context}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -104,58 +104,58 @@ class BottomSheetService { } Future showVideosSoundSettingPicker( - {@required BuildContext context, - ValueChanged onChanged, - VideosSoundSetting initialValue}) { + {required BuildContext context, + ValueChanged? onChanged, + VideosSoundSetting? initialValue}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { return OBVideosSoundSettingPickerBottomSheet( - onTypeChanged: onChanged, initialValue: initialValue); + onTypeChanged: onChanged ?? (_) {}, initialValue: initialValue); }); } Future showHashtagsDisplaySettingPicker( - {@required BuildContext context, - ValueChanged onChanged, - HashtagsDisplaySetting initialValue}) { + {required BuildContext context, + ValueChanged? onChanged, + HashtagsDisplaySetting? initialValue}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { return OBHashtagsDisplaySettingPickerBottomSheet( - onTypeChanged: onChanged, initialValue: initialValue); + onTypeChanged: onChanged ?? (_) {}, initialValue: initialValue); }); } Future showVideosAutoPlaySettingPicker( - {@required BuildContext context, - ValueChanged onChanged, - VideosAutoPlaySetting initialValue}) { + {required BuildContext context, + ValueChanged? onChanged, + VideosAutoPlaySetting? initialValue}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { return OBVideosAutoPlaySettingPickerBottomSheet( - onTypeChanged: onChanged, initialValue: initialValue); + onTypeChanged: onChanged ?? (_) {}, initialValue: initialValue); }); } Future showLinkPreviewsSettingPicker( - {@required BuildContext context, - ValueChanged onChanged, - LinkPreviewsSetting initialValue}) { + {required BuildContext context, + ValueChanged? onChanged, + LinkPreviewsSetting? initialValue}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { return OBLinkPreviewsSettingPickerBottomSheet( - onTypeChanged: onChanged, initialValue: initialValue); + onTypeChanged: onChanged ?? (_) {}, initialValue: initialValue); }); } - Future> showFollowsListsPicker( - {@required BuildContext context, - @required String title, - @required String actionLabel, - List initialPickedFollowsLists}) { + Future?> showFollowsListsPicker( + {required BuildContext context, + required String title, + required String actionLabel, + List? initialPickedFollowsLists}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -168,15 +168,15 @@ class BottomSheetService { } Future showPostActions( - {@required BuildContext context, - @required Post post, - @required OBPostDisplayContext displayContext, - @required OnPostDeleted onPostDeleted, - @required ValueChanged onPostReported, - ValueChanged onPostCommunityExcludedFromProfilePosts, - Function onCommunityExcluded, - Function onUndoCommunityExcluded, - List initialPickedFollowsLists}) { + {required BuildContext context, + required Post post, + required OBPostDisplayContext displayContext, + required OnPostDeleted? onPostDeleted, + required ValueChanged? onPostReported, + ValueChanged? onPostCommunityExcludedFromProfilePosts, + Function? onCommunityExcluded, + Function? onUndoCommunityExcluded, + List? initialPickedFollowsLists}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -186,16 +186,16 @@ class BottomSheetService { onCommunityExcluded: onCommunityExcluded, onUndoCommunityExcluded: onUndoCommunityExcluded, onPostCommunityExcludedFromProfilePosts: onPostCommunityExcludedFromProfilePosts, - onPostDeleted: onPostDeleted, - onPostReported: onPostReported, + onPostDeleted: onPostDeleted ?? (_) {}, + onPostReported: onPostReported ?? (_) {}, ); }); } Future showHashtagActions( - {@required BuildContext context, - @required Hashtag hashtag, - @required ValueChanged onHashtagReported}) { + {required BuildContext context, + required Hashtag hashtag, + required ValueChanged onHashtagReported}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -207,7 +207,7 @@ class BottomSheetService { } Future showUserActions( - {@required BuildContext context, @required User user}) { + {required BuildContext context, required User user}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -218,38 +218,38 @@ class BottomSheetService { } Future showCommunityActions( - {@required BuildContext context, - @required Community community, - OnCommunityReported onCommunityReported}) { + {required BuildContext context, + required Community community, + OnCommunityReported? onCommunityReported}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { return OBCommunityActionsBottomSheet( community: community, - onCommunityReported: onCommunityReported, + onCommunityReported: onCommunityReported ?? (_) {}, ); }); } Future showMoreCommentActions({ - @required BuildContext context, - @required Post post, - @required PostComment postComment, - @required ValueChanged onPostCommentDeleted, - @required ValueChanged onPostCommentReported, + required BuildContext context, + required Post post, + required PostComment postComment, + required ValueChanged? onPostCommentDeleted, + required ValueChanged? onPostCommentReported, }) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { return OBPostCommentMoreActionsBottomSheet( - onPostCommentReported: onPostCommentReported, - onPostCommentDeleted: onPostCommentDeleted, + onPostCommentReported: onPostCommentReported ?? (_) {}, + onPostCommentDeleted: onPostCommentDeleted ?? (_) {}, post: post, postComment: postComment); }); } - Future showCameraPicker({@required BuildContext context}) { + Future showCameraPicker({required BuildContext context}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -257,7 +257,7 @@ class BottomSheetService { }); } - Future showVideoPicker({@required BuildContext context}) { + Future showVideoPicker({required BuildContext context}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -265,7 +265,7 @@ class BottomSheetService { }); } - Future showImagePicker({@required BuildContext context}) { + Future showImagePicker({required BuildContext context}) { return _showModalBottomSheetApp( context: context, builder: (BuildContext context) { @@ -274,13 +274,13 @@ class BottomSheetService { } Future showConfirmAction({ - @required BuildContext context, - String title, - String subtitle, - String description, - String confirmText, - String cancelText, - @required ActionCompleter actionCompleter, + required BuildContext context, + String? title, + String? subtitle, + String? description, + String? confirmText, + String? cancelText, + required ActionCompleter actionCompleter, }) { return _showModalBottomSheetApp( context: context, @@ -296,7 +296,7 @@ class BottomSheetService { }); } - void dismissActiveBottomSheet({@required BuildContext context}) async { + void dismissActiveBottomSheet({required BuildContext context}) async { if (this.hasActiveBottomSheet) { Navigator.of(context, rootNavigator: true).pop(); this.hasActiveBottomSheet = true; @@ -304,7 +304,7 @@ class BottomSheetService { } Future _showModalBottomSheetApp( - {BuildContext context, WidgetBuilder builder}) async { + {required BuildContext context, required WidgetBuilder builder}) async { dismissActiveBottomSheet(context: context); hasActiveBottomSheet = true; final result = @@ -353,7 +353,7 @@ class _ModalBottomSheetLayout extends SingleChildLayoutDelegate { } class _ModalBottomSheet extends StatefulWidget { - const _ModalBottomSheet({Key key, this.route}) : super(key: key); + const _ModalBottomSheet({Key? key, required this.route}) : super(key: key); final _ModalBottomSheetRoute route; @@ -367,20 +367,20 @@ class _ModalBottomSheetState extends State<_ModalBottomSheet> { return new GestureDetector( onTap: widget.route.dismissOnTap ? () => Navigator.pop(context) : null, child: new AnimatedBuilder( - animation: widget.route.animation, - builder: (BuildContext context, Widget child) { + animation: widget.route.animation!, + builder: (BuildContext context, Widget? child) { double bottomInset = widget.route.resizeToAvoidBottomPadding ? MediaQuery.of(context).viewInsets.bottom : 0.0; return new ClipRect( child: new CustomSingleChildLayout( delegate: new _ModalBottomSheetLayout( - widget.route.animation.value, bottomInset), + widget.route.animation!.value, bottomInset), child: new BottomSheet( animationController: widget.route._animationController, onClosing: () => Navigator.pop(context), - builder: widget.route.builder))); + builder: widget.route.builder!))); })); } } @@ -390,13 +390,13 @@ class _ModalBottomSheetRoute extends PopupRoute { this.builder, this.theme, this.barrierLabel, - RouteSettings settings, - this.resizeToAvoidBottomPadding, - this.dismissOnTap, + RouteSettings? settings, + this.resizeToAvoidBottomPadding = false, + this.dismissOnTap = false, }) : super(settings: settings); - final WidgetBuilder builder; - final ThemeData theme; + final WidgetBuilder? builder; + final ThemeData? theme; final bool resizeToAvoidBottomPadding; final bool dismissOnTap; @@ -407,19 +407,19 @@ class _ModalBottomSheetRoute extends PopupRoute { bool get barrierDismissible => true; @override - final String barrierLabel; + final String? barrierLabel; @override Color get barrierColor => Colors.black54; - AnimationController _animationController; + AnimationController? _animationController; @override AnimationController createAnimationController() { assert(_animationController == null); _animationController = - BottomSheet.createAnimationController(navigator.overlay); - return _animationController; + BottomSheet.createAnimationController(navigator!.overlay!); + return _animationController!; } @override @@ -432,7 +432,7 @@ class _ModalBottomSheetRoute extends PopupRoute { removeTop: true, child: new _ModalBottomSheet(route: this), ); - if (theme != null) bottomSheet = new Theme(data: theme, child: bottomSheet); + if (theme != null) bottomSheet = new Theme(data: theme!, child: bottomSheet); return bottomSheet; } } @@ -463,9 +463,9 @@ class _ModalBottomSheetRoute extends PopupRoute { /// * [showBottomSheet] and [ScaffoldState.showBottomSheet], for showing /// non-modal bottom sheets. /// * -Future showModalBottomSheetApp({ - @required BuildContext context, - @required WidgetBuilder builder, +Future showModalBottomSheetApp({ + required BuildContext context, + required WidgetBuilder builder, bool dismissOnTap: false, bool resizeToAvoidBottomPadding: true, }) { diff --git a/lib/services/categories_api.dart b/lib/services/categories_api.dart index 32c4ab4f5..8ac3a09f9 100644 --- a/lib/services/categories_api.dart +++ b/lib/services/categories_api.dart @@ -1,9 +1,9 @@ import 'package:Okuna/services/httpie.dart'; class CategoriesApiService { - HttpieService _httpService; + late HttpieService _httpService; - String apiURL; + late String apiURL; static const getCategoriesPath = 'api/categories/'; diff --git a/lib/services/communities_api.dart b/lib/services/communities_api.dart index 36e44cfac..76e33ccfe 100644 --- a/lib/services/communities_api.dart +++ b/lib/services/communities_api.dart @@ -5,10 +5,10 @@ import 'package:Okuna/services/string_template.dart'; import 'package:meta/meta.dart'; class CommunitiesApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const SEARCH_COMMUNITIES_PATH = 'api/communities/search/'; static const GET_TRENDING_COMMUNITIES_PATH = 'api/communities/trending/'; @@ -103,13 +103,13 @@ class CommunitiesApiService { apiURL = newApiURL; } - Future checkNameIsAvailable({@required String name}) { + Future checkNameIsAvailable({required String name}) { return _httpService.postJSON('$apiURL$CHECK_COMMUNITY_NAME_PATH', body: {'name': name}, appendAuthorizationToken: true); } Future getTrendingCommunities( - {bool authenticatedRequest = true, String category}) { + {bool authenticatedRequest = true, String? category}) { Map queryParams = {}; if (category != null) queryParams['category'] = category; @@ -127,9 +127,9 @@ class CommunitiesApiService { Future createPostForCommunityWithId( String communityName, - {String text, - File image, - File video, + {String? text, + File? image, + File? video, bool isDraft = false}) { Map body = {}; @@ -156,7 +156,7 @@ class CommunitiesApiService { } Future getPostsForCommunityWithName(String communityName, - {int maxId, int count, bool authenticatedRequest = true}) { + {int? maxId, int? count, bool authenticatedRequest = true}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -180,8 +180,8 @@ class CommunitiesApiService { Future getClosedPostsForCommunityWithName( String communityName, - {int maxId, - int count, + {int? maxId, + int? count, bool authenticatedRequest = true}) { Map queryParams = {}; @@ -198,8 +198,8 @@ class CommunitiesApiService { Future searchCommunitiesWithQuery( {bool authenticatedRequest = true, - @required String query, - bool excludedFromProfilePosts}) { + required String query, + bool? excludedFromProfilePosts}) { Map queryParams = {'query': query}; if (excludedFromProfilePosts != null) @@ -219,18 +219,18 @@ class CommunitiesApiService { } Future createCommunity( - {@required String name, - @required String title, - @required List categories, - @required String type, - bool invitesEnabled, - String color, - String userAdjective, - String usersAdjective, - String description, - String rules, - File cover, - File avatar}) { + {required String name, + required String title, + required List categories, + required String type, + bool? invitesEnabled, + String? color, + String? userAdjective, + String? usersAdjective, + String? description, + String? rules, + File? cover, + File? avatar}) { Map body = { 'name': name, 'title': title, @@ -275,16 +275,16 @@ class CommunitiesApiService { } Future updateCommunityWithName(String communityName, - {String name, - String title, - List categories, - bool invitesEnabled, - String type, - String color, - String userAdjective, - String usersAdjective, - String description, - String rules}) { + {String? name, + String? title, + List? categories, + bool? invitesEnabled, + String? type, + String? color, + String? userAdjective, + String? usersAdjective, + String? description, + String? rules}) { Map body = {}; if (name != null) { @@ -335,7 +335,7 @@ class CommunitiesApiService { Future updateAvatarForCommunityWithName( String communityName, - {File avatar}) { + {File? avatar}) { Map body = {'avatar': avatar}; return _httpService.putMultiform( @@ -353,7 +353,7 @@ class CommunitiesApiService { Future updateCoverForCommunityWithName( String communityName, - {File cover}) { + {File? cover}) { Map body = {'cover': cover}; return _httpService.putMultiform( @@ -376,7 +376,7 @@ class CommunitiesApiService { } Future getMembersForCommunityWithId(String communityName, - {int count, int maxId, List exclude}) { + {int? count, int? maxId, List? exclude}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -391,9 +391,9 @@ class CommunitiesApiService { } Future searchMembers( - {@required String communityName, - @required String query, - List exclude}) { + {required String communityName, + required String query, + List? exclude}) { Map queryParams = {'query': query}; if (exclude != null && exclude.isNotEmpty) queryParams['exclude'] = exclude; @@ -405,7 +405,7 @@ class CommunitiesApiService { } Future inviteUserToCommunity( - {@required String communityName, @required String username}) { + {required String communityName, required String username}) { Map body = {'username': username}; String path = _makeInviteUserToCommunityPath(communityName); return _httpService.post(_makeApiUrl(path), @@ -413,7 +413,7 @@ class CommunitiesApiService { } Future uninviteUserFromCommunity( - {@required String communityName, @required String username}) { + {required String communityName, required String username}) { Map body = {'username': username}; String path = _makeUninviteUserToCommunityPath(communityName); return _httpService.post(_makeApiUrl(path), @@ -422,8 +422,8 @@ class CommunitiesApiService { Future getJoinedCommunities( {bool authenticatedRequest = true, - int offset, - bool excludedFromProfilePosts}) { + int? offset, + bool? excludedFromProfilePosts}) { Map queryParams = {'offset': offset}; if (excludedFromProfilePosts != null) @@ -435,8 +435,8 @@ class CommunitiesApiService { } Future searchJoinedCommunities({ - @required String query, - int count, + required String query, + int? count, }) { Map queryParams = {'query': query}; @@ -457,7 +457,7 @@ class CommunitiesApiService { } Future getModeratorsForCommunityWithId(String communityName, - {int count, int maxId}) { + {int? count, int? maxId}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -470,8 +470,8 @@ class CommunitiesApiService { } Future searchModerators({ - @required String communityName, - @required String query, + required String communityName, + required String query, }) { Map queryParams = {'query': query}; @@ -482,7 +482,7 @@ class CommunitiesApiService { } Future addCommunityModerator( - {@required String communityName, @required String username}) { + {required String communityName, required String username}) { Map body = {'username': username}; String path = _makeAddCommunityModeratorPath(communityName); @@ -491,7 +491,7 @@ class CommunitiesApiService { } Future removeCommunityModerator( - {@required String communityName, @required String username}) { + {required String communityName, required String username}) { String path = _makeRemoveCommunityModeratorPath(communityName, username); return _httpService.delete(_makeApiUrl(path), appendAuthorizationToken: true); @@ -499,8 +499,8 @@ class CommunitiesApiService { Future getAdministratorsForCommunityWithName( String communityName, - {int count, - int maxId}) { + {int? count, + int? maxId}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -513,8 +513,8 @@ class CommunitiesApiService { } Future searchAdministrators({ - @required String communityName, - @required String query, + required String communityName, + required String query, }) { Map queryParams = {'query': query}; @@ -525,7 +525,7 @@ class CommunitiesApiService { } Future addCommunityAdministrator( - {@required String communityName, @required String username}) { + {required String communityName, required String username}) { Map body = {'username': username}; String path = _makeAddCommunityAdministratorPath(communityName); @@ -534,7 +534,7 @@ class CommunitiesApiService { } Future removeCommunityAdministrator( - {@required String communityName, @required String username}) { + {required String communityName, required String username}) { String path = _makeRemoveCommunityAdministratorPath(communityName, username); return _httpService.delete(_makeApiUrl(path), @@ -542,7 +542,7 @@ class CommunitiesApiService { } Future getBannedUsersForCommunityWithId(String communityName, - {int count, int maxId}) { + {int? count, int? maxId}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -555,8 +555,8 @@ class CommunitiesApiService { } Future searchBannedUsers({ - @required String communityName, - @required String query, + required String communityName, + required String query, }) { Map queryParams = {'query': query}; @@ -567,7 +567,7 @@ class CommunitiesApiService { } Future banCommunityUser( - {@required String communityName, @required String username}) { + {required String communityName, required String username}) { Map body = {'username': username}; String path = _makeBanCommunityUserPath(communityName); return _httpService.postJSON(_makeApiUrl(path), @@ -575,7 +575,7 @@ class CommunitiesApiService { } Future unbanCommunityUser( - {@required String communityName, @required String username}) { + {required String communityName, required String username}) { Map body = {'username': username}; String path = _makeUnbanCommunityUserPath(communityName); return _httpService.post(_makeApiUrl(path), @@ -583,14 +583,14 @@ class CommunitiesApiService { } Future getFavoriteCommunities( - {bool authenticatedRequest = true, int offset}) { + {bool authenticatedRequest = true, int? offset}) { return _httpService.get('$apiURL$GET_FAVORITE_COMMUNITIES_PATH', appendAuthorizationToken: authenticatedRequest, queryParameters: {'offset': offset}); } Future searchFavoriteCommunities( - {@required String query, int count}) { + {required String query, int? count}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -599,20 +599,20 @@ class CommunitiesApiService { queryParameters: queryParams, appendAuthorizationToken: true); } - Future favoriteCommunity({@required String communityName}) { + Future favoriteCommunity({required String communityName}) { String path = _makeFavoriteCommunityPath(communityName); return _httpService.putJSON(_makeApiUrl(path), appendAuthorizationToken: true); } - Future unfavoriteCommunity({@required String communityName}) { + Future unfavoriteCommunity({required String communityName}) { String path = _makeFavoriteCommunityPath(communityName); return _httpService.delete(_makeApiUrl(path), appendAuthorizationToken: true); } Future enableNewPostNotificationsForCommunity( - {@required String communityName}) { + {required String communityName}) { String path = _makeEnableNewPostNotificationsForCommunityPath(communityName); return _httpService.putJSON(_makeApiUrl(path), @@ -620,7 +620,7 @@ class CommunitiesApiService { } Future disableNewPostNotificationsForCommunity( - {@required String communityName}) { + {required String communityName}) { String path = _makeEnableNewPostNotificationsForCommunityPath(communityName); return _httpService.delete(_makeApiUrl(path), @@ -628,14 +628,14 @@ class CommunitiesApiService { } Future getAdministratedCommunities( - {bool authenticatedRequest = true, int offset}) { + {bool authenticatedRequest = true, int? offset}) { return _httpService.get('$apiURL$GET_ADMINISTRATED_COMMUNITIES_PATH', appendAuthorizationToken: authenticatedRequest, queryParameters: {'offset': offset}); } Future searchAdministratedCommunities( - {@required String query, int count}) { + {required String query, int? count}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -645,7 +645,7 @@ class CommunitiesApiService { } Future searchModeratedCommunities( - {@required String query, int count}) { + {required String query, int? count}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -655,16 +655,16 @@ class CommunitiesApiService { } Future getModeratedCommunities( - {bool authenticatedRequest = true, int offset}) { + {bool authenticatedRequest = true, int? offset}) { return _httpService.get('$apiURL$GET_MODERATED_COMMUNITIES_PATH', appendAuthorizationToken: authenticatedRequest, queryParameters: {'offset': offset}); } Future reportCommunityWithName( - {@required String communityName, - @required int moderationCategoryId, - String description}) { + {required String communityName, + required int moderationCategoryId, + String? description}) { String path = _makeReportCommunityPath(communityName); Map body = { @@ -680,13 +680,13 @@ class CommunitiesApiService { } Future getModeratedObjects({ - @required String communityName, - int count, - int maxId, - String type, - bool verified, - List statuses, - List types, + required String communityName, + int? count, + int? maxId, + String? type, + bool? verified, + List? statuses, + List? types, }) { Map queryParams = {}; if (count != null) queryParams['count'] = count; diff --git a/lib/services/connections_api.dart b/lib/services/connections_api.dart index 72508319d..4752e0532 100644 --- a/lib/services/connections_api.dart +++ b/lib/services/connections_api.dart @@ -1,9 +1,9 @@ import 'package:Okuna/services/httpie.dart'; class ConnectionsApiService { - HttpieService _httpService; + late HttpieService _httpService; - String apiURL; + late String apiURL; static const CONNECT_WITH_USER_PATH = 'api/connections/connect/'; static const DISCONNECT_FROM_USER_PATH = 'api/connections/disconnect/'; @@ -19,7 +19,7 @@ class ConnectionsApiService { } Future connectWithUserWithUsername(String username, - {List circlesIds}) { + {List? circlesIds}) { Map body = {'username': username}; if (circlesIds != null) body['circles_ids'] = circlesIds; @@ -29,7 +29,7 @@ class ConnectionsApiService { } Future confirmConnectionWithUserWithUsername(String username, - {List circlesIds}) { + {List? circlesIds}) { Map body = {'username': username}; if (circlesIds != null) body['circles_ids'] = circlesIds; @@ -44,7 +44,7 @@ class ConnectionsApiService { } Future updateConnectionWithUsername(String username, - {List circlesIds}) { + {List? circlesIds}) { Map body = {'username': username}; if (circlesIds != null) body['circles_ids'] = circlesIds; diff --git a/lib/services/connections_circles_api.dart b/lib/services/connections_circles_api.dart index 188992003..5d45b1c1c 100644 --- a/lib/services/connections_circles_api.dart +++ b/lib/services/connections_circles_api.dart @@ -4,10 +4,10 @@ import 'package:Okuna/services/string_template.dart'; import 'package:meta/meta.dart'; class ConnectionsCirclesApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const GET_CIRCLES_PATH = 'api/circles/'; static const CREATE_CIRCLE_PATH = 'api/circles/'; @@ -33,7 +33,7 @@ class ConnectionsCirclesApiService { return _httpService.get(url, appendAuthorizationToken: true); } - Future createCircle({@required String name, String color}) { + Future createCircle({required String name, String? color}) { String url = _makeApiUrl(CREATE_CIRCLE_PATH); Map body = {'name': name}; @@ -44,7 +44,7 @@ class ConnectionsCirclesApiService { } Future updateCircleWithId(int circleId, - {String name, String color, List usernames}) { + {String? name, String? color, List? usernames}) { Map body = {}; if (color != null) body['color'] = color; @@ -68,7 +68,7 @@ class ConnectionsCirclesApiService { return _httpService.get(url, appendAuthorizationToken: true); } - Future checkNameIsAvailable({@required String name}) { + Future checkNameIsAvailable({required String name}) { return _httpService.postJSON('$apiURL$CHECK_NAME_PATH', body: {'name': name}, appendAuthorizationToken: true); } diff --git a/lib/services/connectivity.dart b/lib/services/connectivity.dart index 04c232961..dd302f23b 100644 --- a/lib/services/connectivity.dart +++ b/lib/services/connectivity.dart @@ -3,8 +3,8 @@ import 'dart:async'; import 'package:connectivity/connectivity.dart'; class ConnectivityService { - StreamSubscription _connectivityChangeSubscription; - ConnectivityResult _connectivity; + late StreamSubscription _connectivityChangeSubscription; + late ConnectivityResult _connectivity; Future bootstrap() async { _connectivity = await Connectivity().checkConnectivity(); diff --git a/lib/services/date_picker.dart b/lib/services/date_picker.dart index a5f0c02f9..09c794a58 100644 --- a/lib/services/date_picker.dart +++ b/lib/services/date_picker.dart @@ -6,11 +6,11 @@ class DatePickerService { static const double DATE_PICKER_HEIGHT = 250; Future pickDate( - {@required BuildContext context, - @required DateTime initialDate, - DateTime minimumDate, - DateTime maximumDate, - ValueChanged onDateChanged}) { + {required BuildContext context, + required DateTime initialDate, + DateTime? minimumDate, + DateTime? maximumDate, + required ValueChanged onDateChanged}) { // This should also take into account months and days, not only years // See https://github.com/flutter/flutter/issues/24820 @@ -20,8 +20,8 @@ class DatePickerService { return ConstrainedBox( constraints: BoxConstraints(maxHeight: DATE_PICKER_HEIGHT), child: CupertinoDatePicker( - minimumYear: minimumDate.year, - maximumYear: maximumDate.year, + minimumYear: minimumDate?.year ?? 1, + maximumYear: maximumDate?.year, mode: CupertinoDatePickerMode.date, initialDateTime: initialDate, onDateTimeChanged: onDateChanged), diff --git a/lib/services/devices_api.dart b/lib/services/devices_api.dart index 4e33f6a2d..1b2eded82 100644 --- a/lib/services/devices_api.dart +++ b/lib/services/devices_api.dart @@ -3,10 +3,10 @@ import 'package:Okuna/services/string_template.dart'; import 'package:meta/meta.dart'; class DevicesApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const DEVICES_PATH = 'api/devices/'; static const DEVICE_PATH = 'api/devices/{deviceUuid}/'; @@ -34,7 +34,7 @@ class DevicesApiService { } Future createDevice( - {@required String uuid, String name}) { + {required String uuid, String? name}) { String url = _makeApiUrl(DEVICES_PATH); Map body = {'uuid': uuid}; @@ -45,7 +45,7 @@ class DevicesApiService { } Future updateDeviceWithUuid(String deviceUuid, - {String name}) { + {String? name}) { String url = _makeDevicePath(deviceUuid); Map body = {}; diff --git a/lib/services/dialog.dart b/lib/services/dialog.dart index 804b164e4..f1d66a535 100644 --- a/lib/services/dialog.dart +++ b/lib/services/dialog.dart @@ -14,8 +14,8 @@ import 'package:video_player/video_player.dart'; import 'package:wakelock/wakelock.dart'; class DialogService { - ThemeService _themeService; - ThemeValueParserService _themeValueParserService; + late ThemeService _themeService; + late ThemeValueParserService _themeValueParserService; void setThemeService(ThemeService themeService) { _themeService = themeService; @@ -27,9 +27,9 @@ class DialogService { } Future showColorPicker({ - @required ValueChanged onColorChanged, - @required BuildContext context, - @required Color initialColor, + required ValueChanged onColorChanged, + required BuildContext context, + required Color initialColor, bool enableAlpha = false, }) { return showAlert( @@ -46,7 +46,7 @@ class DialogService { } Future showZoomablePhotoBoxView( - {@required String imageUrl, @required BuildContext context}) { + {required String imageUrl, required BuildContext context}) { return showGeneralDialog( context: context, pageBuilder: (BuildContext buildContext, Animation animation, @@ -68,12 +68,12 @@ class DialogService { } Future showVideo( - {String videoUrl, - File video, - VideoPlayerController videoPlayerController, - ChewieController chewieController, + {String? videoUrl, + File? video, + VideoPlayerController? videoPlayerController, + ChewieController? chewieController, bool autoPlay: true, - @required BuildContext context}) async { + required BuildContext context}) async { SystemChrome.setEnabledSystemUIOverlays([]); Wakelock.enable(); await showGeneralDialog( @@ -122,10 +122,10 @@ class DialogService { } Future showAlert( - {@required Widget content, - List actions, - Widget title, - @required BuildContext context}) { + {required Widget content, + List? actions, + Widget? title, + required BuildContext context}) { return showDialog( context: context, builder: (BuildContext context) { diff --git a/lib/services/documents.dart b/lib/services/documents.dart index c02c29b3d..9382d2012 100644 --- a/lib/services/documents.dart +++ b/lib/services/documents.dart @@ -1,7 +1,7 @@ import 'package:Okuna/services/httpie.dart'; class DocumentsService { - HttpieService _httpService; + late HttpieService _httpService; static const guidelinesUrl = 'https://about.okuna.io/docs/COMMUNITY_GUIDELINES.md'; diff --git a/lib/services/draft.dart b/lib/services/draft.dart index 8de89d7e9..402229e47 100644 --- a/lib/services/draft.dart +++ b/lib/services/draft.dart @@ -5,10 +5,10 @@ class DraftService { Map _drafts = LinkedHashMap(); - String getCommentDraft(int postId, [int commentId]) => + String getCommentDraft(int postId, [int? commentId]) => _drafts[_buildCommentKey(postId, commentId)] ?? ''; - String getPostDraft([int communityId]) => + String getPostDraft([int? communityId]) => _drafts[_buildPostKey(communityId)] ?? ''; void _set(String key, String text) { @@ -16,7 +16,7 @@ class DraftService { _trimDraftsIfNeeded(); } - void setCommentDraft(String text, int postId, [int commentId]) { + void setCommentDraft(String text, int postId, [int? commentId]) { if (text.trim().isNotEmpty) { _set(_buildCommentKey(postId, commentId), text); } else { @@ -24,7 +24,7 @@ class DraftService { } } - void setPostDraft(String text, [int communityId]) { + void setPostDraft(String text, [int? communityId]) { if (text.trim().isNotEmpty) { _set(_buildPostKey(communityId), text); } else { @@ -35,7 +35,7 @@ class DraftService { void removeCommentDraft(int postId, [commentId]) => _drafts.remove(_buildCommentKey(postId, commentId)); - void removePostDraft([int communityId]) => + void removePostDraft([int? communityId]) => _drafts.remove(_buildPostKey(communityId)); void _trimDraftsIfNeeded() { @@ -48,8 +48,8 @@ class DraftService { _drafts.clear(); } - String _buildCommentKey(int postId, int commentId) => + String _buildCommentKey(int postId, int? commentId) => 'c|$postId|${commentId ?? "-1"}'; - String _buildPostKey(int communityId) => 'p|${communityId ?? "-1"}'; + String _buildPostKey(int? communityId) => 'p|${communityId ?? "-1"}'; } diff --git a/lib/services/emoji_picker.dart b/lib/services/emoji_picker.dart index a51224b3e..3514483d0 100644 --- a/lib/services/emoji_picker.dart +++ b/lib/services/emoji_picker.dart @@ -5,7 +5,7 @@ import 'package:meta/meta.dart'; class EmojiPickerService { Future pickEmoji( - {@required BuildContext context, @required OnEmojiPicked onEmojiPicked}) { + {required BuildContext context, required OnEmojiPicked onEmojiPicked}) { return showModalBottomSheet( context: context, builder: (BuildContext context) { diff --git a/lib/services/emojis_api.dart b/lib/services/emojis_api.dart index 6b617f611..d42cb067e 100644 --- a/lib/services/emojis_api.dart +++ b/lib/services/emojis_api.dart @@ -1,9 +1,9 @@ import 'package:Okuna/services/httpie.dart'; class EmojisApiService { - HttpieService _httpService; + late HttpieService _httpService; - String apiURL; + late String apiURL; static const GET_EMOJI_GROUPS_PATH = 'api/emojis/groups/'; diff --git a/lib/services/environment_loader.dart b/lib/services/environment_loader.dart index 07bb814be..8bc733e03 100644 --- a/lib/services/environment_loader.dart +++ b/lib/services/environment_loader.dart @@ -3,12 +3,12 @@ import 'dart:convert' show json; import 'package:flutter/services.dart' show rootBundle; class EnvironmentLoader { - final String environmentPath; + final String? environmentPath; EnvironmentLoader({this.environmentPath}); Future load() { - return rootBundle.loadStructuredData(this.environmentPath, + return rootBundle.loadStructuredData(this.environmentPath!, (jsonStr) async { final environmentLoader = Environment.fromJson(json.decode(jsonStr)); return environmentLoader; diff --git a/lib/services/explore_timeline_preferences.dart b/lib/services/explore_timeline_preferences.dart index bed08dd77..522f3f8c2 100644 --- a/lib/services/explore_timeline_preferences.dart +++ b/lib/services/explore_timeline_preferences.dart @@ -4,7 +4,7 @@ import 'package:Okuna/services/storage.dart'; import 'package:rxdart/rxdart.dart'; class ExploreTimelinePreferencesService { - OBStorage _storage; + late OBStorage _storage; static const excludeJoinedCommunitiesStorageKey = 'excludeJoinedCommunitiesSetting'; @@ -32,8 +32,8 @@ class ExploreTimelinePreferencesService { } Future getExcludeJoinedCommunitiesSetting() async { - String rawValue = await _storage.get(excludeJoinedCommunitiesStorageKey, - defaultValue: 'true'); + String rawValue = (await _storage.get(excludeJoinedCommunitiesStorageKey, + defaultValue: 'true'))!; return rawValue == 'true'; } @@ -47,4 +47,4 @@ class ExploreTimelinePreferencesService { _excludeJoinedCommunitiesSettingChangeSubject.close(); } -} \ No newline at end of file +} diff --git a/lib/services/follows_api.dart b/lib/services/follows_api.dart index 743ed11d2..c2652e985 100644 --- a/lib/services/follows_api.dart +++ b/lib/services/follows_api.dart @@ -1,9 +1,9 @@ import 'package:Okuna/services/httpie.dart'; class FollowsApiService { - HttpieService _httpService; + late HttpieService _httpService; - String apiURL; + late String apiURL; static const FOLLOW_USER_PATH = 'api/follows/follow/'; static const REQUEST_TO_FOLLOW_USER_PATH = 'api/follows/requests/'; @@ -54,8 +54,8 @@ class FollowsApiService { } Future getReceivedFollowRequests( { - int maxId, - int count,}) { + int? maxId, + int? count,}) { Map queryParams = {}; @@ -69,7 +69,7 @@ class FollowsApiService { } Future followUserWithUsername(String username, - {List listsIds}) { + {List? listsIds}) { Map body = {'username': username}; if (listsIds != null) body['lists_ids'] = listsIds; @@ -84,7 +84,7 @@ class FollowsApiService { } Future updateFollowWithUsername(String username, - {List listsIds}) { + {List? listsIds}) { Map body = {'username': username}; if (listsIds != null) body['lists_ids'] = listsIds; diff --git a/lib/services/follows_lists_api.dart b/lib/services/follows_lists_api.dart index 882f07857..b16590ea3 100644 --- a/lib/services/follows_lists_api.dart +++ b/lib/services/follows_lists_api.dart @@ -4,10 +4,10 @@ import 'package:Okuna/services/string_template.dart'; import 'package:meta/meta.dart'; class FollowsListsApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const GET_LISTS_PATH = 'api/lists/'; static const CREATE_LIST_PATH = 'api/lists/'; @@ -33,7 +33,7 @@ class FollowsListsApiService { return _httpService.get(url, appendAuthorizationToken: true); } - Future createList({@required String name, int emojiId}) { + Future createList({required String name, int? emojiId}) { String url = _makeApiUrl(CREATE_LIST_PATH); Map body = {'name': name}; @@ -44,7 +44,7 @@ class FollowsListsApiService { } Future updateListWithId(int listId, - {String name, int emojiId, List usernames}) { + {String? name, int? emojiId, List? usernames}) { Map body = {}; if (emojiId != null) body['emoji_id'] = emojiId; @@ -68,7 +68,7 @@ class FollowsListsApiService { return _httpService.get(url, appendAuthorizationToken: true); } - Future checkNameIsAvailable({@required String name}) { + Future checkNameIsAvailable({required String name}) { return _httpService.postJSON('$apiURL$CHECK_NAME_PATH', body: {'name': name}, appendAuthorizationToken: true); } diff --git a/lib/services/hashtags_api.dart b/lib/services/hashtags_api.dart index d4d78505f..c14d15d43 100644 --- a/lib/services/hashtags_api.dart +++ b/lib/services/hashtags_api.dart @@ -3,10 +3,10 @@ import 'package:Okuna/services/string_template.dart'; import 'package:meta/meta.dart'; class HashtagsApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const SEARCH_HASHTAGS_PATH = 'api/hashtags/search/'; static const GET_TRENDING_HASHTAGS_PATH = 'api/hashtags/trending/'; @@ -46,7 +46,7 @@ class HashtagsApiService { } Future getHashtagsWithQuery( - {bool authenticatedRequest = true, @required String query}) { + {bool authenticatedRequest = true, required String query}) { Map queryParams = {'query': query}; return _httpService.get('$apiURL$SEARCH_HASHTAGS_PATH', @@ -62,9 +62,9 @@ class HashtagsApiService { } Future reportHashtagWithName( - {@required String hashtagName, - @required int moderationCategoryId, - String description}) { + {required String hashtagName, + required int moderationCategoryId, + String? description}) { String path = _makeReportHashtagPath(hashtagName); Map body = { @@ -80,7 +80,7 @@ class HashtagsApiService { } Future getPostsForHashtagWithName(String hashtagName, - {int maxId, int count, bool authenticatedRequest = true}) { + {int? maxId, int? count, bool authenticatedRequest = true}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; diff --git a/lib/services/httpie.dart b/lib/services/httpie.dart index f0fabf837..40917cd47 100644 --- a/lib/services/httpie.dart +++ b/lib/services/httpie.dart @@ -12,12 +12,12 @@ import 'package:http_retry/http_retry.dart'; export 'package:http/http.dart'; class HttpieService { - LocalizationService _localizationService; - UtilsService _utilsService; - String authorizationToken; - String magicHeaderName; - String magicHeaderValue; - Client client; + late LocalizationService _localizationService; + late UtilsService _utilsService; + String? authorizationToken; + String? magicHeaderName; + String? magicHeaderValue; + late Client client; HttpieService() { client = IOClient(); @@ -37,7 +37,7 @@ class HttpieService { authorizationToken = token; } - String getAuthorizationToken() { + String? getAuthorizationToken() { return authorizationToken; } @@ -59,27 +59,27 @@ class HttpieService { } void setProxy(String proxy) { - var overrides = HttpOverrides.current as HttpieOverrides; + var overrides = HttpOverrides.current as HttpieOverrides?; if (overrides != null) { overrides.setProxy(proxy); } } Future post(url, - {Map headers, + {Map? headers, body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) async { + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) async { var finalHeaders = _getHeadersWithConfig( headers: headers, appendLanguageHeader: appendLanguageHeader, appendAuthorizationToken: appendAuthorizationToken); - Response response; + Response? response; try { - response = await client.post(url, + response = await client.post(Uri.parse(url), headers: finalHeaders, body: body, encoding: encoding); } catch (error) { _handleRequestError(error); @@ -89,20 +89,20 @@ class HttpieService { } Future put(url, - {Map headers, + {Map? headers, body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) async { + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) async { var finalHeaders = _getHeadersWithConfig( headers: headers, appendLanguageHeader: appendLanguageHeader, appendAuthorizationToken: appendAuthorizationToken); - Response response; + Response? response; try { - response = await client.put(url, + response = await client.put(Uri.parse(url), headers: finalHeaders, body: body, encoding: encoding); } catch (error) { _handleRequestError(error); @@ -111,20 +111,20 @@ class HttpieService { } Future patch(url, - {Map headers, + {Map? headers, body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) async { + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) async { var finalHeaders = _getHeadersWithConfig( headers: headers, appendLanguageHeader: appendLanguageHeader, appendAuthorizationToken: appendAuthorizationToken); - Response response; + Response? response; try { - response = await client.patch(url, + response = await client.patch(Uri.parse(url), headers: finalHeaders, body: body, encoding: encoding); } catch (error) { _handleRequestError(error); @@ -134,18 +134,18 @@ class HttpieService { } Future delete(url, - {Map headers, - bool appendLanguageHeader, - bool appendAuthorizationToken}) async { + {Map? headers, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) async { var finalHeaders = _getHeadersWithConfig( headers: headers, appendLanguageHeader: appendLanguageHeader, appendAuthorizationToken: appendAuthorizationToken); - Response response; + Response? response; try { - response = await client.delete(url, headers: finalHeaders); + response = await client.delete(Uri.parse(url), headers: finalHeaders); } catch (error) { _handleRequestError(error); } @@ -156,9 +156,9 @@ class HttpieService { Future postJSON(url, {Map headers = const {}, body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) { + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) { String jsonBody = json.encode(body); Map jsonHeaders = _getJsonHeaders(); @@ -176,9 +176,9 @@ class HttpieService { Future putJSON(url, {Map headers = const {}, body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) { + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) { String jsonBody = json.encode(body); Map jsonHeaders = _getJsonHeaders(); @@ -196,9 +196,9 @@ class HttpieService { Future patchJSON(url, {Map headers = const {}, body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) { + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) { String jsonBody = json.encode(body); Map jsonHeaders = _getJsonHeaders(); @@ -214,10 +214,10 @@ class HttpieService { } Future get(url, - {Map headers, - Map queryParameters, - bool appendLanguageHeader, - bool appendAuthorizationToken}) async { + {Map? headers, + Map? queryParameters, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) async { var finalHeaders = _getHeadersWithConfig( headers: headers, appendLanguageHeader: appendLanguageHeader, @@ -227,10 +227,10 @@ class HttpieService { url = url + _makeQueryString(queryParameters); } - Response response; + Response? response; try { - response = await client.get(url, headers: finalHeaders); + response = await client.get(Uri.parse(url), headers: finalHeaders); } catch (error) { _handleRequestError(error); } @@ -239,11 +239,11 @@ class HttpieService { } Future postMultiform(String url, - {Map headers, - Map body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) { + {Map? headers, + Map? body, + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) { return _multipartRequest(url, method: 'POST', headers: headers, @@ -254,11 +254,11 @@ class HttpieService { } Future patchMultiform(String url, - {Map headers, - Map body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) { + {Map? headers, + Map? body, + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) { return _multipartRequest(url, method: 'PATCH', headers: headers, @@ -269,11 +269,11 @@ class HttpieService { } Future putMultiform(String url, - {Map headers, - Map body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) { + {Map? headers, + Map? body, + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) { return _multipartRequest(url, method: 'PUT', headers: headers, @@ -284,12 +284,12 @@ class HttpieService { } Future _multipartRequest(String url, - {Map headers, - String method, - Map body, - Encoding encoding, - bool appendLanguageHeader, - bool appendAuthorizationToken}) async { + {Map? headers, + required String method, + Map? body, + Encoding? encoding, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) async { var request = new http.MultipartRequest(method, Uri.parse(url)); var finalHeaders = _getHeadersWithConfig( @@ -301,35 +301,38 @@ class HttpieService { List fileFields = []; - List bodyKeys = body.keys.toList(); + List? bodyKeys = body?.keys.toList(); - for (final String key in bodyKeys) { - dynamic value = body[key]; - if (value is String || value is bool) { - request.fields[key] = value.toString(); - } else if (value is List) { - request.fields[key] = - value.map((item) => item.toString()).toList().join(','); - } else if (value is File) { - String fileMimeType = await _utilsService.getFileMimeType(value) ?? - 'application/octet-stream'; + if (bodyKeys != null) { + for (final String key in bodyKeys) { + dynamic value = body![key]; + if (value is String || value is bool) { + request.fields[key] = value.toString(); + } else if (value is List) { + request.fields[key] = + value.map((item) => item.toString()).toList().join(','); + } else if (value is File) { + String fileMimeType = await _utilsService.getFileMimeType(value); - String fileExtension = - _utilsService.getFileExtensionForMimeType(fileMimeType); + String? fileExtension = + _utilsService.getFileExtensionForMimeType(fileMimeType); - var bytes = utf8.encode(value.path); - var digest = sha256.convert(bytes); + var bytes = utf8.encode(value.path); + var digest = sha256.convert(bytes); - String newFileName = digest.toString() + '.' + fileExtension; + String newFileName = fileExtension == null + ? digest.toString() + : digest.toString() + '.' + fileExtension; - MediaType fileMediaType = MediaType.parse(fileMimeType); + MediaType fileMediaType = MediaType.parse(fileMimeType); - var fileFuture = http.MultipartFile.fromPath(key, value.path, - filename: newFileName, contentType: fileMediaType); + var fileFuture = http.MultipartFile.fromPath(key, value.path, + filename: newFileName, contentType: fileMediaType); - fileFields.add(fileFuture); - } else { - throw HttpieArgumentsError('Unsupported multiform value type'); + fileFields.add(fileFuture); + } else { + throw HttpieArgumentsError('Unsupported multiform value type'); + } } } @@ -352,9 +355,9 @@ class HttpieService { } Map _getHeadersWithConfig( - {Map headers = const {}, - bool appendLanguageHeader, - bool appendAuthorizationToken}) { + {Map? headers = const {}, + bool? appendLanguageHeader, + bool? appendAuthorizationToken}) { headers = headers ?? {}; Map finalHeaders = Map.from(headers); @@ -369,7 +372,7 @@ class HttpieService { } if (magicHeaderName != null && magicHeaderValue != null) { - finalHeaders[magicHeaderName] = magicHeaderValue; + finalHeaders[magicHeaderName!] = magicHeaderValue!; } return finalHeaders; @@ -377,7 +380,7 @@ class HttpieService { void _handleRequestError(error) { if (error is SocketException) { - var errorCode = error.osError.errorCode; + var errorCode = error.osError?.errorCode; if (errorCode == 61 || errorCode == 60 || errorCode == 111 || @@ -536,7 +539,7 @@ class HttpieRequestError implements Exception { } Future body() async { - String body; + late String body; if (response is HttpieResponse) { HttpieResponse castedResponse = this.response as HttpieResponse; @@ -549,7 +552,7 @@ class HttpieRequestError implements Exception { return body; } - Future toHumanReadableMessage() async { + Future toHumanReadableMessage() async { String errorBody = await body(); try { @@ -576,6 +579,8 @@ class HttpieRequestError implements Exception { } else if (parsedError is List && parsedError.isNotEmpty) { return parsedError.first; } + + return null; } catch (error) { return convertStatusCodeToHumanReadableMessage(response.statusCode); } @@ -611,8 +616,8 @@ class HttpieArgumentsError implements Exception { // used by any other package, as long as they're running inside a zone with // these set. class HttpieOverrides extends HttpOverrides { - String _proxy; - final HttpOverrides _previous = HttpOverrides.current; + String? _proxy; + final HttpOverrides? _previous = HttpOverrides.current; HttpieOverrides(); @@ -621,15 +626,15 @@ class HttpieOverrides extends HttpOverrides { } @override - HttpClient createHttpClient(SecurityContext context) { - if (_previous != null) return _previous.createHttpClient(context); + HttpClient createHttpClient(SecurityContext? context) { + if (_previous != null) return _previous!.createHttpClient(context); return super.createHttpClient(context); } @override - String findProxyFromEnvironment(Uri uri, Map environment) { - if (_proxy != null) return _proxy; - if (_previous != null) return _previous.findProxyFromEnvironment(uri, environment); + String findProxyFromEnvironment(Uri uri, Map? environment) { + if (_proxy != null) return _proxy!; + if (_previous != null) return _previous!.findProxyFromEnvironment(uri, environment); return super.findProxyFromEnvironment(uri, environment); } } diff --git a/lib/services/intercom.dart b/lib/services/intercom.dart index 85283175f..ee65ce9e2 100644 --- a/lib/services/intercom.dart +++ b/lib/services/intercom.dart @@ -7,20 +7,20 @@ import 'package:meta/meta.dart'; import 'package:intercom_flutter/intercom_flutter.dart'; class IntercomService { - UserService _userService; + late UserService _userService; - String iosApiKey; - String androidApiKey; - String appId; + late String iosApiKey; + late String androidApiKey; + late String appId; void setUserService(UserService userService) { _userService = userService; } void bootstrap( - {@required String iosApiKey, - @required String androidApiKey, - @required String appId}) async { + {required String iosApiKey, + required String androidApiKey, + required String appId}) async { this.iosApiKey = iosApiKey; this.androidApiKey = androidApiKey; this.appId = appId; @@ -34,7 +34,7 @@ class IntercomService { Future enableIntercom() async { await disableIntercom(); - User loggedInUser = _userService.getLoggedInUser(); + User? loggedInUser = _userService.getLoggedInUser(); if (loggedInUser == null) throw 'Cannot enable intercom. Not logged in.'; assert(loggedInUser.uuid != null && loggedInUser.id != null); @@ -48,7 +48,7 @@ class IntercomService { } String _makeUserId(User user) { - var bytes = utf8.encode(user.uuid + user.id.toString()); + var bytes = utf8.encode(user.uuid! + user.id.toString()); var digest = sha256.convert(bytes); return digest.toString(); } diff --git a/lib/services/localization.dart b/lib/services/localization.dart index 43b3860b4..f58937ea1 100644 --- a/lib/services/localization.dart +++ b/lib/services/localization.dart @@ -38,12 +38,12 @@ class LocalizationService { } static LocalizationService of(BuildContext context) { - StreamSubscription _onLoggedInUserChangeSubscription; + late StreamSubscription _onLoggedInUserChangeSubscription; var openbookProvider = OpenbookProvider.of(context); _onLoggedInUserChangeSubscription = - openbookProvider.userService.loggedInUserChange.listen((User newUser) { - String _userLanguageCode = newUser != null && newUser.hasLanguage() - ? newUser.language.code + openbookProvider.userService.loggedInUserChange.listen((User? newUser) { + String? _userLanguageCode = newUser != null && newUser.hasLanguage() + ? newUser.language?.code : null; Locale _currentLocale = Localizations.localeOf(context); if (_userLanguageCode != null && @@ -58,7 +58,7 @@ class LocalizationService { _onLoggedInUserChangeSubscription.cancel(); }); - return Localizations.of(context, LocalizationService); + return Localizations.of(context, LocalizationService)!; } String trans(String key) { diff --git a/lib/services/media/media.dart b/lib/services/media/media.dart index 31d6d07c3..36818ee5f 100644 --- a/lib/services/media/media.dart +++ b/lib/services/media/media.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:io'; +import 'dart:typed_data'; import 'package:Okuna/plugins/image_converter/image_converter.dart'; import 'package:Okuna/services/bottom_sheet.dart'; @@ -34,12 +35,12 @@ class MediaService { Map _thumbnail_cache = {}; - ValidationService _validationService; - BottomSheetService _bottomSheetService; - LocalizationService _localizationService; - ToastService _toastService; - PermissionsService _permissionsService; - UtilsService _utilsService; + late ValidationService _validationService; + late BottomSheetService _bottomSheetService; + late LocalizationService _localizationService; + late ToastService _toastService; + late PermissionsService _permissionsService; + late UtilsService _utilsService; void setLocalizationService(LocalizationService localizationService) { _localizationService = localizationService; @@ -72,22 +73,22 @@ class MediaService { /// /// The returned file may be either an image or a video. Use [MediaFile.type] /// to determine which one it is. - Future pickMedia( - {@required BuildContext context, - @required ImageSource source, - bool flattenGifs}) async { - MediaFile media; + Future pickMedia( + {required BuildContext context, + required ImageSource source, + bool flattenGifs = false}) async { + MediaFile? media; if (source == ImageSource.gallery) { bool permissionGranted = await _permissionsService.requestStoragePermissions(context: context); if (permissionGranted) { - FilePickerResult result = + FilePickerResult? result = await FilePicker.platform.pickFiles(type: FileType.media); if (result != null) { - File file = File(result.files.single.path); - FileType type = await getMediaType(file); + File file = File(result.files.single.path!); + FileType type = (await getMediaType(file))!; media = MediaFile(file, type); } } @@ -115,9 +116,9 @@ class MediaService { /// /// The returned file should always point to an image. If a GIF is picked it will /// be flattened. - Future pickImage( - {@required OBImageType imageType, @required BuildContext context}) async { - File pickedImage = + Future pickImage( + {required OBImageType imageType, required BuildContext context}) async { + File? pickedImage = await _bottomSheetService.showImagePicker(context: context); if (pickedImage == null) return null; @@ -129,15 +130,15 @@ class MediaService { imageType: imageType, ); - return media.file; + return media?.file; } /// Opens a bottom sheet with the option to pick a video from gallery or take /// a new one with the camera. /// /// The returned file should always point to a video. - Future pickVideo({@required BuildContext context}) async { - File pickedVideo = + Future pickVideo({required BuildContext context}) async { + File? pickedVideo = await _bottomSheetService.showVideoPicker(context: context); if (pickedVideo == null) return null; @@ -147,16 +148,16 @@ class MediaService { context: context, ); - return media.file; + return media?.file; } - Future processMedia( - {@required MediaFile media, - @required BuildContext context, + Future processMedia( + {required MediaFile media, + required BuildContext context, bool flattenGifs = false, OBImageType imageType = OBImageType.post}) async { var mediaType = media.type; - MediaFile result; + MediaFile? result; // Copy the media to a temporary location. final tempPath = await _getTempPath(); @@ -190,7 +191,7 @@ class MediaService { return result; } - Future _processImage(MediaFile media, String tempPath, + Future _processImage(MediaFile media, String tempPath, String mediaUuid, OBImageType imageType) async { var image = await fixExifRotation(media.file, deleteOriginal: true); String processedImageName = mediaUuid + '.jpg'; @@ -215,9 +216,11 @@ class MediaService { double ratioX = IMAGE_RATIOS[imageType]['x']; double ratioY = IMAGE_RATIOS[imageType]['y']; - File croppedFile = + File? croppedFile = await cropImage(processedImage, ratioX: ratioX, ratioY: ratioY); + if (croppedFile == null) return null; + result = MediaFile(croppedFile, media.type); } @@ -235,7 +238,7 @@ class MediaService { Future fixExifRotation(File image, {deleteOriginal: false}) async { List imageBytes = await image.readAsBytes(); - List result = await FlutterImageCompress.compressWithList(imageBytes, + List result = await FlutterImageCompress.compressWithList(Uint8List.fromList(imageBytes), quality: 100, rotate: 0); final String processedImageUuid = _uuid.v4(); @@ -293,7 +296,7 @@ class MediaService { final String thumbnailPath = '$tempPath/$tmpImageName'; final file = File(thumbnailPath); _thumbnail_cache[videoFile.path] = file; - file.writeAsBytesSync(thumbnailData); + file.writeAsBytesSync(thumbnailData!.toList()); return file; } @@ -321,7 +324,7 @@ class MediaService { } Future compressImage(File image) async { - List compressedImageData = await FlutterImageCompress.compressWithFile( + Uint8List? compressedImageData = await FlutterImageCompress.compressWithFile( image.absolute.path, quality: 80, ); @@ -331,7 +334,7 @@ class MediaService { final tempPath = await _getTempPath(); final String thumbnailPath = '$tempPath/$tmpImageName'; final file = File(thumbnailPath); - file.writeAsBytesSync(compressedImageData); + file.writeAsBytesSync(compressedImageData!.toList()); return file; } @@ -388,7 +391,7 @@ class MediaService { return mediaMimeSubtype == 'gif'; } - Future getMediaType(File file) async { + Future getMediaType(File file) async { String mediaMime = await _utilsService.getFileMimeType(file); String mediaMimeType = mediaMime.split('/')[0]; @@ -404,7 +407,7 @@ class MediaService { } } - Future cropImage(File image, {double ratioX, double ratioY}) async { + Future cropImage(File image, {double? ratioX, double? ratioY}) async { return ImageCropper.cropImage( sourcePath: image.path, aspectRatio: ratioX != null && ratioY != null diff --git a/lib/services/modal_service.dart b/lib/services/modal_service.dart index 535dd3fbc..044baa8ea 100644 --- a/lib/services/modal_service.dart +++ b/lib/services/modal_service.dart @@ -39,19 +39,19 @@ import 'package:flutter/material.dart'; import 'localization.dart'; class ModalService { - LocalizationService localizationService; + late LocalizationService localizationService; void setLocalizationService(localizationService) { this.localizationService = localizationService; } - Future openCreatePost( - {@required BuildContext context, - Community community, - String text, - File image, - File video}) async { - OBNewPostData createPostData = + Future openCreatePost( + {required BuildContext context, + Community? community, + String? text, + File? image, + File? video}) async { + OBNewPostData? createPostData = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -69,9 +69,9 @@ class ModalService { return createPostData; } - Future openEditPost( - {@required BuildContext context, @required Post post}) async { - Post editedPost = await Navigator.of(context, rootNavigator: true) + Future openEditPost( + {required BuildContext context, required Post post}) async { + Post? editedPost = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -85,11 +85,11 @@ class ModalService { return editedPost; } - Future openExpandedCommenter( - {@required BuildContext context, - @required PostComment postComment, - @required Post post}) async { - PostComment editedComment = await Navigator.of(context, rootNavigator: true) + Future openExpandedCommenter( + {required BuildContext context, + required PostComment postComment, + required Post post}) async { + PostComment? editedComment = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -103,13 +103,13 @@ class ModalService { return editedComment; } - Future openExpandedReplyCommenter( - {@required BuildContext context, - @required PostComment postComment, - @required Post post, - @required Function(PostComment) onReplyAdded, - @required Function(PostComment) onReplyDeleted}) async { - PostComment replyComment = await Navigator.of(context, rootNavigator: true) + Future openExpandedReplyCommenter( + {required BuildContext context, + required PostComment postComment, + required Post post, + required Function(PostComment)? onReplyAdded, + required Function(PostComment)? onReplyDeleted}) async { + PostComment? replyComment = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -125,9 +125,9 @@ class ModalService { } Future openEditProfile( - {@required User user, - @required BuildContext context, - VoidCallback onUserProfileUpdated}) async { + {required User user, + required BuildContext context, + VoidCallback? onUserProfileUpdated}) async { Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -137,9 +137,9 @@ class ModalService { ))); } - Future openCreateFollowsList( - {@required BuildContext context}) async { - FollowsList createdFollowsList = + Future openCreateFollowsList( + {required BuildContext context}) async { + FollowsList? createdFollowsList = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -152,10 +152,10 @@ class ModalService { return createdFollowsList; } - Future openEditFollowsList( - {@required FollowsList followsList, - @required BuildContext context}) async { - FollowsList editedFollowsList = + Future openEditFollowsList( + {required FollowsList followsList, + required BuildContext context}) async { + FollowsList? editedFollowsList = await Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -167,24 +167,26 @@ class ModalService { return editedFollowsList; } - Future openCreateConnectionsCircle( - {@required BuildContext context}) async { - Circle createdConnectionsCircle = + Future openCreateConnectionsCircle( + {required BuildContext context}) async { + Circle? createdConnectionsCircle = await Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { - return OBSaveConnectionsCircleModal( - autofocusNameTextField: true, - ); + return Material( + child: OBSaveConnectionsCircleModal( + autofocusNameTextField: true, + ) + ) })); return createdConnectionsCircle; } - Future openEditConnectionsCircle( - {@required Circle connectionsCircle, - @required BuildContext context}) async { - Circle editedConnectionsCircle = + Future openEditConnectionsCircle( + {required Circle connectionsCircle, + required BuildContext context}) async { + Circle? editedConnectionsCircle = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -199,9 +201,9 @@ class ModalService { return editedConnectionsCircle; } - Future openEditCommunity( - {@required BuildContext context, @required Community community}) async { - Community editedCommunity = await Navigator.of(context, rootNavigator: true) + Future openEditCommunity( + {required BuildContext context, required Community community}) async { + Community? editedCommunity = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -215,8 +217,8 @@ class ModalService { return editedCommunity; } - Future openInviteToCommunity( - {@required BuildContext context, @required Community community}) async { + Future openInviteToCommunity( + {required BuildContext context, required Community community}) async { return Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -229,9 +231,9 @@ class ModalService { })); } - Future openCreateCommunity( - {@required BuildContext context}) async { - Community createdCommunity = + Future openCreateCommunity( + {required BuildContext context}) async { + Community? createdCommunity = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -244,9 +246,9 @@ class ModalService { return createdCommunity; } - Future openAddCommunityAdministrator( - {@required BuildContext context, @required Community community}) async { - User addedCommunityAdministrator = + Future openAddCommunityAdministrator( + {required BuildContext context, required Community community}) async { + User? addedCommunityAdministrator = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -261,9 +263,9 @@ class ModalService { return addedCommunityAdministrator; } - Future openAddCommunityModerator( - {@required BuildContext context, @required Community community}) async { - User addedCommunityModerator = + Future openAddCommunityModerator( + {required BuildContext context, required Community community}) async { + User? addedCommunityModerator = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -278,9 +280,9 @@ class ModalService { return addedCommunityModerator; } - Future openBanCommunityUser( - {@required BuildContext context, @required Community community}) async { - User addedCommunityBannedUser = + Future openBanCommunityUser( + {required BuildContext context, required Community community}) async { + User? addedCommunityBannedUser = await Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -296,8 +298,8 @@ class ModalService { } Future openTimelineFilters( - {@required OBTimelinePageController timelineController, - @required BuildContext context}) { + {required OBTimelinePageController timelineController, + required BuildContext context}) { return Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute( fullscreenDialog: true, @@ -310,9 +312,9 @@ class ModalService { })); } - Future openCreateUserInvite( - {@required BuildContext context}) async { - UserInvite createdUserInvite = + Future openCreateUserInvite( + {required BuildContext context}) async { + UserInvite? createdUserInvite = await Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -324,9 +326,9 @@ class ModalService { return createdUserInvite; } - Future openEditUserInvite( - {@required BuildContext context, @required UserInvite userInvite}) async { - UserInvite editedUserInvite = + Future openEditUserInvite( + {required BuildContext context, required UserInvite userInvite}) async { + UserInvite? editedUserInvite = await Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -340,7 +342,7 @@ class ModalService { } Future openSendUserInviteEmail( - {@required BuildContext context, @required UserInvite userInvite}) async { + {required BuildContext context, required UserInvite userInvite}) async { await Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -352,9 +354,9 @@ class ModalService { } Future openModeratedObjectsFilters( - {@required + {required BuildContext context, - @required + required OBModeratedObjectsPageController moderatedObjectsPageController}) async { await Navigator.of(context).push(CupertinoPageRoute( @@ -366,7 +368,7 @@ class ModalService { })); } - Future openAcceptGuidelines({@required BuildContext context}) async { + Future openAcceptGuidelines({required BuildContext context}) async { await Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -376,9 +378,9 @@ class ModalService { })); } - Future openModeratedObjectUpdateDescription( - {@required BuildContext context, - @required ModeratedObject moderatedObject}) async { + Future openModeratedObjectUpdateDescription( + {required BuildContext context, + required ModeratedObject moderatedObject}) async { return Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -388,9 +390,9 @@ class ModalService { })); } - Future openModeratedObjectUpdateCategory( - {@required BuildContext context, - @required ModeratedObject moderatedObject}) async { + Future openModeratedObjectUpdateCategory( + {required BuildContext context, + required ModeratedObject moderatedObject}) async { return Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -400,9 +402,9 @@ class ModalService { })); } - Future openModeratedObjectUpdateStatus( - {@required BuildContext context, - @required ModeratedObject moderatedObject}) async { + Future openModeratedObjectUpdateStatus( + {required BuildContext context, + required ModeratedObject moderatedObject}) async { return Navigator.of(context).push(CupertinoPageRoute( fullscreenDialog: true, builder: (BuildContext context) { @@ -412,8 +414,8 @@ class ModalService { })); } - Future> openExcludeCommunitiesFromProfilePosts( - {@required BuildContext context}) async { + Future?> openExcludeCommunitiesFromProfilePosts( + {required BuildContext context}) async { return Navigator.of(context, rootNavigator: true) .push(CupertinoPageRoute>( fullscreenDialog: true, diff --git a/lib/services/moderation_api.dart b/lib/services/moderation_api.dart index 7c8fc7e82..686fbe4d4 100644 --- a/lib/services/moderation_api.dart +++ b/lib/services/moderation_api.dart @@ -2,10 +2,10 @@ import 'package:Okuna/services/httpie.dart'; import 'package:Okuna/services/string_template.dart'; class ModerationApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const GET_GLOBAL_MODERATED_OBJECTS_PATH = 'api/moderation/moderated-objects/global/'; @@ -42,12 +42,12 @@ class ModerationApiService { } Future getGlobalModeratedObjects({ - int count, - int maxId, - String type, - bool verified, - List statuses, - List types, + int? count, + int? maxId, + String? type, + bool? verified, + List? statuses, + List? types, }) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -68,8 +68,8 @@ class ModerationApiService { Future getModeratedObjectLogs( int moderatedObjectId, { - int count, - int maxId, + int? count, + int? maxId, }) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -84,8 +84,8 @@ class ModerationApiService { Future getModeratedObjectReports( int moderatedObjectId, { - int count, - int maxId, + int? count, + int? maxId, }) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -104,7 +104,7 @@ class ModerationApiService { return _httpService.get(_makeApiUrl(path), appendAuthorizationToken: true); } - Future getUserModerationPenalties({int maxId, int count}) { + Future getUserModerationPenalties({int? maxId, int? count}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -117,7 +117,7 @@ class ModerationApiService { } Future getUserPendingModeratedObjectsCommunities( - {int maxId, int count}) { + {int? maxId, int? count}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -154,7 +154,7 @@ class ModerationApiService { } Future updateModeratedObjectWithId(int moderatedObjectId, - {String description, int categoryId}) { + {String? description, int? categoryId}) { Map body = {}; if (description != null) body['description'] = description; diff --git a/lib/services/navigation_service.dart b/lib/services/navigation_service.dart index 2f9dbb3dd..802a50ea2 100644 --- a/lib/services/navigation_service.dart +++ b/lib/services/navigation_service.dart @@ -85,7 +85,7 @@ class NavigationService { var rng = new Random(); Future navigateToUserProfile( - {@required User user, @required BuildContext context}) async { + {required User user, required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -99,7 +99,7 @@ class NavigationService { } Future navigateToCommunity( - {@required Community community, @required BuildContext context}) async { + {required Community community, required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -113,7 +113,7 @@ class NavigationService { } Future navigateToCommunityStaffPage( - {@required BuildContext context, @required Community community}) { + {required BuildContext context, required Community community}) { return Navigator.push( context, OBSlideRightRoute( @@ -127,7 +127,7 @@ class NavigationService { } Future navigateToCommunityRulesPage( - {@required BuildContext context, @required Community community}) { + {required BuildContext context, required Community community}) { return Navigator.push( context, OBSlideRightRoute( @@ -140,10 +140,10 @@ class NavigationService { ); } - Future navigateToConfirmAddCommunityAdministrator( - {@required Community community, - @required User user, - @required BuildContext context}) async { + Future navigateToConfirmAddCommunityAdministrator( + {required Community community, + required User user, + required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -158,8 +158,8 @@ class NavigationService { ); } - Future navigateToConfirmDeleteAccount( - {@required String userPassword, @required BuildContext context}) async { + Future navigateToConfirmDeleteAccount( + {required String userPassword, required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -172,7 +172,7 @@ class NavigationService { ); } - Future navigateToDeleteAccount({@required BuildContext context}) async { + Future navigateToDeleteAccount({required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -183,10 +183,10 @@ class NavigationService { ); } - Future navigateToConfirmAddCommunityModerator( - {@required Community community, - @required User user, - @required BuildContext context}) async { + Future navigateToConfirmAddCommunityModerator( + {required Community community, + required User user, + required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -201,10 +201,10 @@ class NavigationService { ); } - Future navigateToConfirmBanCommunityUser( - {@required Community community, - @required User user, - @required BuildContext context}) async { + Future navigateToConfirmBanCommunityUser( + {required Community community, + required User user, + required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -220,7 +220,7 @@ class NavigationService { } Future navigateToManageCommunity( - {@required Community community, @required BuildContext context}) { + {required Community community, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -235,7 +235,7 @@ class NavigationService { } Future navigateToLeaveCommunity( - {@required Community community, @required BuildContext context}) { + {required Community community, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -249,7 +249,7 @@ class NavigationService { } Future navigateToDeleteCommunity( - {@required Community community, @required BuildContext context}) { + {required Community community, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -263,7 +263,7 @@ class NavigationService { } Future navigateToCommunityAdministrators( - {@required Community community, @required BuildContext context}) { + {required Community community, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -278,7 +278,7 @@ class NavigationService { } Future navigateToCommunityMembers( - {@required Community community, @required BuildContext context}) { + {required Community community, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -292,7 +292,7 @@ class NavigationService { } Future navigateToCommunityModerators( - {@required Community community, @required BuildContext context}) { + {required Community community, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -307,7 +307,7 @@ class NavigationService { } Future navigateToCommunityBannedUsers( - {@required Community community, @required BuildContext context}) { + {required Community community, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -322,7 +322,7 @@ class NavigationService { } Future navigateToCommunityClosedPosts( - {@required Community community, @required BuildContext context}) { + {required Community community, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -337,7 +337,7 @@ class NavigationService { } Future navigateToCommentPost( - {@required Post post, @required BuildContext context}) { + {required Post post, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -352,7 +352,7 @@ class NavigationService { } Future navigateToPostComments( - {@required Post post, @required BuildContext context}) { + {required Post post, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -368,11 +368,11 @@ class NavigationService { } Future navigateToPostCommentReplies( - {@required Post post, - @required PostComment postComment, - @required BuildContext context, - Function(PostComment) onReplyDeleted, - Function(PostComment) onReplyAdded}) { + {required Post post, + required PostComment postComment, + required BuildContext context, + Function(PostComment)? onReplyDeleted, + Function(PostComment)? onReplyAdded}) { return Navigator.push( context, OBSlideRightRoute( @@ -391,7 +391,7 @@ class NavigationService { } Future navigateToPostCommentsLinked( - {@required PostComment postComment, @required BuildContext context}) { + {required PostComment postComment, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -408,9 +408,9 @@ class NavigationService { } Future navigateToPostCommentRepliesLinked( - {@required PostComment postComment, - @required PostComment parentComment, - @required BuildContext context}) { + {required PostComment postComment, + required PostComment parentComment, + required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -428,7 +428,7 @@ class NavigationService { ); } - Future navigateToPost({@required Post post, @required BuildContext context}) { + Future navigateToPost({required Post post, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -439,7 +439,7 @@ class NavigationService { ); } - Future navigateToSettingsPage({@required BuildContext context}) { + Future navigateToSettingsPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -450,7 +450,7 @@ class NavigationService { ); } - Future navigateToFollowersPage({@required BuildContext context}) { + Future navigateToFollowersPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -461,7 +461,7 @@ class NavigationService { ); } - Future navigateToFollowingPage({@required BuildContext context}) { + Future navigateToFollowingPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -472,7 +472,7 @@ class NavigationService { ); } - Future navigateToAccountSettingsPage({@required BuildContext context}) { + Future navigateToAccountSettingsPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -483,7 +483,7 @@ class NavigationService { ); } - Future navigateToDeveloperSettingsPage({@required BuildContext context}) { + Future navigateToDeveloperSettingsPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -494,7 +494,7 @@ class NavigationService { ); } - Future navigateToApplicationSettingsPage({@required BuildContext context}) { + Future navigateToApplicationSettingsPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -506,7 +506,7 @@ class NavigationService { ); } - Future navigateToAboutPage({@required BuildContext context}) { + Future navigateToAboutPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -517,7 +517,7 @@ class NavigationService { ); } - Future navigateToThemesPage({@required BuildContext context}) { + Future navigateToThemesPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -528,7 +528,7 @@ class NavigationService { ); } - Future navigateToUsefulLinksPage({@required BuildContext context}) { + Future navigateToUsefulLinksPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -539,7 +539,7 @@ class NavigationService { ); } - Future navigateToCommunityGuidelinesPage({@required BuildContext context}) { + Future navigateToCommunityGuidelinesPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -550,7 +550,7 @@ class NavigationService { ); } - Future navigateToPrivacyPolicyPage({@required BuildContext context}) { + Future navigateToPrivacyPolicyPage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -561,7 +561,7 @@ class NavigationService { ); } - Future navigateToTermsOfUsePage({@required BuildContext context}) { + Future navigateToTermsOfUsePage({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -573,7 +573,7 @@ class NavigationService { } Future navigateToConfirmRejectGuidelinesPage( - {@required BuildContext context}) { + {required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -585,9 +585,9 @@ class NavigationService { ); } - Future navigateToSharePost( - {@required BuildContext context, - @required OBNewPostData createPostData}) { + Future navigateToSharePost( + {required BuildContext context, + required OBNewPostData createPostData}) { return Navigator.push( context, OBSlideRightRoute( @@ -600,9 +600,9 @@ class NavigationService { ); } - Future navigateToSharePostWithCircles( - {@required BuildContext context, - @required OBNewPostData createPostData}) { + Future navigateToSharePostWithCircles( + {required BuildContext context, + required OBNewPostData createPostData}) { return Navigator.push( context, OBSlideRightRoute( @@ -616,9 +616,9 @@ class NavigationService { ); } - Future navigateToSharePostWithCommunity( - {@required BuildContext context, - @required OBNewPostData createPostData}) { + Future navigateToSharePostWithCommunity( + {required BuildContext context, + required OBNewPostData createPostData}) { return Navigator.push( context, OBSlideRightRoute( @@ -632,7 +632,7 @@ class NavigationService { ); } - Future navigateToFollowsLists({@required BuildContext context}) { + Future navigateToFollowsLists({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -643,7 +643,7 @@ class NavigationService { ); } - Future navigateToUserInvites({@required BuildContext context}) { + Future navigateToUserInvites({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -655,7 +655,7 @@ class NavigationService { } Future navigateToShareInvite( - {@required BuildContext context, @required UserInvite userInvite}) { + {required BuildContext context, required UserInvite userInvite}) { return Navigator.push( context, OBSlideRightRoute( @@ -668,7 +668,7 @@ class NavigationService { } Future navigateToInviteDetailPage( - {@required BuildContext context, @required UserInvite userInvite}) { + {required BuildContext context, required UserInvite userInvite}) { return Navigator.push( context, OBSlideRightRoute( @@ -680,7 +680,7 @@ class NavigationService { ); } - Future navigateToConnectionsCircles({@required BuildContext context}) { + Future navigateToConnectionsCircles({required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -692,7 +692,7 @@ class NavigationService { } Future navigateToConnectionsCircle( - {@required Circle connectionsCircle, @required BuildContext context}) { + {required Circle connectionsCircle, required BuildContext context}) { return Navigator.push( context, OBSlideRightRoute( @@ -704,8 +704,8 @@ class NavigationService { } Future navigateToFollowsList({ - @required FollowsList followsList, - @required BuildContext context, + required FollowsList followsList, + required BuildContext context, }) { return Navigator.push( context, @@ -718,10 +718,10 @@ class NavigationService { } Future navigateToPostReactions( - {@required Post post, - @required List reactionsEmojiCounts, - @required BuildContext context, - Emoji reactionEmoji}) { + {required Post post, + required List reactionsEmojiCounts, + required BuildContext context, + Emoji? reactionEmoji}) { return Navigator.push( context, OBSlideRightRoute( @@ -737,11 +737,11 @@ class NavigationService { } Future navigateToPostCommentReactions( - {@required PostComment postComment, - @required Post post, - @required List reactionsEmojiCounts, - @required BuildContext context, - Emoji reactionEmoji}) { + {required PostComment postComment, + required Post post, + required List reactionsEmojiCounts, + required BuildContext context, + Emoji? reactionEmoji}) { return Navigator.push( context, OBSlideRightRoute( @@ -759,7 +759,7 @@ class NavigationService { } Future navigateToNotificationsSettings({ - @required BuildContext context, + required BuildContext context, }) { return Navigator.push( context, @@ -773,7 +773,7 @@ class NavigationService { } Future navigateToUserLanguageSettings({ - @required BuildContext context, + required BuildContext context, }) { return Navigator.push( context, @@ -787,7 +787,7 @@ class NavigationService { } Future navigateToBlockedUsers({ - @required BuildContext context, + required BuildContext context, }) { return Navigator.push( context, @@ -800,7 +800,7 @@ class NavigationService { } Future navigateToTopPostsExcludedCommunities({ - @required BuildContext context, + required BuildContext context, }) { return Navigator.push( context, @@ -813,7 +813,7 @@ class NavigationService { } Future navigateToTopPostsSettings({ - @required BuildContext context, + required BuildContext context, }) { return Navigator.push( context, @@ -826,7 +826,7 @@ class NavigationService { } Future navigateToConfirmBlockUser( - {@required BuildContext context, @required User user}) { + {required BuildContext context, required User user}) { return Navigator.push( context, OBSlideRightRoute( @@ -839,14 +839,14 @@ class NavigationService { ); } - Future navigateToConfirmReportObject( - {@required BuildContext context, - @required dynamic object, - Map extraData, - @required ModerationCategory category}) { + Future navigateToConfirmReportObject( + {required BuildContext context, + required dynamic object, + Map? extraData, + required ModerationCategory category}) { return Navigator.push( context, - OBSlideRightRoute( + OBSlideRightRoute( slidableKey: _getKeyRandomisedWithWord('confirmReportObjectPageRoute'), builder: (BuildContext context) { @@ -859,11 +859,11 @@ class NavigationService { ); } - Future navigateToReportObject( - {@required BuildContext context, - @required dynamic object, - Map extraData, - ValueChanged onObjectReported}) async { + Future navigateToReportObject( + {required BuildContext context, + required dynamic object, + Map? extraData, + ValueChanged? onObjectReported}) async { return Navigator.push( context, OBSlideRightRoute( @@ -878,8 +878,8 @@ class NavigationService { ); } - Future navigateToCommunityModeratedObjects( - {@required BuildContext context, @required Community community}) async { + Future navigateToCommunityModeratedObjects( + {required BuildContext context, required Community community}) async { return Navigator.push( context, OBSlideRightRoute( @@ -893,8 +893,8 @@ class NavigationService { ); } - Future navigateToGlobalModeratedObjects( - {@required BuildContext context}) async { + Future navigateToGlobalModeratedObjects( + {required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -906,9 +906,9 @@ class NavigationService { ); } - Future navigateToModeratedObjectReports( - {@required BuildContext context, - @required ModeratedObject moderatedObject}) async { + Future navigateToModeratedObjectReports( + {required BuildContext context, + required ModeratedObject moderatedObject}) async { return Navigator.push( context, OBSlideRightRoute( @@ -921,9 +921,9 @@ class NavigationService { ); } - Future navigateToModeratedObjectGlobalReview( - {@required BuildContext context, - @required ModeratedObject moderatedObject}) async { + Future navigateToModeratedObjectGlobalReview( + {required BuildContext context, + required ModeratedObject moderatedObject}) async { return Navigator.push( context, OBSlideRightRoute( @@ -937,10 +937,10 @@ class NavigationService { ); } - Future navigateToModeratedObjectCommunityReview( - {@required BuildContext context, - @required Community community, - @required ModeratedObject moderatedObject}) async { + Future navigateToModeratedObjectCommunityReview( + {required BuildContext context, + required Community? community, + required ModeratedObject moderatedObject}) async { return Navigator.push( context, OBSlideRightRoute( @@ -948,15 +948,15 @@ class NavigationService { 'moderatedObjectCommunityReviewPageRoute'), builder: (BuildContext context) { return OBModeratedObjectCommunityReviewPage( - community: community, + community: community!, moderatedObject: moderatedObject, ); }), ); } - Future navigateToMyModerationTasksPage( - {@required BuildContext context}) async { + Future navigateToMyModerationTasksPage( + {required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -967,8 +967,8 @@ class NavigationService { ); } - Future navigateToMyModerationPenaltiesPage( - {@required BuildContext context}) async { + Future navigateToMyModerationPenaltiesPage( + {required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( @@ -981,10 +981,10 @@ class NavigationService { } Future navigateToBlankPageWithWidget( - {@required BuildContext context, - @required String navBarTitle, - @required Key key, - @required Widget widget}) { + {required BuildContext context, + required String navBarTitle, + required Key key, + required Widget widget}) { return Navigator.push( context, OBSlideRightRoute( @@ -1004,24 +1004,24 @@ class NavigationService { } Future navigateToHashtag( - {@required Hashtag hashtag, - String rawHashtagName, - @required BuildContext context}) async { + {required Hashtag hashtag, + String? rawHashtagName, + required BuildContext context}) async { return Navigator.push( context, OBSlideRightRoute( slidableKey: _getKeyRandomisedWithWord('hashtagRoute'), builder: (BuildContext context) { return OBHashtagPage( - hashtag: hashtag, rawHashtagName: rawHashtagName); + hashtag: hashtag, rawHashtagName: rawHashtagName ?? ''); }), ); } Future navigateToProfilePostsExcludedCommunities( - {@required BuildContext context, - ValueChanged onExcludedCommunityRemoved, - ValueChanged> onExcludedCommunitiesAdded}) { + {required BuildContext context, + ValueChanged? onExcludedCommunityRemoved, + ValueChanged>? onExcludedCommunitiesAdded}) { return Navigator.push( context, OBSlideRightRoute( @@ -1035,12 +1035,12 @@ class NavigationService { ); } - Future navigateToManageProfile({ - @required User user, - @required BuildContext context, - VoidCallback onUserProfileUpdated, - ValueChanged onExcludedCommunityRemoved, - ValueChanged> onExcludedCommunitiesAdded, + Future navigateToManageProfile({ + required User user, + required BuildContext context, + VoidCallback? onUserProfileUpdated, + ValueChanged? onExcludedCommunityRemoved, + ValueChanged>? onExcludedCommunitiesAdded, }) async { return Navigator.push( context, @@ -1057,8 +1057,8 @@ class NavigationService { ); } - Future navigateToFollowRequests({ - @required BuildContext context, + Future navigateToFollowRequests({ + required BuildContext context, }) async { return Navigator.push( context, diff --git a/lib/services/notifications_api.dart b/lib/services/notifications_api.dart index 084a3332b..ec5904231 100644 --- a/lib/services/notifications_api.dart +++ b/lib/services/notifications_api.dart @@ -3,10 +3,10 @@ import 'package:Okuna/services/httpie.dart'; import 'package:Okuna/services/string_template.dart'; class NotificationsApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const NOTIFICATIONS_PATH = 'api/notifications/'; static const NOTIFICATIONS_READ_PATH = 'api/notifications/read/'; @@ -28,7 +28,7 @@ class NotificationsApiService { } Future getNotifications( - {int maxId, int count, List types}) { + {int? maxId, int? count, List? types}) { Map queryParams = {}; if (maxId != null) queryParams['max_id'] = maxId; @@ -44,7 +44,7 @@ class NotificationsApiService { } Future getUnreadNotificationsCount( - {int maxId, List types}) { + {int? maxId, List? types}) { Map queryParams = {}; if (maxId != null) queryParams['max_id'] = maxId; @@ -58,7 +58,7 @@ class NotificationsApiService { } Future readNotifications( - {int maxId, List types}) { + {int? maxId, List? types}) { String url = _makeApiUrl(NOTIFICATIONS_READ_PATH); Map body = {}; diff --git a/lib/services/permissions.dart b/lib/services/permissions.dart index fda9cb9de..bf40e850b 100644 --- a/lib/services/permissions.dart +++ b/lib/services/permissions.dart @@ -3,8 +3,8 @@ import 'package:Okuna/services/toast.dart'; import 'package:flutter/material.dart'; class PermissionsService { - ToastService _toastService; - LocalizationService _localizationService; + late ToastService _toastService; + late LocalizationService _localizationService; void setToastService(toastService) { _toastService = toastService; @@ -15,7 +15,7 @@ class PermissionsService { } Future requestStoragePermissions( - {@required BuildContext context}) async { + {required BuildContext context}) async { return _requestPermissionWithErrorMessage( permission: null, errorMessage: @@ -24,7 +24,7 @@ class PermissionsService { } Future requestCameraPermissions( - {@required BuildContext context}) async { + {required BuildContext context}) async { return _requestPermissionWithErrorMessage( permission: null, errorMessage: @@ -33,9 +33,9 @@ class PermissionsService { } Future _requestPermissionWithErrorMessage( - {@required dynamic permission, - @required String errorMessage, - @required BuildContext context}) async { + {required dynamic permission, + required String errorMessage, + required BuildContext context}) async { return true; } } diff --git a/lib/services/posts_api.dart b/lib/services/posts_api.dart index b7351e133..99e2683c6 100644 --- a/lib/services/posts_api.dart +++ b/lib/services/posts_api.dart @@ -5,10 +5,10 @@ import 'package:Okuna/services/string_template.dart'; import 'package:meta/meta.dart'; class PostsApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const GET_POSTS_PATH = 'api/posts/'; static const GET_TOP_POSTS_PATH = 'api/posts/top/'; @@ -98,10 +98,10 @@ class PostsApiService { } Future getTopPosts( - {int maxId, - int minId, - int count, - bool excludeJoinedCommunities, + {int? maxId, + int? minId, + int? count, + bool? excludeJoinedCommunities, bool authenticatedRequest = true}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -119,7 +119,7 @@ class PostsApiService { } Future getTrendingPosts( - {int maxId, int minId, int count, bool authenticatedRequest = true}) { + {int? maxId, int? minId, int? count, bool authenticatedRequest = true}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -133,11 +133,11 @@ class PostsApiService { } Future getTimelinePosts( - {List listIds, - List circleIds, - int maxId, - int count, - String username, + {List? listIds, + List? circleIds, + int? maxId, + int? count, + String? username, bool authenticatedRequest = true}) { Map queryParams = {}; @@ -158,7 +158,7 @@ class PostsApiService { } Future createPost( - {String text, List circleIds, bool isDraft = false}) { + {String? text, List? circleIds, bool isDraft = false}) { Map body = {}; if (text != null && text.length > 0) { @@ -178,7 +178,7 @@ class PostsApiService { } Future addMediaToPost( - {@required File file, @required String postUuid}) { + {required File file, required String postUuid}) { Map body = {'file': file}; String path = _makeAddPostMediaPath(postUuid: postUuid); @@ -187,13 +187,13 @@ class PostsApiService { body: body, appendAuthorizationToken: true); } - Future getPostMedia({@required String postUuid}) { + Future getPostMedia({required String postUuid}) { String path = _makeGetPostMediaPath(postUuid: postUuid); return _httpService.get(_makeApiUrl(path), appendAuthorizationToken: true); } - Future publishPost({@required String postUuid}) { + Future publishPost({required String postUuid}) { String path = _makePublishPostPath(postUuid: postUuid); return _httpService.post(_makeApiUrl(path), appendAuthorizationToken: true); @@ -207,7 +207,7 @@ class PostsApiService { } Future editPost( - {@required String postUuid, String text}) { + {required String postUuid, String? text}) { Map body = {}; body['post_uuid'] = postUuid; @@ -236,7 +236,7 @@ class PostsApiService { } Future getCommentsForPostWithUuid(String postUuid, - {int countMax, int maxId, int countMin, int minId, String sort}) { + {int? countMax, int? maxId, int? countMin, int? minId, String? sort}) { Map queryParams = {}; if (countMax != null) queryParams['count_max'] = countMax; if (countMin != null) queryParams['count_min'] = countMin; @@ -253,7 +253,7 @@ class PostsApiService { Future getRepliesForCommentWithIdForPostWithUuid( String postUuid, int postCommentId, - {int countMax, int maxId, int countMin, int minId, String sort}) { + {int? countMax, int? maxId, int? countMin, int? minId, String? sort}) { Map queryParams = {}; if (countMax != null) queryParams['count_max'] = countMax; if (countMin != null) queryParams['count_min'] = countMin; @@ -269,7 +269,7 @@ class PostsApiService { } Future commentPost( - {@required String postUuid, @required String text}) { + {required String postUuid, required String text}) { Map body = {'text': text}; String path = _makeCommentPostPath(postUuid); @@ -278,9 +278,9 @@ class PostsApiService { } Future editPostComment( - {@required String postUuid, - @required int postCommentId, - @required String text}) { + {required String postUuid, + required int postCommentId, + required String text}) { Map body = {'text': text}; String path = _makeEditCommentPostPath(postUuid, postCommentId); @@ -289,15 +289,15 @@ class PostsApiService { } Future getPostComment( - {@required String postUuid, @required int postCommentId}) { + {required String postUuid, required int postCommentId}) { String path = _makeGetCommentPostPath(postUuid, postCommentId); return _httpService.get(_makeApiUrl(path), appendAuthorizationToken: true); } Future replyPostComment( - {@required String postUuid, - @required int postCommentId, - @required String text}) { + {required String postUuid, + required int postCommentId, + required String text}) { Map body = {'text': text}; String path = _makeReplyCommentPostPath(postUuid, postCommentId); @@ -306,7 +306,7 @@ class PostsApiService { } Future deletePostComment( - {@required postCommentId, @required postUuid}) { + {required postCommentId, required postUuid}) { String path = _makeDeletePostCommentPath( postCommentId: postCommentId, postUuid: postUuid); @@ -315,7 +315,7 @@ class PostsApiService { } Future getReactionsForPostWithUuid(String postUuid, - {int count, int maxId, int emojiId}) { + {int? count, int? maxId, int? emojiId}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -337,7 +337,7 @@ class PostsApiService { } Future reactToPost( - {@required String postUuid, @required int emojiId}) { + {required String postUuid, required int emojiId}) { Map body = {'emoji_id': emojiId}; String path = _makeReactToPostPath(postUuid); @@ -346,7 +346,7 @@ class PostsApiService { } Future deletePostReaction( - {@required postReactionId, @required postUuid}) { + {required postReactionId, required postUuid}) { String path = _makeDeletePostReactionPath( postReactionId: postReactionId, postUuid: postUuid); @@ -355,11 +355,11 @@ class PostsApiService { } Future getReactionsForPostComment( - {@required int postCommentId, - @required String postUuid, - int count, - int maxId, - int emojiId}) { + {required int postCommentId, + required String postUuid, + int? count, + int? maxId, + int? emojiId}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -375,8 +375,8 @@ class PostsApiService { } Future getReactionsEmojiCountForPostComment({ - @required int postCommentId, - @required String postUuid, + required int postCommentId, + required String postUuid, }) { String path = _makeGetPostCommentReactionsEmojiCountPath( postCommentId: postCommentId, postUuid: postUuid); @@ -385,9 +385,9 @@ class PostsApiService { } Future reactToPostComment( - {@required int postCommentId, - @required String postUuid, - @required int emojiId}) { + {required int postCommentId, + required String postUuid, + required int emojiId}) { Map body = {'emoji_id': emojiId}; String path = _makeReactToPostCommentPath( @@ -398,9 +398,9 @@ class PostsApiService { } Future deletePostCommentReaction({ - @required postCommentReactionId, - @required int postCommentId, - @required String postUuid, + required postCommentReactionId, + required int postCommentId, + required String postUuid, }) { String path = _makeDeletePostCommentReactionPath( postCommentReactionId: postCommentReactionId, @@ -413,8 +413,8 @@ class PostsApiService { } Future mutePostComment({ - @required int postCommentId, - @required String postUuid, + required int postCommentId, + required String postUuid, }) { String path = _makeMutePostCommentPath( postCommentId: postCommentId, postUuid: postUuid); @@ -422,8 +422,8 @@ class PostsApiService { } Future unmutePostComment({ - @required int postCommentId, - @required String postUuid, + required int postCommentId, + required String postUuid, }) { String path = _makeUnmutePostCommentPath( postCommentId: postCommentId, postUuid: postUuid); @@ -466,10 +466,10 @@ class PostsApiService { } Future reportPostComment( - {@required int postCommentId, - @required String postUuid, - @required int moderationCategoryId, - String description}) { + {required int postCommentId, + required String postUuid, + required int moderationCategoryId, + String? description}) { String path = _makeReportPostCommentPath( postCommentId: postCommentId, postUuid: postUuid); @@ -486,9 +486,9 @@ class PostsApiService { } Future reportPost( - {@required String postUuid, - @required int moderationCategoryId, - String description}) { + {required String postUuid, + required int moderationCategoryId, + String? description}) { String path = _makeReportPostPath(postUuid: postUuid); Map body = { @@ -503,21 +503,21 @@ class PostsApiService { body: body, appendAuthorizationToken: true); } - Future translatePost({@required String postUuid}) { + Future translatePost({required String postUuid}) { String path = _makeTranslatePostPath(postUuid: postUuid); return _httpService.post(_makeApiUrl(path), appendAuthorizationToken: true); } Future getPreviewDataForPostUuid( - {@required String postUuid}) { + {required String postUuid}) { String path = _makePreviewPostDataPath(postUuid: postUuid); return _httpService.get(_makeApiUrl(path), appendAuthorizationToken: true); } Future translatePostComment( - {@required String postUuid, @required int postCommentId}) { + {required String postUuid, required int postCommentId}) { String path = _makeTranslatePostCommentPath( postUuid: postUuid, postCommentId: postCommentId); @@ -525,7 +525,7 @@ class PostsApiService { } Future getPostParticipants( - {@required String postUuid, int count}) { + {required String postUuid, int? count}) { String path = _makeGetPostParticipantsPath(postUuid); Map queryParams = {}; @@ -536,7 +536,7 @@ class PostsApiService { } Future searchPostParticipants( - {@required String postUuid, @required String query, int count}) { + {required String postUuid, required String query, int? count}) { String path = _makeSearchPostParticipantsPath(postUuid); Map body = {'query': query}; @@ -548,14 +548,14 @@ class PostsApiService { } Future getTopPostsExcludedCommunities( - {bool authenticatedRequest = true, int offset, int count}) { + {bool authenticatedRequest = true, int? offset, int? count}) { return _httpService.get('$apiURL$EXCLUDED_TOP_POSTS_COMMUNITIES_PATH', appendAuthorizationToken: authenticatedRequest, queryParameters: {'offset': offset, 'count': count}); } Future searchTopPostsExcludedCommunities( - {@required String query, int count}) { + {required String query, int? count}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -565,14 +565,14 @@ class PostsApiService { } Future excludeCommunityFromTopPosts( - {@required String communityName}) { + {required String communityName}) { return _httpService.putJSON('$apiURL$EXCLUDED_TOP_POSTS_COMMUNITIES_PATH', body: {'community_name': communityName}, appendAuthorizationToken: true); } Future undoExcludeCommunityFromTopPosts( - {@required String communityName}) { + {required String communityName}) { String path = _makeExcludedCommunityFromTopPostsPath(communityName); return _httpService.delete(_makeApiUrl(path), appendAuthorizationToken: true); @@ -584,14 +584,14 @@ class PostsApiService { } Future getProfilePostsExcludedCommunities( - {bool authenticatedRequest = true, int offset, int count}) { + {bool authenticatedRequest = true, int? offset, int? count}) { return _httpService.get('$apiURL$EXCLUDED_PROFILE_POSTS_COMMUNITIES_PATH', appendAuthorizationToken: authenticatedRequest, queryParameters: {'offset': offset, 'count': count}); } Future searchProfilePostsExcludedCommunities( - {@required String query, int count}) { + {required String query, int? count}) { Map queryParams = {'query': query}; if (count != null) queryParams['count'] = count; @@ -601,7 +601,7 @@ class PostsApiService { } Future excludeCommunityFromProfilePosts( - {@required String communityName}) { + {required String communityName}) { return _httpService.putJSON( '$apiURL$EXCLUDED_PROFILE_POSTS_COMMUNITIES_PATH', body: {'community_name': communityName}, @@ -609,14 +609,14 @@ class PostsApiService { } Future undoExcludeCommunityFromProfilePosts( - {@required String communityName}) { + {required String communityName}) { String path = _makeExcludedCommunityFromProfilePostsPath(communityName); return _httpService.delete(_makeApiUrl(path), appendAuthorizationToken: true); } Future previewLink( - {@required String link}) { + {required String link}) { Map body = {'link': link}; return _httpService.postJSON(_makeApiUrl(PREVIEW_LINK_PATH), @@ -624,7 +624,7 @@ class PostsApiService { } Future linkIsPreviewable( - {@required String link}) { + {required String link}) { Map body = {'link': link}; return _httpService.postJSON(_makeApiUrl(LINK_IS_PREVIEWABLE_PATH), @@ -650,16 +650,16 @@ class PostsApiService { } String _makeMutePostCommentPath({ - @required int postCommentId, - @required String postUuid, + required int postCommentId, + required String postUuid, }) { return _stringTemplateService.parse(MUTE_POST_COMMENT_PATH, {'postCommentId': postCommentId, 'postUuid': postUuid}); } String _makeUnmutePostCommentPath({ - @required int postCommentId, - @required String postUuid, + required int postCommentId, + required String postUuid, }) { return _stringTemplateService.parse(UNMUTE_POST_COMMENT_PATH, {'postCommentId': postCommentId, 'postUuid': postUuid}); @@ -715,7 +715,7 @@ class PostsApiService { } String _makeDeletePostCommentPath( - {@required postCommentId, @required postUuid}) { + {required postCommentId, required postUuid}) { return _stringTemplateService.parse(DELETE_POST_COMMENT_PATH, {'postCommentId': postCommentId, 'postUuid': postUuid}); } @@ -741,21 +741,21 @@ class PostsApiService { } String _makeReactToPostCommentPath( - {@required int postCommentId, @required String postUuid}) { + {required int postCommentId, required String postUuid}) { return _stringTemplateService.parse(REACT_TO_POST_COMMENT_PATH, {'postUuid': postUuid, 'postCommentId': postCommentId}); } String _makeGetPostCommentReactionsPath( - {@required int postCommentId, @required String postUuid}) { + {required int postCommentId, required String postUuid}) { return _stringTemplateService.parse(GET_POST_COMMENT_REACTIONS_PATH, {'postCommentId': postCommentId, 'postUuid': postUuid}); } String _makeDeletePostCommentReactionPath( - {@required int postCommentReactionId, - @required String postUuid, - @required int postCommentId}) { + {required int postCommentReactionId, + required String postUuid, + required int postCommentId}) { return _stringTemplateService.parse(DELETE_POST_COMMENT_REACTION_PATH, { 'postCommentReactionId': postCommentReactionId, 'postUuid': postUuid, @@ -764,14 +764,14 @@ class PostsApiService { } String _makeGetPostCommentReactionsEmojiCountPath( - {@required postUuid, @required int postCommentId}) { + {required postUuid, required int postCommentId}) { return _stringTemplateService.parse( GET_POST_COMMENT_REACTIONS_EMOJI_COUNT_PATH, {'postUuid': postUuid, 'postCommentId': postCommentId}); } String _makeDeletePostReactionPath( - {@required postReactionId, @required postUuid}) { + {required postReactionId, required postUuid}) { return _stringTemplateService.parse(DELETE_POST_REACTION_PATH, {'postReactionId': postReactionId, 'postUuid': postUuid}); } @@ -782,48 +782,48 @@ class PostsApiService { } String _makeReportPostCommentPath( - {@required int postCommentId, @required String postUuid}) { + {required int postCommentId, required String postUuid}) { return _stringTemplateService.parse(REPORT_POST_COMMENT_PATH, {'postCommentId': postCommentId, 'postUuid': postUuid}); } - String _makeReportPostPath({@required postUuid}) { + String _makeReportPostPath({required postUuid}) { return _stringTemplateService .parse(REPORT_POST_PATH, {'postUuid': postUuid}); } - String _makeTranslatePostPath({@required postUuid}) { + String _makeTranslatePostPath({required postUuid}) { return _stringTemplateService .parse(TRANSLATE_POST_PATH, {'postUuid': postUuid}); } - String _makePreviewPostDataPath({@required postUuid}) { + String _makePreviewPostDataPath({required postUuid}) { return _stringTemplateService .parse(PREVIEW_POST_DATA_PATH, {'postUuid': postUuid}); } - String _makeAddPostMediaPath({@required postUuid}) { + String _makeAddPostMediaPath({required postUuid}) { return _stringTemplateService .parse(POST_MEDIA_PATH, {'postUuid': postUuid}); } - String _makeGetPostMediaPath({@required postUuid}) { + String _makeGetPostMediaPath({required postUuid}) { return _stringTemplateService .parse(POST_MEDIA_PATH, {'postUuid': postUuid}); } - String _makePublishPostPath({@required postUuid}) { + String _makePublishPostPath({required postUuid}) { return _stringTemplateService .parse(PUBLISH_POST_PATH, {'postUuid': postUuid}); } - String _makeGetPostStatusPath({@required postUuid}) { + String _makeGetPostStatusPath({required postUuid}) { return _stringTemplateService .parse(GET_POST_STATUS_PATH, {'postUuid': postUuid}); } String _makeTranslatePostCommentPath( - {@required postUuid, @required postCommentId}) { + {required postUuid, required postCommentId}) { return _stringTemplateService.parse(TRANSLATE_POST_COMMENT_PATH, {'postUuid': postUuid, 'postCommentId': postCommentId}); } diff --git a/lib/services/push_notifications/push_notifications.dart b/lib/services/push_notifications/push_notifications.dart index 409a7c986..de1af76d0 100644 --- a/lib/services/push_notifications/push_notifications.dart +++ b/lib/services/push_notifications/push_notifications.dart @@ -14,7 +14,7 @@ import 'package:rxdart/rxdart.dart'; class PushNotificationsService { static const String oneSignalAppId = '66074bf4-9943-4504-a011-531c2635698b'; - UserService _userService; + late UserService _userService; Stream get pushNotification => _pushNotificationSubject.stream; @@ -25,7 +25,7 @@ class PushNotificationsService { final _pushNotificationOpenedSubject = PublishSubject(); - OBStorage _pushNotificationsStorage; + late OBStorage _pushNotificationsStorage; static const String promptedUserForPermissionsStorageKey = 'promptedUser'; void setStorageService(StorageService storageService) { @@ -34,26 +34,24 @@ class PushNotificationsService { } void bootstrap() async { - await OneSignal.shared.init(oneSignalAppId, iOSSettings: { - OSiOSSettings.autoPrompt: false, - OSiOSSettings.inAppLaunchUrl: true - }); - await OneSignal.shared - .setInFocusDisplayType(OSNotificationDisplayType.notification); + await OneSignal.shared.setAppId(oneSignalAppId); + // Deprecated, not sure if we need it. + // await OneSignal.shared + // .setInFocusDisplayType(OSNotificationDisplayType.notification); await OneSignal.shared.setLocationShared(false); - OneSignal.shared.setNotificationReceivedHandler(_onNotificationReceived); + OneSignal.shared.setNotificationWillShowInForegroundHandler(_onNotificationReceived); OneSignal.shared.setNotificationOpenedHandler(_onNotificationOpened); OneSignal.shared.setSubscriptionObserver(_onSubscriptionChanged); - OSPermissionState permissionState = await this._getPermissionsState(); + bool permissionGranted = await this._getPermissionsState(); bool promptedBefore = await this.hasPromptedUserForPermission(); if (!promptedBefore) { // Prompt - permissionState = await this.promptUserForPushNotificationPermission(); + permissionGranted = await this.promptUserForPushNotificationPermission(); } - if (permissionState.status == OSNotificationPermission.authorized) { + if (permissionGranted) { // Subscribe bool isSubscribed = await this.isSubscribedToPushNotifications(); if (isSubscribed) { @@ -79,26 +77,23 @@ class PushNotificationsService { } Future isSubscribedToPushNotifications() async { - OSPermissionSubscriptionState osPermissionSubscriptionState = - await OneSignal.shared.getPermissionSubscriptionState(); - - OSSubscriptionState subscriptionState = - osPermissionSubscriptionState.subscriptionStatus; + OSDeviceState? osDeviceState = + await OneSignal.shared.getDeviceState(); - return subscriptionState.subscribed; + return osDeviceState?.subscribed ?? false; } Future subscribeToPushNotifications() async { - OSPermissionState permissionState = await this._getPermissionsState(); + bool permissionGranted = await this._getPermissionsState(); - if (permissionState.status != OSNotificationPermission.authorized) { + if (!permissionGranted) { throw new Exception( 'Tried to subscribe to push notifications without push notification permission'); } - OSSubscriptionState subscriptionState = await this._getSubscriptionState(); + bool subscribed = await this._getSubscriptionState(); - if (subscriptionState.subscribed) { + if (subscribed) { debugLog( 'Already subscribed to push notifications, not subscribing again'); _onSubscribedToPushNotifications(); @@ -106,16 +101,16 @@ class PushNotificationsService { } debugLog('Subscribing to push notifications'); - return OneSignal.shared.setSubscription(true); + return OneSignal.shared.disablePush(false); } Future unsubscribeFromPushNotifications() async { // This will trigger the _onUnsubscribedFromPushNotifications debugLog('Unsubscribing from push notifications'); - return OneSignal.shared.setSubscription(false); + return OneSignal.shared.disablePush(true); } - Future promptUserForPushNotificationPermission() async { + Future promptUserForPushNotificationPermission() async { if (Platform.isAndroid) { await this._setPromptedUserForPermission(); return this._getPermissionsState(); @@ -129,29 +124,31 @@ class PushNotificationsService { _userService = userService; } - Future _getPermissionsState() async { - OSPermissionSubscriptionState subscriptionState = + Future _getPermissionsState() async { + OSDeviceState? subscriptionState = await this._getOneSignalState(); - return subscriptionState.permissionStatus; + return subscriptionState?.hasNotificationPermission ?? false; } - Future _getSubscriptionState() async { - OSPermissionSubscriptionState subscriptionState = + Future _getSubscriptionState() async { + OSDeviceState? subscriptionState = await this._getOneSignalState(); - return subscriptionState.subscriptionStatus; + return subscriptionState?.subscribed ?? false; } - Future _getOneSignalState() { - return OneSignal.shared.getPermissionSubscriptionState(); + Future _getOneSignalState() { + return OneSignal.shared.getDeviceState(); } - void _onNotificationReceived(OSNotification notification) { + void _onNotificationReceived(OSNotificationReceivedEvent event) { debugLog('Notification received'); + OSNotification notification = event.notification; Map notificationData = - _parseAdditionalData(notification.payload.additionalData); + _parseAdditionalData(notification.additionalData); PushNotification pushNotification = PushNotification.fromJson(notificationData); _pushNotificationSubject.add(pushNotification); + event.complete(notification); } void _onNotificationOpened(OSNotificationOpenedResult result) { @@ -165,10 +162,10 @@ class PushNotificationsService { void _onSubscriptionChanged(OSSubscriptionStateChanges changes) { OSSubscriptionState toState = changes.to; OSSubscriptionState fromState = changes.from; - if (!fromState.subscribed && toState.subscribed) { + if (!fromState.isSubscribed && toState.isSubscribed) { // User just subscribed for notifications _onSubscribedToPushNotifications(); - } else if (fromState.subscribed && !toState.subscribed) { + } else if (fromState.isSubscribed&& !toState.isSubscribed) { // User just unsubscribed for notifications _onUnsubscribedFromPushNotifications(); } @@ -183,7 +180,7 @@ class PushNotificationsService { } Future _tagDeviceForPushNotifications() async { - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; Device currentDevice = await _userService.getOrCreateCurrentDevice(); String userId = _makeUserId(loggedInUser); @@ -202,7 +199,7 @@ class PushNotificationsService { } String _makeUserId(User user) { - var bytes = utf8.encode(user.uuid + user.id.toString()); + var bytes = utf8.encode(user.uuid! + user.id.toString()); var digest = sha256.convert(bytes); return digest.toString(); } @@ -214,18 +211,18 @@ class PushNotificationsService { PushNotification _makePushNotification(OSNotification notification) { Map notificationData = - _parseAdditionalData(notification.payload.additionalData); + _parseAdditionalData(notification.additionalData); return PushNotification.fromJson(notificationData); } Map _parseAdditionalData( - Map additionalData) { + Map? additionalData) { String jsonAdditionalData = json.encode(additionalData); return json.decode(jsonAdditionalData); } Future hasPromptedUserForPermission() async { - if (Platform.isIOS) return (await this._getPermissionsState()).hasPrompted; + if (Platform.isIOS) return (await this._getPermissionsState()); return _getPromptedUserForPermission(); } @@ -256,8 +253,8 @@ class PushNotificationsService { } class PushNotificationOpenedResult { - final PushNotification pushNotification; - final OSNotificationAction action; + final PushNotification? pushNotification; + final OSNotificationAction? action; const PushNotificationOpenedResult({this.pushNotification, this.action}); } diff --git a/lib/services/share.dart b/lib/services/share.dart index d06b9bf99..bdda6d0a8 100644 --- a/lib/services/share.dart +++ b/lib/services/share.dart @@ -15,20 +15,20 @@ import 'package:flutter/services.dart'; class ShareService { static const _stream = const EventChannel('okuna.io/receive_share'); - ToastService _toastService; - MediaService _mediaService; - ValidationService _validationService; - LocalizationService _localizationService; + late ToastService _toastService; + late MediaService _mediaService; + late ValidationService _validationService; + late LocalizationService _localizationService; - StreamSubscription _shareReceiveSubscription; - List Function({String text, File image, File video})> + StreamSubscription? _shareReceiveSubscription; + late List Function({String? text, File? image, File? video})> _subscribers; - Share _queuedShare; + Share? _queuedShare; bool _isProcessingShare = false; - Map _activeShares; + late Map _activeShares; - BuildContext _context; + late BuildContext _context; ShareService() { _subscribers = []; @@ -72,7 +72,7 @@ class ShareService { /// If a [CancelableOperation] is returned, it _must_ handle cancellation /// properly. void subscribe( - Future Function({String text, File image, File video}) onShare) { + Future Function({String? text, File? image, File? video}) onShare) { _subscribers.add(onShare); if (_subscribers.length == 1) { @@ -101,13 +101,13 @@ class ShareService { _activeShares .forEach((key, value) => Future.delayed(Duration(), value.cancel)); - var share = _queuedShare; + var share = _queuedShare!; _queuedShare = null; _isProcessingShare = true; _activeShares[share] = ShareOperation(share, _onShare); - _activeShares[share].then(() => _activeShares.remove(share)); - _activeShares[share].start(); + _activeShares[share]?.then(() => _activeShares.remove(share)); + _activeShares[share]?.start(); _isProcessingShare = false; // Recurse since a new share might have came in while the last was being processed. @@ -116,42 +116,42 @@ class ShareService { } Future _onShare(Share share) async { - String text; - File image; - File video; + String? text; + File? image; + File? video; if (share.error != null) { _toastService.error( - message: _localizationService.trans(share.error), context: _context); - if (share.error.contains('uri_scheme')) { - throw share.error; + message: _localizationService.trans(share.error!), context: _context); + if (share.error!.contains('uri_scheme')) { + throw share.error!; } return; } if (share.image != null) { - image = File.fromUri(Uri.parse(share.image)); + image = File.fromUri(Uri.parse(share.image!)); var processedFile = await _mediaService.processMedia( media: MediaFile(image, FileType.image), context: _context, ); - image = processedFile.file; + image = processedFile?.file; } if (share.video != null) { - video = File.fromUri(Uri.parse(share.video)); + video = File.fromUri(Uri.parse(share.video!)); var processedFile = await _mediaService.processMedia( media: MediaFile(video, FileType.video), context: _context, ); - video = processedFile.file; + video = processedFile?.file; } if (share.text != null) { text = share.text; - if (!_validationService.isPostTextAllowedLength(text)) { + if (!_validationService.isPostTextAllowedLength(text!)) { String errorMessage = _localizationService.error__receive_share_text_too_long( ValidationService.POST_MAX_LENGTH); @@ -161,7 +161,7 @@ class ShareService { } for (var sub in _subscribers.reversed) { - if (_activeShares[share].isCancelled) { + if (_activeShares[share] != null && _activeShares[share]!.isCancelled) { break; } @@ -170,7 +170,7 @@ class ShareService { // Stop event propagation if we have a sub-result that is either true or // a CancelableOperation. if (subResult is CancelableOperation) { - _activeShares[share].setSubOperation(subResult); + _activeShares[share]?.setSubOperation(subResult); break; } else if (subResult == true) { break; @@ -183,20 +183,20 @@ class ShareOperation { final Future Function(Share) _shareFunction; Share share; - CancelableOperation shareOperation; - CancelableOperation subOperation; + CancelableOperation? shareOperation; + CancelableOperation? subOperation; bool isCancelled = false; bool _shareComplete = false; bool _subComplete = false; - FutureOr Function() _callback; + late FutureOr Function() _callback; ShareOperation(this.share, Future Function(Share) shareFunction) : _shareFunction = shareFunction; void start() { shareOperation = CancelableOperation.fromFuture(_shareFunction(share)); - shareOperation.then((_) { + shareOperation!.then((_) { _shareComplete = true; _complete(); }); @@ -204,14 +204,14 @@ class ShareOperation { void setSubOperation(CancelableOperation operation) { subOperation = operation; - subOperation.then((_) { + subOperation!.then((_) { _subComplete = true; _complete(); }); - shareOperation.then((_) { - if (shareOperation.isCanceled) { - subOperation.cancel(); + shareOperation!.then((_) { + if (shareOperation!.isCanceled) { + subOperation!.cancel(); } }); } diff --git a/lib/services/storage.dart b/lib/services/storage.dart index b811154e0..423049da8 100644 --- a/lib/services/storage.dart +++ b/lib/services/storage.dart @@ -5,11 +5,11 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'package:flutter/services.dart'; class StorageService { - OBStorage getSecureStorage({String namespace}) { + OBStorage getSecureStorage({String? namespace}) { return OBStorage(store: _SecureStore(), namespace: namespace); } - OBStorage getSystemPreferencesStorage({String namespace}) { + OBStorage getSystemPreferencesStorage({required String namespace}) { return OBStorage( store: _SystemPreferencesStorage(namespace), namespace: namespace); } @@ -17,13 +17,13 @@ class StorageService { class OBStorage { _Store store; - String namespace; + String? namespace; - OBStorage({this.store, this.namespace}); + OBStorage({required this.store, this.namespace}); - Future get(String key, {String defaultValue}) async { + Future get(String key, {String? defaultValue}) async { String finalKey = _makeKey(key); - String value = await this.store.get(finalKey); + String? value = await this.store.get(finalKey); if (value == null && defaultValue != null) { await store.set(finalKey, defaultValue); value = defaultValue; @@ -69,7 +69,7 @@ class _SecureStore implements _Store { // stored data and send it back, which is unnecessary. On top of that, // readAll() doesn't work on iOS (https://github.com/mogol/flutter_secure_storage/issues/70). SharedPreferences preferences = await SharedPreferences.getInstance(); - List storedKeys = preferences.getStringList('secure_store.keylist'); + List? storedKeys = preferences.getStringList('secure_store.keylist'); if(storedKeys != null && storedKeys.isNotEmpty) _storedKeys.addAll(storedKeys); } @@ -78,7 +78,7 @@ class _SecureStore implements _Store { preferences.setStringList('secure_store.keylist', _storedKeys.toList()); } - Future get(String key) async { + Future get(String key) async { try { return storage.read(key: key); } on PlatformException { @@ -111,42 +111,42 @@ class _SecureStore implements _Store { class _SystemPreferencesStorage implements _Store { final String _namespace; - Future _sharedPreferencesCache; + Future? _sharedPreferencesCache; _SystemPreferencesStorage(String namespace) : _namespace = namespace; - Future _getSharedPreferences() async { + Future _getSharedPreferences() async { if (_sharedPreferencesCache != null) return _sharedPreferencesCache; _sharedPreferencesCache = SharedPreferences.getInstance(); return _sharedPreferencesCache; } - Future get(String key) async { - SharedPreferences sharedPreferences = await _getSharedPreferences(); - return sharedPreferences.get(key); + Future get(String key) async { + SharedPreferences? sharedPreferences = await _getSharedPreferences(); + return sharedPreferences?.getString(key); } - Future set(String key, String value) async { - SharedPreferences sharedPreferences = await _getSharedPreferences(); - return sharedPreferences.setString(key, value); + Future set(String key, String value) async { + SharedPreferences? sharedPreferences = await _getSharedPreferences(); + return sharedPreferences?.setString(key, value); } - Future remove(String key) async { - SharedPreferences sharedPreferences = await _getSharedPreferences(); - return sharedPreferences.remove(key); + Future remove(String key) async { + SharedPreferences? sharedPreferences = await _getSharedPreferences(); + return sharedPreferences?.remove(key); } - Future clear() async { - SharedPreferences preferences = await _getSharedPreferences(); + Future> clear() async { + SharedPreferences? preferences = await _getSharedPreferences(); return Future.wait(preferences - .getKeys() + !.getKeys() .where((key) => key.startsWith('$_namespace.')) .map((key) => preferences.remove(key))); } } abstract class _Store { - Future get(String key); + Future get(String key); Future set(String key, T value); diff --git a/lib/services/text_autocompletion.dart b/lib/services/text_autocompletion.dart index 94b601ed8..5718f533e 100644 --- a/lib/services/text_autocompletion.dart +++ b/lib/services/text_autocompletion.dart @@ -6,7 +6,7 @@ class TextAutocompletionService { static const String _hashtagPrefix = '#'; static const String _communityPrefix = 'c/'; - ValidationService _validationService; + late ValidationService _validationService; void setValidationService(validationService) { _validationService = validationService; @@ -94,11 +94,11 @@ class TextAutocompletionService { class TextAutocompletionResult { final bool isAutocompleting; - final String autocompleteQuery; - final TextAutocompletionType type; + final String? autocompleteQuery; + final TextAutocompletionType? type; TextAutocompletionResult( - {@required this.isAutocompleting, this.type, this.autocompleteQuery}); + {required this.isAutocompleting, this.type, this.autocompleteQuery}); } enum TextAutocompletionType { account, community, hashtag } diff --git a/lib/services/theme.dart b/lib/services/theme.dart index e7899637c..ece3bc15d 100644 --- a/lib/services/theme.dart +++ b/lib/services/theme.dart @@ -11,16 +11,16 @@ import 'package:rxdart/rxdart.dart'; import 'dart:math'; class ThemeService { - UtilsService _utilsService; + late UtilsService _utilsService; Stream get themeChange => _themeChangeSubject.stream; final _themeChangeSubject = ReplaySubject(maxSize: 1); Random random = new Random(); - OBTheme _activeTheme; + late OBTheme _activeTheme; - OBStorage _storage; + OBStorage? _storage; List _themes = [ OBTheme( @@ -194,11 +194,11 @@ class ThemeService { void setActiveTheme(OBTheme theme) { _setActiveTheme(theme); - _storeActiveThemeId(theme.id); + _storeActiveThemeId(theme.id!); } void _bootstrap() async { - int activeThemeId = await _getStoredActiveThemeId(); + int? activeThemeId = await _getStoredActiveThemeId(); if (activeThemeId != null) { OBTheme activeTheme = await _getThemeWithId(activeThemeId); _setActiveTheme(activeTheme); @@ -211,7 +211,7 @@ class ThemeService { } void _storeActiveThemeId(int themeId) { - if (_storage != null) _storage.set('activeThemeId', themeId.toString()); + if (_storage != null) _storage!.set('activeThemeId', themeId.toString()); } Future _getThemeWithId(int id) async { @@ -220,9 +220,9 @@ class ThemeService { }); } - Future _getStoredActiveThemeId() async { - String activeThemeId = await _storage.get('activeThemeId'); - return activeThemeId != null ? int.parse(activeThemeId) : null; + Future _getStoredActiveThemeId() async { + int? activeThemeId = (await _storage!.get('activeThemeId')) as int?; + return activeThemeId; } OBTheme getActiveTheme() { diff --git a/lib/services/theme_value_parser.dart b/lib/services/theme_value_parser.dart index 1f28a8f79..1232475e9 100644 --- a/lib/services/theme_value_parser.dart +++ b/lib/services/theme_value_parser.dart @@ -9,10 +9,10 @@ class ThemeValueParserService { static AlignmentGeometry _endAlignment = Alignment.bottomRight; static SimpleCache colorCache = - SimpleCache(storage: SimpleStorage(size: 30)); + SimpleCache(storage: new InMemoryStorage(30)); static SimpleCache gradientCache = - SimpleCache(storage: SimpleStorage(size: 10)); + SimpleCache(storage: new InMemoryStorage(10)); Color parseColor(String value) { return colorCache.get(value) ?? _parseAndStoreColor(value); diff --git a/lib/services/toast.dart b/lib/services/toast.dart index d87a3c3e1..0bea7229b 100644 --- a/lib/services/toast.dart +++ b/lib/services/toast.dart @@ -7,17 +7,17 @@ enum ToastType { info, warning, success, error } class ToastService { static const Duration toastDuration = Duration(seconds: 3); static Color colorError = Colors.redAccent; - static Color colorSuccess = Colors.greenAccent[700]; + static Color colorSuccess = Colors.greenAccent[700]!; static Color colorInfo = Colors.blue; - static Color colorWarning = Colors.yellow[800]; + static Color colorWarning = Colors.yellow[800]!; void warning({ - String title, - @required String message, - @required BuildContext context, - GlobalKey scaffoldKey, - VoidCallback onDismissed, - Duration duration, + String? title, + required String message, + required BuildContext context, + GlobalKey? scaffoldKey, + VoidCallback? onDismissed, + Duration? duration, }) { toast( title: title, @@ -30,13 +30,13 @@ class ToastService { } void success({ - String title, - Widget child, - @required String message, - @required BuildContext context, - GlobalKey scaffoldKey, - VoidCallback onDismissed, - Duration duration, + String? title, + Widget? child, + required String message, + required BuildContext context, + GlobalKey? scaffoldKey, + VoidCallback? onDismissed, + Duration? duration, }) { toast( title: title, @@ -50,12 +50,12 @@ class ToastService { } void error({ - String title, - @required String message, - @required BuildContext context, - GlobalKey scaffoldKey, - VoidCallback onDismissed, - Duration duration, + String? title, + required String message, + required BuildContext context, + GlobalKey? scaffoldKey, + VoidCallback? onDismissed, + Duration? duration, }) { toast( title: title, @@ -68,13 +68,13 @@ class ToastService { } void info({ - String title, - Widget child, - String message, - @required BuildContext context, - GlobalKey scaffoldKey, - VoidCallback onDismissed, - Duration duration, + String? title, + Widget? child, + required String message, + required BuildContext context, + GlobalKey? scaffoldKey, + VoidCallback? onDismissed, + Duration? duration, }) { toast( title: title, @@ -88,14 +88,14 @@ class ToastService { } void toast({ - String title, - Widget child, - @required String message, - @required ToastType type, - @required BuildContext context, - GlobalKey scaffoldKey, - VoidCallback onDismissed, - Duration duration, + String? title, + Widget? child, + required String message, + required ToastType type, + required BuildContext context, + GlobalKey? scaffoldKey, + VoidCallback? onDismissed, + Duration? duration, }) { if (context != null) { OBToast.of(context).showToast( diff --git a/lib/services/universal_links/handlers/create_account_link.dart b/lib/services/universal_links/handlers/create_account_link.dart index 332e66f55..878554d21 100644 --- a/lib/services/universal_links/handlers/create_account_link.dart +++ b/lib/services/universal_links/handlers/create_account_link.dart @@ -8,7 +8,7 @@ class CreateAccountLinkHandler extends UniversalLinkHandler { static const String createAccountLink = '/api/auth/invite'; @override - Future handle({BuildContext context, String link}) { + Future handle({required BuildContext context, required String link}) async { if (link.indexOf(createAccountLink) != -1) { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); UserService userService = openbookProvider.userService; @@ -30,7 +30,7 @@ class CreateAccountLinkHandler extends UniversalLinkHandler { final params = Uri.parse(link).queryParametersAll; var token = ''; if (params.containsKey('token')) { - token = params['token'][0]; + token = params['token']![0]; } return token; } diff --git a/lib/services/universal_links/handlers/email_verification_link.dart b/lib/services/universal_links/handlers/email_verification_link.dart index ab3e42159..4f01f4b86 100644 --- a/lib/services/universal_links/handlers/email_verification_link.dart +++ b/lib/services/universal_links/handlers/email_verification_link.dart @@ -13,10 +13,10 @@ import '../../localization.dart'; class EmailVerificationLinkHandler extends UniversalLinkHandler { static const String verifyEmailLink = '/api/auth/email/verify'; - StreamSubscription _onLoggedInUserChangeSubscription; + late StreamSubscription _onLoggedInUserChangeSubscription; @override - Future handle({BuildContext context, String link}) async{ + Future handle({required BuildContext context, required String link}) async { if (link.indexOf(verifyEmailLink) != -1) { final token = _getEmailVerificationTokenFromLink(link); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); @@ -26,7 +26,7 @@ class EmailVerificationLinkHandler extends UniversalLinkHandler { LocalizationService localizationService = openbookProvider.localizationService; _onLoggedInUserChangeSubscription = - userService.loggedInUserChange.listen((User newUser) async { + userService.loggedInUserChange.listen((User? newUser) async { _onLoggedInUserChangeSubscription.cancel(); try { @@ -42,9 +42,9 @@ class EmailVerificationLinkHandler extends UniversalLinkHandler { context: context); } } on HttpieConnectionRefusedError { - toastService.error(message: localizationService.error__no_internet_connection, context: null); + toastService.error(message: localizationService.error__no_internet_connection, context: context); } catch (e) { - toastService.error(message: localizationService.error__unknown_error, context: null); + toastService.error(message: localizationService.error__unknown_error, context: context); rethrow; } }); diff --git a/lib/services/universal_links/handlers/password_reset_link.dart b/lib/services/universal_links/handlers/password_reset_link.dart index 1858b5d18..39e8a0a8d 100644 --- a/lib/services/universal_links/handlers/password_reset_link.dart +++ b/lib/services/universal_links/handlers/password_reset_link.dart @@ -8,7 +8,7 @@ class PasswordResetLinkHandler extends UniversalLinkHandler { static const String passwordResetVerifyLink = '/api/auth/password/verify'; @override - Future handle({BuildContext context, String link}) async{ + Future handle({required BuildContext context, required String link}) async{ if (link.indexOf(passwordResetVerifyLink) != -1) { final token = getPasswordResetVerificationTokenFromLink(link); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); @@ -22,7 +22,7 @@ class PasswordResetLinkHandler extends UniversalLinkHandler { final params = Uri.parse(link).queryParametersAll; var token = ''; if (params.containsKey('token')) { - token = params['token'][0]; + token = params['token']![0]; } return token; } diff --git a/lib/services/universal_links/universal_links.dart b/lib/services/universal_links/universal_links.dart index e278ce511..7faaaef49 100644 --- a/lib/services/universal_links/universal_links.dart +++ b/lib/services/universal_links/universal_links.dart @@ -6,7 +6,7 @@ import 'package:flutter/cupertino.dart'; import 'package:uni_links/uni_links.dart'; class UniversalLinksService { - StreamSubscription _universalLinksLibSubscription; + late StreamSubscription _universalLinksLibSubscription; List _universalLinksHandlers = [ CreateAccountLinkHandler(), EmailVerificationLinkHandler(), @@ -14,7 +14,7 @@ class UniversalLinksService { ]; List _universalLinksQueue = []; bool _needsBootstrap = true; - BuildContext _latestContext; + BuildContext? _latestContext; /// Should be called at the page widgets void digestLinksWithContext(BuildContext context) { @@ -40,7 +40,7 @@ class UniversalLinksService { _universalLinksLibSubscription = getLinksStream().listen(_onLink, onError: _onLinkError); try { - String initialLink = await getInitialLink(); + String? initialLink = await getInitialLink(); _onLink(initialLink); } catch (error) { _onLinkError(error); @@ -48,17 +48,17 @@ class UniversalLinksService { } void _digestLinkWithContext( - {@required String link, @required BuildContext context}) { + {required String link, required BuildContext context}) { print('Digesting universal link $link'); _universalLinksHandlers .forEach((handler) => handler.handle(context: context, link: link)); } - void _onLink(String link) async { + void _onLink(String? link) async { if (link == null) return; if (_latestContext != null) { - _digestLinkWithContext(link: link, context: _latestContext); + _digestLinkWithContext(link: link, context: _latestContext!); } else { _universalLinksQueue.add(link); } @@ -71,5 +71,5 @@ class UniversalLinksService { } abstract class UniversalLinkHandler { - Future handle({@required BuildContext context, @required String link}); + Future handle({required BuildContext context, required String link}); } diff --git a/lib/services/user.dart b/lib/services/user.dart index 56e269d5c..04d7ab449 100644 --- a/lib/services/user.dart +++ b/lib/services/user.dart @@ -84,7 +84,7 @@ import 'package:path/path.dart'; import 'intercom.dart'; class UserService { - OBStorage _userStorage; + late OBStorage _userStorage; static const STORAGE_KEY_AUTH_TOKEN = 'authToken'; static const STORAGE_KEY_USER_DATA = 'data'; @@ -92,38 +92,38 @@ class UserService { static const STORAGE_TOP_POSTS_DATA = 'topPostsData'; static const STORAGE_TOP_POSTS_LAST_VIEWED_ID = 'topPostsLastViewedId'; - AuthApiService _authApiService; - HttpieService _httpieService; - PostsApiService _postsApiService; - ModerationApiService _moderationApiService; - CommunitiesApiService _communitiesApiService; - HashtagsApiService _hashtagsApiService; - CategoriesApiService _categoriesApiService; - EmojisApiService _emojisApiService; - FollowsApiService _followsApiService; - ConnectionsApiService _connectionsApiService; - ConnectionsCirclesApiService _connectionsCirclesApiService; - FollowsListsApiService _followsListsApiService; - UserInvitesApiService _userInvitesApiService; - NotificationsApiService _notificationsApiService; - DevicesApiService _devicesApiService; - CreateAccountBloc _createAccountBlocService; - WaitlistApiService _waitlistApiService; - LocalizationService _localizationService; - DraftService _draftService; - PushNotificationsService _pushNotificationService; - IntercomService _intercomService; + late AuthApiService _authApiService; + late HttpieService _httpieService; + late PostsApiService _postsApiService; + late ModerationApiService _moderationApiService; + late CommunitiesApiService _communitiesApiService; + late HashtagsApiService _hashtagsApiService; + late CategoriesApiService _categoriesApiService; + late EmojisApiService _emojisApiService; + late FollowsApiService _followsApiService; + late ConnectionsApiService _connectionsApiService; + late ConnectionsCirclesApiService _connectionsCirclesApiService; + late FollowsListsApiService _followsListsApiService; + late UserInvitesApiService _userInvitesApiService; + late NotificationsApiService _notificationsApiService; + late DevicesApiService _devicesApiService; + late CreateAccountBloc _createAccountBlocService; + late WaitlistApiService _waitlistApiService; + late LocalizationService _localizationService; + late DraftService _draftService; + late PushNotificationsService _pushNotificationService; + late IntercomService _intercomService; // If this is null, means user logged out. - Stream get loggedInUserChange => _loggedInUserChangeSubject.stream; + Stream get loggedInUserChange => _loggedInUserChangeSubject.stream; - User _loggedInUser; + User? _loggedInUser; - String _authToken; + String? _authToken; - final _loggedInUserChangeSubject = ReplaySubject(maxSize: 1); + final _loggedInUserChangeSubject = ReplaySubject(maxSize: 1); - Future _getOrCreateCurrentDeviceCache; + Future? _getOrCreateCurrentDeviceCache; static const MAX_TEMP_DIRECTORY_CACHE_MB = 200; // 200mb @@ -330,12 +330,12 @@ class UserService { clearTemporaryDirectories(); } } catch (e) { - debugPrint(e); + debugPrint(e as String); } } Future loginWithCredentials( - {@required String username, @required String password}) async { + {required String username, required String password}) async { HttpieResponse response = await _authApiService.loginWithCredentials( username: username, password: password); if (response.isOk()) { @@ -349,15 +349,15 @@ class UserService { } } - Future requestPasswordReset({@required String email}) async { + Future requestPasswordReset({required String email}) async { HttpieResponse response = await _authApiService.requestPasswordReset(email: email); _checkResponseIsOk(response); } Future verifyPasswordReset( - {@required String newPassword, - @required String passwordResetToken}) async { + {required String newPassword, + required String passwordResetToken}) async { HttpieResponse response = await _authApiService.verifyPasswordReset( newPassword: newPassword, passwordResetToken: passwordResetToken); _checkResponseIsOk(response); @@ -368,7 +368,7 @@ class UserService { _checkResponseIsOk(response); } - Future subscribeToBetaWaitlist({String email}) async { + Future subscribeToBetaWaitlist({required String email}) async { HttpieResponse response = await _waitlistApiService.subscribeToBetaWaitlist(email: email); _checkResponseIsOk(response); @@ -381,23 +381,23 @@ class UserService { await refreshUser(); } - User getLoggedInUser() { + User? getLoggedInUser() { return _loggedInUser; } - Language getUserLanguage() { - return _loggedInUser.language; + Language? getUserLanguage() { + return _loggedInUser?.language; } bool isLoggedInUser(User user) { - return user.id == _loggedInUser.id; + return _loggedInUser != null && user.id == _loggedInUser!.id; } Future refreshUser() async { if (_authToken == null) throw AuthTokenMissingError(); HttpieResponse response = - await _authApiService.getUserWithAuthToken(_authToken); + await _authApiService.getUserWithAuthToken(_authToken!); _checkResponseIsOk(response); var userData = response.body; return _setUserWithData(userData); @@ -421,15 +421,15 @@ class UserService { Future updateUser({ dynamic avatar, dynamic cover, - String name, - String username, - String url, - String password, - bool followersCountVisible, - bool communityPostsVisible, - String bio, - String location, - UserVisibility visibility, + String? name, + String? username, + String? url, + String? password, + bool? followersCountVisible, + bool? communityPostsVisible, + String? bio, + String? location, + UserVisibility? visibility, }) async { HttpieStreamedResponse response = await _authApiService.updateUser( avatar: avatar, @@ -466,17 +466,17 @@ class UserService { return; } - String userData = await this._getStoredUserData(); + String? userData = await this._getStoredUserData(); if (userData != null) { var user = _makeLoggedInUser(userData); _setLoggedInUser(user); } - await loginWithAuthToken(token); + await loginWithAuthToken(token!); } Future hasAuthToken() async { - String authToken = await _getStoredAuthToken(); + String? authToken = await _getStoredAuthToken(); return authToken != null; } @@ -485,7 +485,7 @@ class UserService { } Future getTopPosts( - {int maxId, int minId, int count, bool excludeJoinedCommunities}) async { + {int? maxId, int? minId, int? count, bool? excludeJoinedCommunities}) async { HttpieResponse response = await _postsApiService.getTopPosts( maxId: maxId, minId: minId, @@ -499,7 +499,7 @@ class UserService { } Future getTrendingPosts( - {int maxId, int minId, int count}) async { + {int? maxId, int? minId, int? count}) async { HttpieResponse response = await _postsApiService.getTrendingPosts( maxId: maxId, minId: minId, count: count, authenticatedRequest: true); @@ -511,13 +511,13 @@ class UserService { Future getTimelinePosts( {List circles = const [], List followsLists = const [], - int maxId, - int count, - String username, + int? maxId, + int? count, + String? username, bool cachePosts = false}) async { HttpieResponse response = await _postsApiService.getTimelinePosts( - circleIds: circles.map((circle) => circle.id).toList(), - listIds: followsLists.map((followsList) => followsList.id).toList(), + circleIds: circles.map((circle) => circle.id!).toList(), + listIds: followsLists.map((followsList) => followsList.id!).toList(), maxId: maxId, count: count, username: username, @@ -531,7 +531,7 @@ class UserService { } Future getStoredFirstPosts() async { - String firstPostsData = await this._getStoredFirstPostsData(); + String? firstPostsData = await this._getStoredFirstPostsData(); if (firstPostsData != null) { var postsList = _makePostsList(firstPostsData); return postsList; @@ -541,7 +541,7 @@ class UserService { Future setStoredTopPosts(List topPosts) async { String topPostsData = json - .encode(topPosts.map((TopPost topPost) => topPost.toJson())?.toList()); + .encode(topPosts.map((TopPost topPost) => topPost.toJson()).toList()); await this._removeStoredTopPostsData(); await this._storeTopPostsData(topPostsData); } @@ -554,7 +554,7 @@ class UserService { } Future getStoredTopPosts() async { - String topPostsData = await this._getStoredTopPostsData(); + String? topPostsData = await this._getStoredTopPostsData(); if (topPostsData != null) { var postsList = _makeTopPostsList(topPostsData); return postsList; @@ -562,8 +562,8 @@ class UserService { return TopPostsList(); } - Future getStoredTopPostsLastViewedId() async { - String topPostId = await this._getStoredTopPostsLastViewedId(); + Future getStoredTopPostsLastViewedId() async { + String? topPostId = await this._getStoredTopPostsLastViewedId(); if (topPostId != null) { return int.parse(topPostId); } @@ -571,10 +571,10 @@ class UserService { } Future createPost( - {String text, List circles = const [], bool isDraft}) async { + {String? text, List circles = const [], bool isDraft = false}) async { HttpieStreamedResponse response = await _postsApiService.createPost( text: text, - circleIds: circles.map((circle) => circle.id).toList(), + circleIds: circles.map((circle) => circle.id!).toList(), isDraft: isDraft); _checkResponseIsCreated(response); @@ -587,45 +587,45 @@ class UserService { } Future addMediaToPost( - {@required File file, @required Post post}) async { + {required File file, required Post post}) async { HttpieStreamedResponse response = - await _postsApiService.addMediaToPost(file: file, postUuid: post.uuid); + await _postsApiService.addMediaToPost(file: file, postUuid: post.uuid!); _checkResponseIsOk(response); } - Future getMediaForPost({@required Post post}) async { + Future getMediaForPost({required Post post}) async { HttpieResponse response = - await _postsApiService.getPostMedia(postUuid: post.uuid); + await _postsApiService.getPostMedia(postUuid: post.uuid!); _checkResponseIsOk(response); return PostMediaList.fromJson(json.decode(response.body)); } - Future publishPost({@required Post post}) async { + Future publishPost({required Post post}) async { HttpieResponse response = - await _postsApiService.publishPost(postUuid: post.uuid); + await _postsApiService.publishPost(postUuid: post.uuid!); _checkResponseIsOk(response); } - Future getPostStatus({@required Post post}) async { + Future getPostStatus({required Post post}) async { HttpieResponse response = - await _postsApiService.getPostWithUuidStatus(post.uuid); + await _postsApiService.getPostWithUuidStatus(post.uuid!); _checkResponseIsOk(response); Map responseJson = response.parseJsonBody(); - OBPostStatus status = OBPostStatus.parse(responseJson['status']); + OBPostStatus? status = OBPostStatus.parse(responseJson['status']); post.setStatus(status); return status; } - Future editPost({String postUuid, String text}) async { + Future editPost({required String postUuid, String? text}) async { HttpieStreamedResponse response = await _postsApiService.editPost(postUuid: postUuid, text: text); @@ -637,34 +637,34 @@ class UserService { Future deletePost(Post post) async { HttpieResponse response = - await _postsApiService.deletePostWithUuid(post.uuid); + await _postsApiService.deletePostWithUuid(post.uuid!); _checkResponseIsOk(response); } Future disableCommentsForPost(Post post) async { HttpieResponse response = - await _postsApiService.disableCommentsForPostWithUuidPost(post.uuid); + await _postsApiService.disableCommentsForPostWithUuidPost(post.uuid!); _checkResponseIsOk(response); return Post.fromJson(json.decode(response.body)); } Future enableCommentsForPost(Post post) async { HttpieResponse response = - await _postsApiService.enableCommentsForPostWithUuidPost(post.uuid); + await _postsApiService.enableCommentsForPostWithUuidPost(post.uuid!); _checkResponseIsOk(response); return Post.fromJson(json.decode(response.body)); } Future closePost(Post post) async { HttpieResponse response = - await _postsApiService.closePostWithUuid(post.uuid); + await _postsApiService.closePostWithUuid(post.uuid!); _checkResponseIsOk(response); return Post.fromJson(json.decode(response.body)); } Future openPost(Post post) async { HttpieResponse response = - await _postsApiService.openPostWithUuid(post.uuid); + await _postsApiService.openPostWithUuid(post.uuid!); _checkResponseIsOk(response); return Post.fromJson(json.decode(response.body)); } @@ -676,25 +676,25 @@ class UserService { } Future reactToPost( - {@required Post post, @required Emoji emoji}) async { + {required Post post, required Emoji emoji}) async { HttpieResponse response = await _postsApiService.reactToPost( - postUuid: post.uuid, emojiId: emoji.id); + postUuid: post.uuid!, emojiId: emoji.id!); _checkResponseIsCreated(response); return PostReaction.fromJson(json.decode(response.body)); } Future deletePostReaction( - {@required PostReaction postReaction, @required Post post}) async { + {required PostReaction postReaction, required Post post}) async { HttpieResponse response = await _postsApiService.deletePostReaction( postReactionId: postReaction.id, postUuid: post.uuid); _checkResponseIsOk(response); } Future getReactionsForPost(Post post, - {int count, int maxId, Emoji emoji}) async { + {int? count, int? maxId, Emoji? emoji}) async { HttpieResponse response = - await _postsApiService.getReactionsForPostWithUuid(post.uuid, - count: count, maxId: maxId, emojiId: emoji.id); + await _postsApiService.getReactionsForPostWithUuid(post.uuid!, + count: count, maxId: maxId, emojiId: emoji?.id); _checkResponseIsOk(response); @@ -704,7 +704,7 @@ class UserService { Future getReactionsEmojiCountForPost( Post post) async { HttpieResponse response = - await _postsApiService.getReactionsEmojiCountForPostWithUuid(post.uuid); + await _postsApiService.getReactionsEmojiCountForPostWithUuid(post.uuid!); _checkResponseIsOk(response); @@ -712,41 +712,41 @@ class UserService { } Future reactToPostComment( - {@required Post post, - @required PostComment postComment, - @required Emoji emoji}) async { + {required Post post, + required PostComment postComment, + required Emoji emoji}) async { HttpieResponse response = await _postsApiService.reactToPostComment( - postCommentId: postComment.id, - postUuid: post.uuid, - emojiId: emoji.id, + postCommentId: postComment.id!, + postUuid: post.uuid!, + emojiId: emoji.id!, ); _checkResponseIsCreated(response); return PostCommentReaction.fromJson(json.decode(response.body)); } Future deletePostCommentReaction( - {@required PostCommentReaction postCommentReaction, - @required PostComment postComment, - @required Post post}) async { + {required PostCommentReaction postCommentReaction, + required PostComment postComment, + required Post post}) async { HttpieResponse response = await _postsApiService.deletePostCommentReaction( postCommentReactionId: postCommentReaction.id, - postUuid: post.uuid, - postCommentId: postComment.id); + postUuid: post.uuid!, + postCommentId: postComment.id!); _checkResponseIsOk(response); } Future getReactionsForPostComment( - {PostComment postComment, - Post post, - int count, - int maxId, - Emoji emoji}) async { + {required PostComment postComment, + required Post post, + int? count, + int? maxId, + Emoji? emoji}) async { HttpieResponse response = await _postsApiService.getReactionsForPostComment( - postUuid: post.uuid, - postCommentId: postComment.id, + postUuid: post.uuid!, + postCommentId: postComment.id!, count: count, maxId: maxId, - emojiId: emoji.id); + emojiId: emoji?.id); _checkResponseIsOk(response); @@ -754,10 +754,10 @@ class UserService { } Future getReactionsEmojiCountForPostComment( - {@required PostComment postComment, @required Post post}) async { + {required PostComment postComment, required Post post}) async { HttpieResponse response = await _postsApiService.getReactionsEmojiCountForPostComment( - postCommentId: postComment.id, postUuid: post.uuid); + postCommentId: postComment.id!, postUuid: post.uuid!); _checkResponseIsOk(response); @@ -765,43 +765,43 @@ class UserService { } Future commentPost( - {@required Post post, @required String text}) async { + {required Post post, required String text}) async { HttpieResponse response = - await _postsApiService.commentPost(postUuid: post.uuid, text: text); + await _postsApiService.commentPost(postUuid: post.uuid!, text: text); _checkResponseIsCreated(response); return PostComment.fromJSON(json.decode(response.body)); } Future editPostComment( - {@required Post post, - @required PostComment postComment, - @required String text}) async { + {required Post post, + required PostComment postComment, + required String text}) async { HttpieResponse response = await _postsApiService.editPostComment( - postUuid: post.uuid, postCommentId: postComment.id, text: text); + postUuid: post.uuid!, postCommentId: postComment.id!, text: text); _checkResponseIsOk(response); return PostComment.fromJSON(json.decode(response.body)); } Future getPostComment( - {@required Post post, @required PostComment postComment}) async { + {required Post post, required PostComment postComment}) async { HttpieResponse response = await _postsApiService.getPostComment( - postUuid: post.uuid, postCommentId: postComment.id); + postUuid: post.uuid!, postCommentId: postComment.id!); _checkResponseIsOk(response); return PostComment.fromJSON(json.decode(response.body)); } Future replyPostComment( - {@required Post post, - @required PostComment postComment, - @required String text}) async { + {required Post post, + required PostComment postComment, + required String text}) async { HttpieResponse response = await _postsApiService.replyPostComment( - postUuid: post.uuid, postCommentId: postComment.id, text: text); + postUuid: post.uuid!, postCommentId: postComment.id!, text: text); _checkResponseIsCreated(response); return PostComment.fromJSON(json.decode(response.body)); } Future deletePostComment( - {@required PostComment postComment, @required Post post}) async { + {required PostComment postComment, required Post post}) async { HttpieResponse response = await _postsApiService.deletePostComment( postCommentId: postComment.id, postUuid: post.uuid); _checkResponseIsOk(response); @@ -809,21 +809,21 @@ class UserService { Future mutePost(Post post) async { HttpieResponse response = - await _postsApiService.mutePostWithUuid(post.uuid); + await _postsApiService.mutePostWithUuid(post.uuid!); _checkResponseIsOk(response); return Post.fromJson(json.decode(response.body)); } Future unmutePost(Post post) async { HttpieResponse response = - await _postsApiService.unmutePostWithUuid(post.uuid); + await _postsApiService.unmutePostWithUuid(post.uuid!); _checkResponseIsOk(response); return Post.fromJson(json.decode(response.body)); } Future excludeCommunityFromTopPosts(Community community) async { HttpieResponse response = await _postsApiService - .excludeCommunityFromTopPosts(communityName: community.name); + .excludeCommunityFromTopPosts(communityName: community.name!); _checkResponseIsAccepted(response); return (json.decode(response.body))['message']; @@ -831,7 +831,7 @@ class UserService { Future undoExcludeCommunityFromTopPosts(Community community) async { HttpieResponse response = await _postsApiService - .undoExcludeCommunityFromTopPosts(communityName: community.name); + .undoExcludeCommunityFromTopPosts(communityName: community.name!); _checkResponseIsAccepted(response); return (json.decode(response.body))['message']; @@ -839,7 +839,7 @@ class UserService { Future excludeCommunityFromProfilePosts(Community community) async { HttpieResponse response = await _postsApiService - .excludeCommunityFromProfilePosts(communityName: community.name); + .excludeCommunityFromProfilePosts(communityName: community.name!); _checkResponseIsAccepted(response); return (json.decode(response.body))['message']; @@ -848,36 +848,36 @@ class UserService { Future undoExcludeCommunityFromProfilePosts( Community community) async { HttpieResponse response = await _postsApiService - .undoExcludeCommunityFromProfilePosts(communityName: community.name); + .undoExcludeCommunityFromProfilePosts(communityName: community.name!); _checkResponseIsAccepted(response); return (json.decode(response.body))['message']; } Future mutePostComment( - {@required PostComment postComment, @required Post post}) async { + {required PostComment postComment, required Post post}) async { HttpieResponse response = await _postsApiService.mutePostComment( - postUuid: post.uuid, postCommentId: postComment.id); + postUuid: post.uuid!, postCommentId: postComment.id!); _checkResponseIsOk(response); return PostComment.fromJSON(json.decode(response.body)); } Future unmutePostComment( - {@required PostComment postComment, @required Post post}) async { + {required PostComment postComment, required Post post}) async { HttpieResponse response = await _postsApiService.unmutePostComment( - postCommentId: postComment.id, postUuid: post.uuid); + postCommentId: postComment.id!, postUuid: post.uuid!); _checkResponseIsOk(response); return PostComment.fromJSON(json.decode(response.body)); } Future getCommentsForPost(Post post, - {int maxId, - int countMax, - int minId, - int countMin, - PostCommentsSortType sort}) async { + {int? maxId, + int? countMax, + int? minId, + int? countMin, + PostCommentsSortType? sort}) async { HttpieResponse response = await _postsApiService.getCommentsForPostWithUuid( - post.uuid, + post.uuid!, countMax: countMax, maxId: maxId, countMin: countMin, @@ -892,13 +892,13 @@ class UserService { Future getCommentRepliesForPostComment( Post post, PostComment postComment, - {int maxId, - int countMax, - int minId, - int countMin, - PostCommentsSortType sort}) async { + {int? maxId, + int? countMax, + int? minId, + int? countMin, + PostCommentsSortType? sort}) async { HttpieResponse response = await _postsApiService - .getRepliesForCommentWithIdForPostWithUuid(post.uuid, postComment.id, + .getRepliesForCommentWithIdForPostWithUuid(post.uuid!, postComment.id!, countMax: countMax, maxId: maxId, countMin: countMin, @@ -950,9 +950,9 @@ class UserService { return User.fromJson(json.decode(response.body)); } - Future countPostsForUser(User user, {int maxId, int count}) async { + Future countPostsForUser(User user, {int? maxId, int? count}) async { HttpieResponse response = - await _authApiService.getPostsCountForUserWithName(user.username); + await _authApiService.getPostsCountForUserWithName(user.username!); _checkResponseIsOk(response); User responseUser = User.fromJson(json.decode(response.body)); return responseUser.postsCount; @@ -966,9 +966,9 @@ class UserService { } Future searchLinkedUsers( - {@required String query, int count, Community withCommunity}) async { + {required String query, int? count, Community? withCommunity}) async { HttpieResponse response = await _authApiService.searchLinkedUsers( - query: query, count: count, withCommunity: withCommunity.name); + query: query, count: count, withCommunity: withCommunity?.name); _checkResponseIsOk(response); return UsersList.fromJson(json.decode(response.body), storeInMaxSessionCache: true); @@ -976,9 +976,9 @@ class UserService { Future getLinkedUsers( {bool authenticatedRequest = true, - int maxId, - int count, - Community withCommunity}) async { + int? maxId, + int? count, + Community? withCommunity}) async { HttpieResponse response = await _authApiService.getLinkedUsers( count: count, withCommunity: withCommunity?.name, maxId: maxId); _checkResponseIsOk(response); @@ -988,41 +988,41 @@ class UserService { Future blockUser(User user) async { HttpieResponse response = - await _authApiService.blockUserWithUsername(user.username); + await _authApiService.blockUserWithUsername(user.username!); _checkResponseIsOk(response); return User.fromJson(json.decode(response.body)); } Future unblockUser(User user) async { HttpieResponse response = - await _authApiService.unblockUserWithUsername(user.username); + await _authApiService.unblockUserWithUsername(user.username!); _checkResponseIsOk(response); return User.fromJson(json.decode(response.body)); } Future enableNewPostNotificationsForUser(User user) async { HttpieResponse response = await _authApiService - .enableNewPostNotificationsForUserWithUsername(user.username); + .enableNewPostNotificationsForUserWithUsername(user.username!); _checkResponseIsCreated(response); return User.fromJson(json.decode(response.body)); } Future disableNewPostNotificationsForUser(User user) async { HttpieResponse response = await _authApiService - .disableNewPostNotificationsForUserWithUsername(user.username); + .disableNewPostNotificationsForUserWithUsername(user.username!); _checkResponseIsOk(response); return User.fromJson(json.decode(response.body)); } Future searchBlockedUsers( - {@required String query, int count}) async { + {required String query, int? count}) async { HttpieResponse response = await _authApiService.searchBlockedUsers(query: query, count: count); _checkResponseIsOk(response); return UsersList.fromJson(json.decode(response.body)); } - Future getBlockedUsers({int maxId, int count}) async { + Future getBlockedUsers({int? maxId, int? count}) async { HttpieResponse response = await _authApiService.getBlockedUsers(count: count, maxId: maxId); _checkResponseIsOk(response); @@ -1030,7 +1030,7 @@ class UserService { } Future searchTopPostsExcludedCommunities( - {@required String query, int count}) async { + {required String query, int? count}) async { HttpieResponse response = await _postsApiService .searchTopPostsExcludedCommunities(query: query, count: count); _checkResponseIsOk(response); @@ -1038,7 +1038,7 @@ class UserService { } Future getTopPostsExcludedCommunities( - {int offset, int count}) async { + {int? offset, int? count}) async { HttpieResponse response = await _postsApiService .getTopPostsExcludedCommunities(count: count, offset: offset); _checkResponseIsOk(response); @@ -1046,7 +1046,7 @@ class UserService { } Future searchProfilePostsExcludedCommunities( - {@required String query, int count}) async { + {required String query, int? count}) async { HttpieResponse response = await _postsApiService .searchProfilePostsExcludedCommunities(query: query, count: count); _checkResponseIsOk(response); @@ -1054,14 +1054,14 @@ class UserService { } Future getProfilePostsExcludedCommunities( - {int offset, int count}) async { + {int? offset, int? count}) async { HttpieResponse response = await _postsApiService .getProfilePostsExcludedCommunities(count: count, offset: offset); _checkResponseIsOk(response); return CommunitiesList.fromJson(json.decode(response.body)); } - Future searchFollowers({@required String query, int count}) async { + Future searchFollowers({required String query, int? count}) async { HttpieResponse response = await _authApiService.searchFollowers(query: query, count: count); _checkResponseIsOk(response); @@ -1070,9 +1070,9 @@ class UserService { Future getFollowers( {bool authenticatedRequest = true, - int maxId, - int count, - Community withCommunity}) async { + int? maxId, + int? count, + Community? withCommunity}) async { HttpieResponse response = await _authApiService.getFollowers(count: count, maxId: maxId); _checkResponseIsOk(response); @@ -1080,7 +1080,7 @@ class UserService { } Future searchFollowings( - {@required String query, int count, Community withCommunity}) async { + {required String query, int? count, Community? withCommunity}) async { HttpieResponse response = await _authApiService.searchFollowings(query: query, count: count); _checkResponseIsOk(response); @@ -1089,9 +1089,9 @@ class UserService { Future getFollowings( {bool authenticatedRequest = true, - int maxId, - int count, - Community withCommunity}) async { + int? maxId, + int? count, + Community? withCommunity}) async { HttpieResponse response = await _authApiService.getFollowings(count: count, maxId: maxId); _checkResponseIsOk(response); @@ -1100,21 +1100,21 @@ class UserService { Future requestToFollowUser(User user) async { HttpieResponse response = - await _followsApiService.requestToFollowUserWithUsername(user.username); + await _followsApiService.requestToFollowUserWithUsername(user.username!); _checkResponseIsCreated(response); user.setIsFollowRequested(true); } Future cancelRequestToFollowUser(User user) async { HttpieResponse response = await _followsApiService - .cancelRequestToFollowUserWithUsername(user.username); + .cancelRequestToFollowUserWithUsername(user.username!); _checkResponseIsOk(response); user.setIsFollowRequested(false); } Future approveFollowRequestFromUser(User user) async { HttpieResponse response = await _followsApiService - .approveFollowRequestFromUserWithUsername(user.username); + .approveFollowRequestFromUserWithUsername(user.username!); _checkResponseIsOk(response); user.setIsPendingFollowRequestApproval(false); user.setIsFollowed(true); @@ -1122,16 +1122,16 @@ class UserService { Future rejectFollowRequestFromUser(User user) async { HttpieResponse response = await _followsApiService - .rejectFollowRequestFromUserWithUsername(user.username); + .rejectFollowRequestFromUserWithUsername(user.username!); _checkResponseIsOk(response); user.setIsPendingFollowRequestApproval(false); } Future getReceivedFollowRequests( {bool authenticatedRequest = true, - int maxId, - int count, - Community withCommunity}) async { + int? maxId, + int? count, + Community? withCommunity}) async { HttpieResponse response = await _followsApiService .getReceivedFollowRequests(count: count, maxId: maxId); _checkResponseIsOk(response); @@ -1142,7 +1142,7 @@ class UserService { {List followsLists = const []}) async { HttpieResponse response = await _followsApiService.followUserWithUsername( username, - listsIds: followsLists.map((followsList) => followsList.id).toList()); + listsIds: followsLists.map((followsList) => followsList.id!).toList()); _checkResponseIsCreated(response); return Follow.fromJson(json.decode(response.body)); } @@ -1158,7 +1158,7 @@ class UserService { {List followsLists = const []}) async { HttpieResponse response = await _followsApiService.updateFollowWithUsername( username, - listsIds: followsLists.map((followsList) => followsList.id).toList()); + listsIds: followsLists.map((followsList) => followsList.id!).toList()); _checkResponseIsOk(response); return Follow.fromJson(json.decode(response.body)); } @@ -1167,7 +1167,7 @@ class UserService { {List circles = const []}) async { HttpieResponse response = await _connectionsApiService.connectWithUserWithUsername(username, - circlesIds: circles.map((circle) => circle.id).toList()); + circlesIds: circles.map((circle) => circle.id!).toList()); _checkResponseIsCreated(response); return Connection.fromJson(json.decode(response.body)); } @@ -1176,7 +1176,7 @@ class UserService { {List circles = const []}) async { HttpieResponse response = await _connectionsApiService .confirmConnectionWithUserWithUsername(username, - circlesIds: circles.map((circle) => circle.id).toList()); + circlesIds: circles.map((circle) => circle.id!).toList()); _checkResponseIsOk(response); return Connection.fromJson(json.decode(response.body)); } @@ -1192,7 +1192,7 @@ class UserService { {List circles = const []}) async { HttpieResponse response = await _connectionsApiService.updateConnectionWithUsername(username, - circlesIds: circles.map((circle) => circle.id).toList()); + circlesIds: circles.map((circle) => circle.id!).toList()); _checkResponseIsOk(response); return Connection.fromJson(json.decode(response.body)); } @@ -1211,7 +1211,7 @@ class UserService { } Future createConnectionsCircle( - {@required String name, String color}) async { + {required String name, String? color}) async { HttpieResponse response = await _connectionsCirclesApiService.createCircle( name: name, color: color); _checkResponseIsCreated(response); @@ -1219,19 +1219,19 @@ class UserService { } Future updateConnectionsCircle(Circle circle, - {String name, String color, List users = const []}) async { + {String? name, String? color, List users = const []}) async { HttpieResponse response = - await _connectionsCirclesApiService.updateCircleWithId(circle.id, + await _connectionsCirclesApiService.updateCircleWithId(circle.id!, name: name, color: color, - usernames: users.map((user) => user.username).toList()); + usernames: users.map((user) => user.username!).toList()); _checkResponseIsOk(response); return Circle.fromJSON(json.decode(response.body)); } Future deleteConnectionsCircle(Circle circle) async { HttpieResponse response = - await _connectionsCirclesApiService.deleteCircleWithId(circle.id); + await _connectionsCirclesApiService.deleteCircleWithId(circle.id!); _checkResponseIsOk(response); } @@ -1242,27 +1242,27 @@ class UserService { } Future createFollowsList( - {@required String name, Emoji emoji}) async { + {required String name, Emoji? emoji}) async { HttpieResponse response = - await _followsListsApiService.createList(name: name, emojiId: emoji.id); + await _followsListsApiService.createList(name: name, emojiId: emoji?.id); _checkResponseIsCreated(response); return FollowsList.fromJSON(json.decode(response.body)); } Future updateFollowsList(FollowsList list, - {String name, Emoji emoji, List users}) async { + {String? name, Emoji? emoji, List? users}) async { HttpieResponse response = await _followsListsApiService.updateListWithId( - list.id, + list.id!, name: name, - emojiId: emoji.id, - usernames: users.map((user) => user.username).toList()); + emojiId: emoji?.id, + usernames: users?.map((user) => user.username!).toList()); _checkResponseIsOk(response); return FollowsList.fromJSON(json.decode(response.body)); } Future deleteFollowsList(FollowsList list) async { HttpieResponse response = - await _followsListsApiService.deleteListWithId(list.id); + await _followsListsApiService.deleteListWithId(list.id!); _checkResponseIsOk(response); } @@ -1273,7 +1273,7 @@ class UserService { return FollowsList.fromJSON(json.decode(response.body)); } - Future createUserInvite({String nickname}) async { + Future createUserInvite({required String nickname}) async { HttpieStreamedResponse response = await _userInvitesApiService.createUserInvite(nickname: nickname); _checkResponseIsCreated(response); @@ -1283,9 +1283,9 @@ class UserService { } Future updateUserInvite( - {String nickname, UserInvite userInvite}) async { + {required String? nickname, required UserInvite userInvite}) async { HttpieStreamedResponse response = await _userInvitesApiService - .updateUserInvite(nickname: nickname, userInviteId: userInvite.id); + .updateUserInvite(nickname: nickname, userInviteId: userInvite.id!); _checkResponseIsOk(response); String responseBody = await response.readAsString(); @@ -1293,7 +1293,7 @@ class UserService { } Future getUserInvites( - {int offset, int count, UserInviteFilterByStatus status}) async { + {int? offset, int? count, UserInviteFilterByStatus? status}) async { bool isPending = status != null ? UserInvite.convertUserInviteStatusToBool(status) : UserInvite.convertUserInviteStatusToBool( @@ -1306,7 +1306,7 @@ class UserService { } Future searchUserInvites( - {int count, UserInviteFilterByStatus status, String query}) async { + {int? count, UserInviteFilterByStatus? status, required String query}) async { bool isPending = status != null ? UserInvite.convertUserInviteStatusToBool(status) : UserInvite.convertUserInviteStatusToBool( @@ -1320,18 +1320,18 @@ class UserService { Future deleteUserInvite(UserInvite userInvite) async { HttpieResponse response = - await _userInvitesApiService.deleteUserInvite(userInvite.id); + await _userInvitesApiService.deleteUserInvite(userInvite.id!); _checkResponseIsOk(response); } Future sendUserInviteEmail(UserInvite userInvite, String email) async { HttpieResponse response = await _userInvitesApiService.emailUserInvite( - userInviteId: userInvite.id, email: email); + userInviteId: userInvite.id!, email: email); _checkResponseIsOk(response); } - Future getTrendingCommunities({Category category}) async { + Future getTrendingCommunities({Category? category}) async { HttpieResponse response = await _communitiesApiService .getTrendingCommunities(category: category?.name); _checkResponseIsOk(response); @@ -1346,9 +1346,9 @@ class UserService { } Future createPostForCommunity(Community community, - {String text, File image, File video, bool isDraft}) async { + {String? text, File? image, File? video, bool isDraft = false}) async { HttpieStreamedResponse response = await _communitiesApiService - .createPostForCommunityWithId(community.name, + .createPostForCommunityWithId(community.name!, text: text, image: image, video: video, isDraft: isDraft); _checkResponseIsCreated(response); @@ -1358,18 +1358,18 @@ class UserService { } Future getPostsForCommunity(Community community, - {int maxId, int count}) async { + {int? maxId, int? count}) async { HttpieResponse response = await _communitiesApiService - .getPostsForCommunityWithName(community.name, + .getPostsForCommunityWithName(community.name!, count: count, maxId: maxId); _checkResponseIsOk(response); return PostsList.fromJson(json.decode(response.body)); } - Future countPostsForCommunity(Community community, - {int maxId, int count}) async { + Future countPostsForCommunity(Community community, + {int? maxId, int? count}) async { HttpieResponse response = await _communitiesApiService - .getPostsCountForCommunityWithName(community.name); + .getPostsCountForCommunityWithName(community.name!); _checkResponseIsOk(response); Community responseCommunity = Community.fromJSON(json.decode(response.body)); @@ -1377,16 +1377,16 @@ class UserService { } Future getClosedPostsForCommunity(Community community, - {int maxId, int count}) async { + {int? maxId, int? count}) async { HttpieResponse response = await _communitiesApiService - .getClosedPostsForCommunityWithName(community.name, + .getClosedPostsForCommunityWithName(community.name!, count: count, maxId: maxId); _checkResponseIsOk(response); return PostsList.fromJson(json.decode(response.body)); } Future searchCommunitiesWithQuery(String query, - {bool excludedFromProfilePosts}) async { + {bool? excludedFromProfilePosts}) async { HttpieResponse response = await _communitiesApiService.searchCommunitiesWithQuery( query: query, excludedFromProfilePosts: excludedFromProfilePosts); @@ -1395,23 +1395,23 @@ class UserService { } Future createCommunity( - {@required String name, - @required String title, - @required List categories, - @required CommunityType type, - String color, - String userAdjective, - String usersAdjective, - bool invitesEnabled, - String description, - String rules, - File cover, - File avatar}) async { + {required String name, + required String title, + required List categories, + required CommunityType type, + String? color, + String? userAdjective, + String? usersAdjective, + bool? invitesEnabled, + String? description, + String? rules, + File? cover, + File? avatar}) async { HttpieStreamedResponse response = await _communitiesApiService.createCommunity( name: name, title: title, - categories: categories.map((category) => category.name).toList(), + categories: categories.map((category) => category.name!).toList(), type: Community.convertTypeToString(type), color: color, userAdjective: userAdjective, @@ -1430,25 +1430,25 @@ class UserService { } Future updateCommunity(Community community, - {String name, - String title, - List categories, - CommunityType type, - String color, - String userAdjective, - String usersAdjective, - String description, - bool invitesEnabled, - String rules, - File cover, - File avatar}) async { + {String? name, + String? title, + List? categories, + CommunityType? type, + String? color, + String? userAdjective, + String? usersAdjective, + String? description, + bool? invitesEnabled, + String? rules, + File? cover, + File? avatar}) async { HttpieStreamedResponse response = await _communitiesApiService.updateCommunityWithName( - community.name, + community.name!, name: name, title: title, - categories: categories.map((category) => category.name).toList(), - type: Community.convertTypeToString(type), + categories: categories?.map((category) => category.name!).toList(), + type: type != null ? Community.convertTypeToString(type) : null, color: color, invitesEnabled: invitesEnabled, userAdjective: userAdjective, @@ -1465,9 +1465,9 @@ class UserService { } Future updateAvatarForCommunity(Community community, - {@required File avatar}) async { + {required File avatar}) async { HttpieStreamedResponse response = await _communitiesApiService - .updateAvatarForCommunityWithName(community.name, avatar: avatar); + .updateAvatarForCommunityWithName(community.name!, avatar: avatar); _checkResponseIsOk(response); @@ -1478,7 +1478,7 @@ class UserService { Future deleteAvatarForCommunity(Community community) async { HttpieResponse response = await _communitiesApiService - .deleteAvatarForCommunityWithName(community.name); + .deleteAvatarForCommunityWithName(community.name!); _checkResponseIsOk(response); @@ -1488,9 +1488,9 @@ class UserService { } Future updateCoverForCommunity(Community community, - {@required File cover}) async { + {required File cover}) async { HttpieStreamedResponse response = await _communitiesApiService - .updateCoverForCommunityWithName(community.name, cover: cover); + .updateCoverForCommunityWithName(community.name!, cover: cover); _checkResponseIsOk(response); @@ -1501,7 +1501,7 @@ class UserService { Future deleteCoverForCommunity(Community community) async { HttpieResponse response = await _communitiesApiService - .deleteCoverForCommunityWithName(community.name); + .deleteCoverForCommunityWithName(community.name!); _checkResponseIsOk(response); @@ -1519,14 +1519,14 @@ class UserService { Future deleteCommunity(Community community) async { HttpieResponse response = - await _communitiesApiService.deleteCommunityWithName(community.name); + await _communitiesApiService.deleteCommunityWithName(community.name!); _checkResponseIsOk(response); } Future getMembersForCommunity(Community community, - {int count, int maxId, List exclude}) async { + {int? count, int? maxId, List? exclude}) async { HttpieResponse response = await _communitiesApiService - .getMembersForCommunityWithId(community.name, + .getMembersForCommunityWithId(community.name!, count: count, maxId: maxId, exclude: exclude != null @@ -1542,11 +1542,11 @@ class UserService { } Future searchCommunityMembers( - {@required Community community, - @required String query, - List exclude}) async { + {required Community community, + required String query, + List? exclude}) async { HttpieResponse response = await _communitiesApiService.searchMembers( - communityName: community.name, + communityName: community.name!, query: query, exclude: exclude != null ? exclude @@ -1561,27 +1561,27 @@ class UserService { } Future inviteUserToCommunity( - {@required Community community, @required User user}) async { + {required Community community, required User user}) async { HttpieResponse response = await _communitiesApiService.inviteUserToCommunity( - communityName: community.name, username: user.username); + communityName: community.name!, username: user.username!); _checkResponseIsCreated(response); - return User.fromJson(json.decode(response.body), + User.fromJson(json.decode(response.body), storeInMaxSessionCache: true); } Future uninviteUserFromCommunity( - {@required Community community, @required User user}) async { + {required Community community, required User user}) async { HttpieResponse response = await _communitiesApiService.uninviteUserFromCommunity( - communityName: community.name, username: user.username); + communityName: community.name!, username: user.username!); _checkResponseIsOk(response); - return User.fromJson(json.decode(response.body), + User.fromJson(json.decode(response.body), storeInMaxSessionCache: true); } Future getJoinedCommunities( - {int offset, bool excludedFromProfilePosts}) async { + {int? offset, bool? excludedFromProfilePosts}) async { HttpieResponse response = await _communitiesApiService.getJoinedCommunities( offset: offset, excludedFromProfilePosts: excludedFromProfilePosts); @@ -1591,7 +1591,7 @@ class UserService { } Future searchJoinedCommunities( - {@required String query, int count, Community withCommunity}) async { + {required String query, int? count, Community? withCommunity}) async { HttpieResponse response = await _communitiesApiService .searchJoinedCommunities(query: query, count: count); _checkResponseIsOk(response); @@ -1600,22 +1600,22 @@ class UserService { Future joinCommunity(Community community) async { HttpieResponse response = - await _communitiesApiService.joinCommunityWithId(community.name); + await _communitiesApiService.joinCommunityWithId(community.name!); _checkResponseIsCreated(response); return Community.fromJSON(json.decode(response.body)); } Future leaveCommunity(Community community) async { HttpieResponse response = - await _communitiesApiService.leaveCommunityWithId(community.name); + await _communitiesApiService.leaveCommunityWithId(community.name!); _checkResponseIsOk(response); return Community.fromJSON(json.decode(response.body)); } Future getModeratorsForCommunity(Community community, - {int count, int maxId}) async { + {int? count, int? maxId}) async { HttpieResponse response = await _communitiesApiService - .getModeratorsForCommunityWithId(community.name, + .getModeratorsForCommunityWithId(community.name!, count: count, maxId: maxId); _checkResponseIsOk(response); @@ -1624,11 +1624,11 @@ class UserService { } Future searchCommunityModerators({ - @required Community community, - @required String query, + required Community community, + required String query, }) async { HttpieResponse response = await _communitiesApiService.searchModerators( - communityName: community.name, + communityName: community.name!, query: query, ); @@ -1638,25 +1638,25 @@ class UserService { } Future addCommunityModerator( - {@required Community community, @required User user}) async { + {required Community community, required User user}) async { HttpieResponse response = await _communitiesApiService.addCommunityModerator( - communityName: community.name, username: user.username); + communityName: community.name!, username: user.username!); _checkResponseIsCreated(response); } Future removeCommunityModerator( - {@required Community community, @required User user}) async { + {required Community community, required User user}) async { HttpieResponse response = await _communitiesApiService.removeCommunityModerator( - communityName: community.name, username: user.username); + communityName: community.name!, username: user.username!); _checkResponseIsOk(response); } Future getAdministratorsForCommunity(Community community, - {int count, int maxId}) async { + {int? count, int? maxId}) async { HttpieResponse response = await _communitiesApiService - .getAdministratorsForCommunityWithName(community.name, + .getAdministratorsForCommunityWithName(community.name!, count: count, maxId: maxId); _checkResponseIsOk(response); @@ -1665,11 +1665,11 @@ class UserService { } Future searchCommunityAdministrators({ - @required Community community, - @required String query, + required Community community, + required String query, }) async { HttpieResponse response = await _communitiesApiService.searchAdministrators( - communityName: community.name, + communityName: community.name!, query: query, ); @@ -1678,27 +1678,26 @@ class UserService { return UsersList.fromJson(json.decode(response.body)); } - Future addCommunityAdministrator( - {@required Community community, @required User user}) async { + Future addCommunityAdministrator( + {required Community community, required User user}) async { HttpieResponse response = await _communitiesApiService.addCommunityAdministrator( - communityName: community.name, username: user.username); + communityName: community.name!, username: user.username!); _checkResponseIsCreated(response); - return Community.fromJSON(json.decode(response.body)); } Future removeCommunityAdministrator( - {@required Community community, @required User user}) async { + {required Community community, required User user}) async { HttpieResponse response = await _communitiesApiService.removeCommunityAdministrator( - communityName: community.name, username: user.username); + communityName: community.name!, username: user.username!); _checkResponseIsOk(response); } Future getBannedUsersForCommunity(Community community, - {int count, int maxId}) async { + {int? count, int? maxId}) async { HttpieResponse response = await _communitiesApiService - .getBannedUsersForCommunityWithId(community.name, + .getBannedUsersForCommunityWithId(community.name!, count: count, maxId: maxId); _checkResponseIsOk(response); @@ -1707,11 +1706,11 @@ class UserService { } Future searchCommunityBannedUsers({ - @required Community community, - @required String query, + required Community community, + required String query, }) async { HttpieResponse response = await _communitiesApiService.searchBannedUsers( - communityName: community.name, + communityName: community.name!, query: query, ); @@ -1721,20 +1720,20 @@ class UserService { } Future banCommunityUser( - {@required Community community, @required User user}) async { + {required Community community, required User user}) async { HttpieResponse response = await _communitiesApiService.banCommunityUser( - communityName: community.name, username: user.username); + communityName: community.name!, username: user.username!); _checkResponseIsOk(response); } Future unbanCommunityUser( - {@required Community community, @required User user}) async { + {required Community community, required User user}) async { HttpieResponse response = await _communitiesApiService.unbanCommunityUser( - communityName: community.name, username: user.username); + communityName: community.name!, username: user.username!); _checkResponseIsOk(response); } - Future getFavoriteCommunities({int offset}) async { + Future getFavoriteCommunities({int? offset}) async { HttpieResponse response = await _communitiesApiService.getFavoriteCommunities(offset: offset); @@ -1744,7 +1743,7 @@ class UserService { } Future searchFavoriteCommunities( - {String query, int count}) async { + {required String query, int? count}) async { HttpieResponse response = await _communitiesApiService .searchFavoriteCommunities(query: query, count: count); @@ -1755,37 +1754,37 @@ class UserService { Future favoriteCommunity(Community community) async { HttpieResponse response = await _communitiesApiService.favoriteCommunity( - communityName: community.name); + communityName: community.name!); _checkResponseIsCreated(response); - return Community.fromJSON(json.decode(response.body)); + Community.fromJSON(json.decode(response.body)); } Future unfavoriteCommunity(Community community) async { HttpieResponse response = await _communitiesApiService.unfavoriteCommunity( - communityName: community.name); + communityName: community.name!); _checkResponseIsOk(response); - return Community.fromJSON(json.decode(response.body)); + Community.fromJSON(json.decode(response.body)); } Future enableNewPostNotificationsForCommunity( Community community) async { HttpieResponse response = await _communitiesApiService - .enableNewPostNotificationsForCommunity(communityName: community.name); + .enableNewPostNotificationsForCommunity(communityName: community.name!); _checkResponseIsCreated(response); - return Community.fromJSON(json.decode(response.body)); + Community.fromJSON(json.decode(response.body)); } Future disableNewPostNotificationsForCommunity( Community community) async { HttpieResponse response = await _communitiesApiService - .disableNewPostNotificationsForCommunity(communityName: community.name); + .disableNewPostNotificationsForCommunity(communityName: community.name!); _checkResponseIsOk(response); - return Community.fromJSON(json.decode(response.body)); + Community.fromJSON(json.decode(response.body)); } - Future getAdministratedCommunities({int offset}) async { + Future getAdministratedCommunities({int? offset}) async { HttpieResponse response = await _communitiesApiService .getAdministratedCommunities(offset: offset); @@ -1795,7 +1794,7 @@ class UserService { } Future searchAdministratedCommunities( - {String query, int count}) async { + {required String query, int? count}) async { HttpieResponse response = await _communitiesApiService .searchAdministratedCommunities(query: query, count: count); @@ -1804,7 +1803,7 @@ class UserService { return CommunitiesList.fromJson(json.decode(response.body)); } - Future getModeratedCommunities({int offset}) async { + Future getModeratedCommunities({int? offset}) async { HttpieResponse response = await _communitiesApiService.getModeratedCommunities(offset: offset); @@ -1814,7 +1813,7 @@ class UserService { } Future searchModeratedCommunities( - {String query, int count}) async { + {required String query, int? count}) async { HttpieResponse response = await _communitiesApiService .searchModeratedCommunities(query: query, count: count); @@ -1837,9 +1836,9 @@ class UserService { } Future getPostsForHashtag(Hashtag hashtag, - {int maxId, int count}) async { + {int? maxId, int? count}) async { HttpieResponse response = await _hashtagsApiService - .getPostsForHashtagWithName(hashtag.name, count: count, maxId: maxId); + .getPostsForHashtagWithName(hashtag.name!, count: count, maxId: maxId); _checkResponseIsOk(response); return PostsList.fromJson(json.decode(response.body)); } @@ -1852,7 +1851,7 @@ class UserService { } Future getNotifications( - {int maxId, int count, List types}) async { + {int? maxId, int? count, List? types}) async { HttpieResponse response = await _notificationsApiService.getNotifications( maxId: maxId, count: count, types: types); _checkResponseIsOk(response); @@ -1860,7 +1859,7 @@ class UserService { } Future getUnreadNotificationsCount( - {int maxId, List types}) async { + {int? maxId, List? types}) async { HttpieResponse response = await _notificationsApiService .getUnreadNotificationsCount(maxId: maxId, types: types); _checkResponseIsOk(response); @@ -1875,7 +1874,7 @@ class UserService { } Future readNotifications( - {int maxId, List types}) async { + {int? maxId, List? types}) async { HttpieResponse response = await _notificationsApiService.readNotifications( maxId: maxId, types: types); _checkResponseIsOk(response); @@ -1889,13 +1888,13 @@ class UserService { Future deleteNotification(OBNotification notification) async { HttpieResponse response = await _notificationsApiService - .deleteNotificationWithId(notification.id); + .deleteNotificationWithId(notification.id!); _checkResponseIsOk(response); } Future readNotification(OBNotification notification) async { HttpieResponse response = - await _notificationsApiService.readNotificationWithId(notification.id); + await _notificationsApiService.readNotificationWithId(notification.id!); _checkResponseIsOk(response); } @@ -1910,16 +1909,16 @@ class UserService { _checkResponseIsOk(response); } - Future createDevice({@required String uuid, String name}) async { + Future createDevice({required String uuid, String? name}) async { HttpieResponse response = await _devicesApiService.createDevice(uuid: uuid, name: name); _checkResponseIsCreated(response); return Device.fromJSON(json.decode(response.body)); } - Future updateDevice(Device device, {String name}) async { + Future updateDevice(Device device, {String? name}) async { HttpieResponse response = await _devicesApiService.updateDeviceWithUuid( - device.uuid, + device.uuid!, name: name, ); _checkResponseIsCreated(response); @@ -1928,7 +1927,7 @@ class UserService { Future deleteDevice(Device device) async { HttpieResponse response = - await _devicesApiService.deleteDeviceWithUuid(device.uuid); + await _devicesApiService.deleteDeviceWithUuid(device.uuid!); _checkResponseIsOk(response); } @@ -1941,20 +1940,20 @@ class UserService { Future getOrCreateCurrentDevice() async { if (_getOrCreateCurrentDeviceCache != null) - return _getOrCreateCurrentDeviceCache; + return _getOrCreateCurrentDeviceCache!; _getOrCreateCurrentDeviceCache = _getOrCreateCurrentDevice(); - _getOrCreateCurrentDeviceCache.catchError((error) { + _getOrCreateCurrentDeviceCache!.catchError((error) { _getOrCreateCurrentDeviceCache = null; throw error; }); - return _getOrCreateCurrentDeviceCache; + return _getOrCreateCurrentDeviceCache!; } Future _getOrCreateCurrentDevice() async { if (_getOrCreateCurrentDeviceCache != null) - return _getOrCreateCurrentDeviceCache; + return _getOrCreateCurrentDeviceCache!; String deviceUuid = await _getDeviceUuid(); HttpieResponse response = @@ -1975,10 +1974,10 @@ class UserService { Future _deleteCurrentDevice() async { if (_getOrCreateCurrentDeviceCache == null) return; - Device currentDevice = await _getOrCreateCurrentDeviceCache; + Device currentDevice = await _getOrCreateCurrentDeviceCache!; HttpieResponse response = - await _devicesApiService.deleteDeviceWithUuid(currentDevice.uuid); + await _devicesApiService.deleteDeviceWithUuid(currentDevice.uuid!); if (!response.isOk() && !response.isNotFound()) { print('Could not delete current device'); @@ -1997,20 +1996,20 @@ class UserService { Future updateAuthenticatedUserNotificationsSettings({ - bool postCommentNotifications, - bool postCommentReplyNotifications, - bool postCommentReactionNotifications, - bool postCommentUserMentionNotifications, - bool postUserMentionNotifications, - bool postReactionNotifications, - bool followNotifications, - bool followRequestNotifications, - bool followRequestApprovedNotifications, - bool connectionRequestNotifications, - bool connectionConfirmedNotifications, - bool communityInviteNotifications, - bool communityNewPostNotifications, - bool userNewPostNotifications, + bool? postCommentNotifications, + bool? postCommentReplyNotifications, + bool? postCommentReactionNotifications, + bool? postCommentUserMentionNotifications, + bool? postUserMentionNotifications, + bool? postReactionNotifications, + bool? followNotifications, + bool? followRequestNotifications, + bool? followRequestApprovedNotifications, + bool? connectionRequestNotifications, + bool? connectionConfirmedNotifications, + bool? communityInviteNotifications, + bool? communityNewPostNotifications, + bool? userNewPostNotifications, }) async { HttpieResponse response = await _authApiService.updateAuthenticatedUserNotificationsSettings( @@ -2035,69 +2034,69 @@ class UserService { } Future reportUser( - {@required User user, - String description, - @required ModerationCategory moderationCategory}) async { + {required User user, + String? description, + required ModerationCategory moderationCategory}) async { HttpieResponse response = await _authApiService.reportUserWithUsername( description: description, - userUsername: user.username, - moderationCategoryId: moderationCategory.id); + userUsername: user.username!, + moderationCategoryId: moderationCategory.id!); _checkResponseIsCreated(response); } Future reportHashtag( - {@required Hashtag hashtag, - String description, - @required ModerationCategory moderationCategory}) async { + {required Hashtag hashtag, + String? description, + required ModerationCategory moderationCategory}) async { HttpieResponse response = await _hashtagsApiService.reportHashtagWithName( description: description, - hashtagName: hashtag.name, - moderationCategoryId: moderationCategory.id); + hashtagName: hashtag.name!, + moderationCategoryId: moderationCategory.id!); _checkResponseIsCreated(response); } Future reportCommunity( - {@required Community community, - String description, - @required ModerationCategory moderationCategory}) async { + {required Community community, + String? description, + required ModerationCategory moderationCategory}) async { HttpieResponse response = await _communitiesApiService.reportCommunityWithName( - communityName: community.name, + communityName: community.name!, description: description, - moderationCategoryId: moderationCategory.id); + moderationCategoryId: moderationCategory.id!); _checkResponseIsCreated(response); } Future reportPost( - {@required Post post, - String description, - @required ModerationCategory moderationCategory}) async { + {required Post post, + String? description, + required ModerationCategory moderationCategory}) async { HttpieResponse response = await _postsApiService.reportPost( description: description, - postUuid: post.uuid, - moderationCategoryId: moderationCategory.id); + postUuid: post.uuid!, + moderationCategoryId: moderationCategory.id!); _checkResponseIsCreated(response); } Future reportPostComment( - {@required PostComment postComment, - @required Post post, - String description, - @required ModerationCategory moderationCategory}) async { + {required PostComment postComment, + required Post post, + String? description, + required ModerationCategory moderationCategory}) async { HttpieResponse response = await _postsApiService.reportPostComment( - postCommentId: postComment.id, - postUuid: post.uuid, + postCommentId: postComment.id!, + postUuid: post.uuid!, description: description, - moderationCategoryId: moderationCategory.id); + moderationCategoryId: moderationCategory.id!); _checkResponseIsCreated(response); } Future getGlobalModeratedObjects( - {List statuses, - List types, - int count, - int maxId, - bool verified}) async { + {List? statuses, + List? types, + int? count, + int? maxId, + bool? verified}) async { HttpieResponse response = await _moderationApiService .getGlobalModeratedObjects( @@ -2106,7 +2105,7 @@ class UserService { types: types != null ? types .map((ModeratedObjectType type) => - ModeratedObject.factory.convertTypeToString(type)) + ModeratedObject.factory.convertTypeToString(type)!) .toList() : null, statuses: @@ -2115,7 +2114,7 @@ class UserService { .map( (ModeratedObjectStatus status) => ModeratedObject.factory - .convertStatusToString(status)) + .convertStatusToString(status)!) .toList() : null, count: count); @@ -2126,26 +2125,26 @@ class UserService { } Future getCommunityModeratedObjects( - {@required Community community, - List statuses, - List types, - int count, - int maxId, - bool verified}) async { + {required Community community, + List? statuses, + List? types, + int? count, + int? maxId, + bool? verified}) async { HttpieResponse response = await _communitiesApiService.getModeratedObjects( - communityName: community.name, + communityName: community.name!, maxId: maxId, verified: verified, types: types != null ? types .map((status) => - ModeratedObject.factory.convertTypeToString(status)) + ModeratedObject.factory.convertTypeToString(status)!) .toList() : null, statuses: statuses != null ? statuses .map((status) => - ModeratedObject.factory.convertStatusToString(status)) + ModeratedObject.factory.convertStatusToString(status)!) .toList() : null, count: count); @@ -2156,26 +2155,26 @@ class UserService { } Future updateModeratedObject(ModeratedObject moderatedObject, - {String description, ModerationCategory category}) async { + {String? description, ModerationCategory? category}) async { HttpieResponse response = await _moderationApiService - .updateModeratedObjectWithId(moderatedObject.id, + .updateModeratedObjectWithId(moderatedObject.id!, description: description, categoryId: category?.id); _checkResponseIsOk(response); - return ModeratedObject.fromJSON(json.decode(response.body)); + ModeratedObject.fromJSON(json.decode(response.body)); } Future verifyModeratedObject(ModeratedObject moderatedObject) async { HttpieResponse response = await _moderationApiService - .verifyModeratedObjectWithId(moderatedObject.id); + .verifyModeratedObjectWithId(moderatedObject.id!); _checkResponseIsOk(response); } Future getModeratedObjectLogs( ModeratedObject moderatedObject, - {int maxId, - int count}) async { + {int? maxId, + int? count}) async { HttpieResponse response = await _moderationApiService - .getModeratedObjectLogs(moderatedObject.id, maxId: maxId, count: count); + .getModeratedObjectLogs(moderatedObject.id!, maxId: maxId, count: count); _checkResponseIsOk(response); return ModeratedObjectLogsList.fromJson(json.decode(response.body)); @@ -2183,10 +2182,10 @@ class UserService { Future getModeratedObjectReports( ModeratedObject moderatedObject, - {int maxId, - int count}) async { + {int? maxId, + int? count}) async { HttpieResponse response = await _moderationApiService - .getModeratedObjectReports(moderatedObject.id, + .getModeratedObjectReports(moderatedObject.id!, maxId: maxId, count: count); _checkResponseIsOk(response); @@ -2194,7 +2193,7 @@ class UserService { } Future getModerationPenalties( - {int maxId, int count}) async { + {int? maxId, int? count}) async { HttpieResponse response = await _moderationApiService .getUserModerationPenalties(maxId: maxId, count: count); _checkResponseIsOk(response); @@ -2203,7 +2202,7 @@ class UserService { } Future getPendingModeratedObjectsCommunities( - {int maxId, int count}) async { + {int? maxId, int? count}) async { HttpieResponse response = await _moderationApiService .getUserPendingModeratedObjectsCommunities(maxId: maxId, count: count); _checkResponseIsOk(response); @@ -2213,19 +2212,19 @@ class UserService { Future unverifyModeratedObject(ModeratedObject moderatedObject) async { HttpieResponse response = await _moderationApiService - .unverifyModeratedObjectWithId(moderatedObject.id); + .unverifyModeratedObjectWithId(moderatedObject.id!); _checkResponseIsOk(response); } Future approveModeratedObject(ModeratedObject moderatedObject) async { HttpieResponse response = await _moderationApiService - .approveModeratedObjectWithId(moderatedObject.id); + .approveModeratedObjectWithId(moderatedObject.id!); _checkResponseIsOk(response); } Future rejectModeratedObject(ModeratedObject moderatedObject) async { HttpieResponse response = await _moderationApiService - .rejectModeratedObjectWithId(moderatedObject.id); + .rejectModeratedObjectWithId(moderatedObject.id!); _checkResponseIsOk(response); } @@ -2238,9 +2237,9 @@ class UserService { return ModerationCategoriesList.fromJson(json.decode(response.body)); } - Future translatePost({@required Post post}) async { + Future translatePost({required Post post}) async { HttpieResponse response = - await _postsApiService.translatePost(postUuid: post.uuid); + await _postsApiService.translatePost(postUuid: post.uuid!); _checkResponseIsOk(response); @@ -2248,9 +2247,9 @@ class UserService { } Future translatePostComment( - {@required Post post, @required PostComment postComment}) async { + {required Post post, required PostComment postComment}) async { HttpieResponse response = await _postsApiService.translatePostComment( - postUuid: post.uuid, postCommentId: postComment.id); + postUuid: post.uuid!, postCommentId: postComment.id!); _checkResponseIsOk(response); @@ -2258,28 +2257,28 @@ class UserService { } Future getPostParticipants( - {@required Post post, int count}) async { + {required Post post, int? count}) async { HttpieResponse response = await _postsApiService.getPostParticipants( - count: count, postUuid: post.uuid); + count: count, postUuid: post.uuid!); _checkResponseIsOk(response); return UsersList.fromJson(json.decode(response.body)); } Future searchPostParticipants( - {@required String query, @required Post post, int count}) async { + {required String query, required Post post, int? count}) async { HttpieResponse response = await _postsApiService.searchPostParticipants( - query: query, count: count, postUuid: post.uuid); + query: query, count: count, postUuid: post.uuid!); _checkResponseIsOk(response); return UsersList.fromJson(json.decode(response.body)); } - Future previewLink({@required String link}) async { + Future previewLink({required String link}) async { HttpieResponse response = await _postsApiService.previewLink(link: link); _checkResponseIsOk(response); return LinkPreview.fromJSON(json.decode(response.body)); } - Future linkIsPreviewable({@required String link}) async { + Future linkIsPreviewable({required String link}) async { HttpieResponse response = await _postsApiService.linkIsPreviewable(link: link); _checkResponseIsOk(response); @@ -2359,9 +2358,9 @@ class UserService { Future setLanguageFromDefaults() async { Locale currentLocale = _localizationService.getLocale(); LanguagesList languageList = await getAllLanguages(); - Language deviceLanguage = - languageList.languages.firstWhere((Language language) { - return language.code.toLowerCase() == + Language? deviceLanguage = + languageList.languages?.firstWhere((Language language) { + return language.code?.toLowerCase() == currentLocale.languageCode.toLowerCase(); }); @@ -2369,9 +2368,9 @@ class UserService { print('Setting language from defaults ${currentLocale.languageCode}'); return await setNewLanguage(deviceLanguage); } else { - Language english = languageList.languages.firstWhere( - (Language language) => language.code.toLowerCase() == 'en'); - return await setNewLanguage(english); + Language? english = languageList.languages?.firstWhere( + (Language language) => language.code?.toLowerCase() == 'en'); + return await setNewLanguage(english!); } } @@ -2391,7 +2390,7 @@ class UserService { } void _setLoggedInUser(User user) { - if (_loggedInUser == null || _loggedInUser.id != user.id) + if (_loggedInUser == null || _loggedInUser!.id != user.id) _loggedInUserChangeSubject.add(user); _loggedInUser = user; } @@ -2411,8 +2410,8 @@ class UserService { return _userStorage.set(STORAGE_KEY_AUTH_TOKEN, authToken); } - Future _getStoredAuthToken() async { - String authToken = await _userStorage.get(STORAGE_KEY_AUTH_TOKEN); + Future _getStoredAuthToken() async { + String? authToken = await _userStorage.get(STORAGE_KEY_AUTH_TOKEN); if (authToken != null) _authToken = authToken; return authToken; } @@ -2429,7 +2428,7 @@ class UserService { _userStorage.remove(STORAGE_KEY_USER_DATA); } - Future _getStoredUserData() async { + Future _getStoredUserData() async { return _userStorage.get(STORAGE_KEY_USER_DATA); } @@ -2441,7 +2440,7 @@ class UserService { _userStorage.remove(STORAGE_FIRST_POSTS_DATA); } - Future _getStoredFirstPostsData() async { + Future _getStoredFirstPostsData() async { return _userStorage.get(STORAGE_FIRST_POSTS_DATA); } @@ -2453,7 +2452,7 @@ class UserService { _userStorage.remove(STORAGE_TOP_POSTS_DATA); } - Future _getStoredTopPostsData() async { + Future _getStoredTopPostsData() async { return _userStorage.get(STORAGE_TOP_POSTS_DATA); } @@ -2465,7 +2464,7 @@ class UserService { _userStorage.remove(STORAGE_TOP_POSTS_LAST_VIEWED_ID); } - Future _getStoredTopPostsLastViewedId() async { + Future _getStoredTopPostsLastViewedId() async { return _userStorage.get(STORAGE_TOP_POSTS_LAST_VIEWED_ID); } diff --git a/lib/services/user_invites_api.dart b/lib/services/user_invites_api.dart index f6a39668f..05561f5d5 100644 --- a/lib/services/user_invites_api.dart +++ b/lib/services/user_invites_api.dart @@ -3,10 +3,10 @@ import 'package:Okuna/services/string_template.dart'; import 'package:meta/meta.dart'; class UserInvitesApiService { - HttpieService _httpService; - StringTemplateService _stringTemplateService; + late HttpieService _httpService; + late StringTemplateService _stringTemplateService; - String apiURL; + late String apiURL; static const GET_USER_INVITES_PATH = 'api/invites/'; static const SEARCH_USER_INVITES_PATH = 'api/invites/search/'; @@ -29,7 +29,7 @@ class UserInvitesApiService { } Future createUserInvite( - {@required String nickname}) { + {required String nickname}) { Map body = {}; if (nickname != null) { @@ -41,7 +41,7 @@ class UserInvitesApiService { } Future updateUserInvite( - {@required String nickname, @required int userInviteId}) { + {required String? nickname, required int userInviteId}) { Map body = {}; if (nickname != null) { @@ -53,9 +53,9 @@ class UserInvitesApiService { } Future getUserInvites( - { int offset, - int count, - bool isStatusPending}) { + { int? offset, + int? count, + bool? isStatusPending}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -68,9 +68,9 @@ class UserInvitesApiService { } Future searchUserInvites( - { int count, - bool isStatusPending, - String query}) { + { int? count, + bool? isStatusPending, + String? query}) { Map queryParams = {}; if (count != null) queryParams['count'] = count; @@ -89,7 +89,7 @@ class UserInvitesApiService { } Future emailUserInvite( - {@required int userInviteId, @required String email}) { + {required int userInviteId, required String email}) { String path = _stringTemplateService.parse(EMAIL_INVITE_PATH, {'userInviteId': userInviteId}); Map body = {}; diff --git a/lib/services/user_preferences.dart b/lib/services/user_preferences.dart index cb5281ff5..0069561d9 100644 --- a/lib/services/user_preferences.dart +++ b/lib/services/user_preferences.dart @@ -9,9 +9,9 @@ import 'package:rxdart/rxdart.dart'; import 'localization.dart'; class UserPreferencesService { - LocalizationService _localizationService; - OBStorage _storage; - ConnectivityService _connectivityService; + late LocalizationService _localizationService; + late OBStorage _storage; + late ConnectivityService _connectivityService; static const postCommentsSortTypeStorageKey = 'postCommentsSortType'; static const videosAutoPlaySettingStorageKey = 'videosAutoPlaySetting'; @@ -19,10 +19,10 @@ class UserPreferencesService { static const videosSoundSettingStorageKey = 'videoSoundSetting'; static const hashtagsDisplaySettingStorageKey = 'hashtagsSetting'; - ConnectivityResult _currentConnectivity; - StreamSubscription _connectivityChangeSubscription; + ConnectivityResult? _currentConnectivity; + StreamSubscription? _connectivityChangeSubscription; - Future _getPostCommentsSortTypeCache; + Future? _getPostCommentsSortTypeCache; Stream get videosAutoPlayAreEnabledChange => _videosAutoPlayEnabledChangeSubject.stream; @@ -56,7 +56,7 @@ class UserPreferencesService { final _videosAutoPlaySettingChangeSubject = BehaviorSubject(); - HashtagsDisplaySetting currentHashtagsDisplaySetting; + HashtagsDisplaySetting? currentHashtagsDisplaySetting; Stream get hashtagsDisplaySettingChange => _hashtagsDisplaySettingChangeSubject.stream; @@ -77,8 +77,10 @@ class UserPreferencesService { _connectivityChangeSubscription = _connectivityService.onConnectivityChange(_onConnectivityChange); - HashtagsDisplaySetting hashtagsDisplaySetting = await getHashtagsDisplaySetting(); - _hashtagsDisplaySettingChangeSubject.add(hashtagsDisplaySetting); + HashtagsDisplaySetting? hashtagsDisplaySetting = await getHashtagsDisplaySetting(); + if (hashtagsDisplaySetting != null) { + _hashtagsDisplaySettingChangeSubject.add(hashtagsDisplaySetting); + } } void _onConnectivityChange(ConnectivityResult newConnectivity) { @@ -115,9 +117,9 @@ class UserPreferencesService { _refreshLinkPreviewsAreEnabled(); } - Future getLinkPreviewsSetting() async { - String rawValue = await _storage.get(linkPreviewsSettingStorageKey, - defaultValue: LinkPreviewsSetting.always.toString()); + Future getLinkPreviewsSetting() async { + String rawValue = (await _storage.get(linkPreviewsSettingStorageKey, + defaultValue: LinkPreviewsSetting.always.toString()))!; return LinkPreviewsSetting.parse(rawValue); } @@ -144,9 +146,9 @@ class UserPreferencesService { _refreshVideosAutoPlayAreEnabled(); } - Future getVideosAutoPlaySetting() async { - String rawValue = await _storage.get(videosAutoPlaySettingStorageKey, - defaultValue: VideosAutoPlaySetting.wifiOnly.toString()); + Future getVideosAutoPlaySetting() async { + String rawValue = (await _storage.get(videosAutoPlaySettingStorageKey, + defaultValue: VideosAutoPlaySetting.wifiOnly.toString()))!; return VideosAutoPlaySetting.parse(rawValue); } @@ -167,9 +169,9 @@ class UserPreferencesService { return _storage.set(videosSoundSettingStorageKey, rawValue); } - Future getVideosSoundSetting() async { - String rawValue = await _storage.get(videosSoundSettingStorageKey, - defaultValue: VideosSoundSetting.disabled.toString()); + Future getVideosSoundSetting() async { + String rawValue = (await _storage.get(videosSoundSettingStorageKey, + defaultValue: VideosSoundSetting.disabled.toString()))!; return VideosSoundSetting.parse(rawValue); } @@ -190,9 +192,9 @@ class UserPreferencesService { return _storage.set(hashtagsDisplaySettingStorageKey, rawValue); } - Future getHashtagsDisplaySetting() async { - String rawValue = await _storage.get(hashtagsDisplaySettingStorageKey, - defaultValue: HashtagsDisplaySetting.traditional.toString()); + Future getHashtagsDisplaySetting() async { + String rawValue = (await _storage.get(hashtagsDisplaySettingStorageKey, + defaultValue: HashtagsDisplaySetting.traditional.toString()))!; return HashtagsDisplaySetting.parse(rawValue); } @@ -214,13 +216,13 @@ class UserPreferencesService { Future getPostCommentsSortType() async { if (_getPostCommentsSortTypeCache != null) - return _getPostCommentsSortTypeCache; + return _getPostCommentsSortTypeCache!; _getPostCommentsSortTypeCache = _getPostCommentsSortType(); - return _getPostCommentsSortTypeCache; + return _getPostCommentsSortTypeCache!; } Future _getPostCommentsSortType() async { - String rawType = await _storage.get(postCommentsSortTypeStorageKey); + String? rawType = await _storage.get(postCommentsSortTypeStorageKey); if (rawType == null) { PostCommentsSortType defaultSortType = _getDefaultPostCommentsSortType(); await setPostCommentsSortType(defaultSortType); @@ -239,7 +241,7 @@ class UserPreferencesService { } void _refreshLinkPreviewsAreEnabled() async { - LinkPreviewsSetting currentLinkPreviewsSetting = + LinkPreviewsSetting? currentLinkPreviewsSetting = await getLinkPreviewsSetting(); _linkPreviewsAreEnabled = currentLinkPreviewsSetting == LinkPreviewsSetting.always || @@ -249,7 +251,7 @@ class UserPreferencesService { } void _refreshVideosAutoPlayAreEnabled() async { - VideosAutoPlaySetting currentVideosAutoPlaySetting = + VideosAutoPlaySetting? currentVideosAutoPlaySetting = await getVideosAutoPlaySetting(); _videosAutoPlayAreEnabled = currentVideosAutoPlaySetting == VideosAutoPlaySetting.always || @@ -278,10 +280,10 @@ class VideosAutoPlaySetting { static values() => _values; - static VideosAutoPlaySetting parse(String string) { + static VideosAutoPlaySetting? parse(String? string) { if (string == null) return null; - VideosAutoPlaySetting autoPlaySetting; + VideosAutoPlaySetting? autoPlaySetting; for (var type in _values) { if (string == type.code) { autoPlaySetting = type; @@ -312,10 +314,10 @@ class VideosSoundSetting { static values() => _values; - static VideosSoundSetting parse(String string) { + static VideosSoundSetting? parse(String? string) { if (string == null) return null; - VideosSoundSetting soundSetting; + VideosSoundSetting? soundSetting; for (var type in _values) { if (string == type.code) { soundSetting = type; @@ -347,10 +349,10 @@ class LinkPreviewsSetting { static values() => _values; - static LinkPreviewsSetting parse(String string) { + static LinkPreviewsSetting? parse(String? string) { if (string == null) return null; - LinkPreviewsSetting autoPlaySetting; + LinkPreviewsSetting? autoPlaySetting; for (var type in _values) { if (string == type.code) { autoPlaySetting = type; @@ -381,10 +383,10 @@ class HashtagsDisplaySetting { static values() => _values; - static HashtagsDisplaySetting parse(String string) { + static HashtagsDisplaySetting? parse(String? string) { if (string == null) return null; - HashtagsDisplaySetting setting; + HashtagsDisplaySetting? setting; for (var type in _values) { if (string == type.code) { setting = type; diff --git a/lib/services/utils_service.dart b/lib/services/utils_service.dart index 50c1ba21c..7021bd29b 100644 --- a/lib/services/utils_service.dart +++ b/lib/services/utils_service.dart @@ -18,10 +18,10 @@ class UtilsService { String _trustedProxyUrl = ''; static SimpleCache hexColorIsDarkCache = - SimpleCache(storage: SimpleStorage(size: 30)); + SimpleCache(storage: new InMemoryStorage(30)); static SimpleCache parseHexColorCache = - SimpleCache(storage: SimpleStorage(size: 30)); + SimpleCache(storage: new InMemoryStorage(30)); static RegExp hashtagsRegExp = RegExp(r"\B#\w*[a-zA-Z]+\w*", caseSensitive: false); @@ -31,30 +31,28 @@ class UtilsService { } Future fileHasImageMimeType(File file) async { - String fileMimeType = - await getFileMimeType(file) ?? 'application/octet-stream'; + String fileMimeType = await getFileMimeType(file); MediaType fileMediaType = MediaType.parse(fileMimeType); return fileMediaType.type == 'image'; } - Future getFileExtensionForFile(File file) async { - String fileMimeType = - await getFileMimeType(file) ?? 'application/octet-stream'; + Future getFileExtensionForFile(File file) async { + String fileMimeType = await getFileMimeType(file); return getFileExtensionForMimeType(fileMimeType); } - String getFileExtensionForMimeType(String mimeType) { + String? getFileExtensionForMimeType(String mimeType) { return lookupExtension(mimeType); } - String geFileNameMimeType(String fileName) { + String? geFileNameMimeType(String fileName) { return lookupMimeType(fileName); } Future getFileMimeType(File file) async { - String mimeType = lookupMimeType(file.path); + String? mimeType = lookupMimeType(file.path); if (mimeType == null) { mimeType = await _getFileMimeTypeFromMagicHeaders(file); @@ -75,7 +73,7 @@ class UtilsService { return isDark; } - List extractHashtagsInString(String str) { + List extractHashtagsInString(String str) { return hashtagsRegExp .allMatches(str) .map((match) => match.group(0)) @@ -150,7 +148,7 @@ class UtilsService { return initializeDateFormatting(localeName, null); } - Future _getFileMimeTypeFromMagicHeaders(File file) async { + Future _getFileMimeTypeFromMagicHeaders(File file) async { // TODO When file uploads become larger, this needs to be turned into a stream List fileBytes = file.readAsBytesSync(); @@ -163,7 +161,7 @@ class UtilsService { magicHeaderBytesLeft--; } - String mimetype = lookupMimeType(file.path, headerBytes: magicHeaders); + String? mimetype = lookupMimeType(file.path, headerBytes: magicHeaders); return mimetype; } @@ -178,11 +176,11 @@ class UtilsService { /// Lookup file extension by a given MIME type. /// If no extension is found, `null` is returned. - String lookupExtension(String mimeType) { + String? lookupExtension(String mimeType) { if (_preferredExtensionsMap.containsKey(mimeType)) { return _preferredExtensionsMap[mimeType]; } - String extension; + String? extension; defaultExtensionMap.forEach((String ext, String test) { if (mimeType.toLowerCase() == test) { extension = ext; @@ -199,16 +197,16 @@ class UtilsService { return getLinkToPreviewFromText(text) != null; } - String getLinkToPreviewFromText(String text) { + String? getLinkToPreviewFromText(String text) { List matches = []; - String previewUrl; + String? previewUrl; matches.addAll(linkRegex.allMatches(text).map((match) { return match.group(0); })); if (matches.length > 0) { Uri url = Uri.parse(matches.first); - String urlMimeType = geFileNameMimeType(url.path); + String? urlMimeType = geFileNameMimeType(url.path); if (urlMimeType != null) { String urlFirstType = urlMimeType.split('/').first; if (urlFirstType != 'image' && urlFirstType != 'text') return null; diff --git a/lib/services/validation.dart b/lib/services/validation.dart index 8a6243595..9b0272e99 100644 --- a/lib/services/validation.dart +++ b/lib/services/validation.dart @@ -11,12 +11,12 @@ import 'package:validators/validators.dart' as validators; import 'localization.dart'; class ValidationService { - AuthApiService _authApiService; - CommunitiesApiService _communitiesApiService; - FollowsListsApiService _followsListsApiService; - ConnectionsCirclesApiService _connectionsCirclesApiService; - LocalizationService _localizationService; - UtilsService _utilsService; + late AuthApiService _authApiService; + late CommunitiesApiService _communitiesApiService; + late FollowsListsApiService _followsListsApiService; + late ConnectionsCirclesApiService _connectionsCirclesApiService; + late LocalizationService _localizationService; + late UtilsService _utilsService; static const int USERNAME_MAX_LENGTH = 30; static const int COMMUNITY_NAME_MAX_LENGTH = 32; @@ -110,13 +110,13 @@ class ValidationService { } bool isPostTextContainingValidHashtags(String postText) { - List hashtags = _utilsService.extractHashtagsInString(postText); + List hashtags = _utilsService.extractHashtagsInString(postText); bool hashtagsHaveAllowedMaxCharacters = true; hashtags .takeWhile((hashtag) => hashtagsHaveAllowedMaxCharacters) .forEach((hashtag) { - if (hashtag.length > HASHTAG_MAX_LENGTH) { + if (hashtag != null && hashtag.length > HASHTAG_MAX_LENGTH) { hashtagsHaveAllowedMaxCharacters = false; } }); @@ -297,12 +297,12 @@ class ValidationService { } } - String validateUserUsername(String username) { + String? validateUserUsername(String? username) { assert(username != null); - String errorMsg; + String? errorMsg; - if (username.length == 0) { + if (username!.length == 0) { errorMsg = _localizationService.auth__username_empty_error; } else if (!isUsernameAllowedLength(username)) { errorMsg = _localizationService @@ -314,12 +314,12 @@ class ValidationService { return errorMsg; } - String validatePostComment(String postComment) { + String? validatePostComment(String? postComment) { assert(postComment != null); - String errorMsg; + String? errorMsg; - if (postComment.length == 0) { + if (postComment!.length == 0) { errorMsg = _localizationService.post__comment_required_error; } else if (!isPostCommentAllowedLength(postComment)) { errorMsg = _localizationService @@ -329,12 +329,12 @@ class ValidationService { return errorMsg; } - String validateUserEmail(String email) { + String? validateUserEmail(String? email) { assert(email != null); - String errorMsg; + String? errorMsg; - if (email.length == 0) { + if (email!.length == 0) { errorMsg = _localizationService.auth__email_empty_error; } else if (!isQualifiedEmail(email)) { errorMsg = _localizationService.auth__email_invalid_error; @@ -343,12 +343,12 @@ class ValidationService { return errorMsg; } - String validateUserRegistrationLink(String link) { + String? validateUserRegistrationLink(String? link) { assert(link != null); - String errorMsg; + String? errorMsg; - if (link.length == 0) { + if (link!.length == 0) { errorMsg = _localizationService.auth__create_acc__link_empty_error; } else if (!isQualifiedLink(link)) { errorMsg = _localizationService.auth__create_acc__link_invalid_error; @@ -357,12 +357,12 @@ class ValidationService { return errorMsg; } - String validateUserPassword(String password) { + String? validateUserPassword(String? password) { assert(password != null); - String errorMsg; + String? errorMsg; - if (password.length == 0) { + if (password!.length == 0) { errorMsg = _localizationService.auth__password_empty_error; } else if (!isPasswordAllowedLength(password)) { errorMsg = _localizationService.auth__password_range_error( @@ -372,12 +372,12 @@ class ValidationService { return errorMsg; } - String validateUserProfileName(String name) { + String? validateUserProfileName(String? name) { assert(name != null); - String errorMsg; + String? errorMsg; - if (name.isEmpty) { + if (name!.isEmpty) { errorMsg = _localizationService.auth__name_empty_error; } else if (!isNameAllowedLength(name)) { errorMsg = _localizationService.auth__name_range_error( @@ -386,12 +386,12 @@ class ValidationService { return errorMsg; } - String validateModeratedObjectDescription(String description) { + String? validateModeratedObjectDescription(String? description) { assert(description != null); - String errorMsg; + String? errorMsg; - if (description.isEmpty) { + if (description!.isEmpty) { errorMsg = _localizationService.auth__description_empty_error; } else if (!isModeratedObjectDescriptionAllowedLength(description)) { errorMsg = _localizationService.auth__description_range_error( @@ -401,12 +401,12 @@ class ValidationService { return errorMsg; } - String validateUserProfileUrl(String url) { + String? validateUserProfileUrl(String? url) { assert(url != null); - if (url.isEmpty) return null; + if (url!.isEmpty) return null; - String errorMsg; + String? errorMsg; if (!isUrl(url)) { errorMsg = _localizationService.user__profile_url_invalid_error; @@ -415,12 +415,12 @@ class ValidationService { return errorMsg; } - String validateUserProfileLocation(String location) { + String? validateUserProfileLocation(String? location) { assert(location != null); - if (location.isEmpty) return null; + if (location!.isEmpty) return null; - String errorMsg; + String? errorMsg; if (!isLocationAllowedLength(location)) { errorMsg = _localizationService @@ -430,12 +430,12 @@ class ValidationService { return errorMsg; } - String validateUserProfileBio(String bio) { + String? validateUserProfileBio(String? bio) { assert(bio != null); - if (bio.isEmpty) return null; + if (bio!.isEmpty) return null; - String errorMsg; + String? errorMsg; if (!isBioAllowedLength(bio)) { errorMsg = _localizationService @@ -445,12 +445,12 @@ class ValidationService { return errorMsg; } - String validateFollowsListName(String name) { + String? validateFollowsListName(String? name) { assert(name != null); - String errorMsg; + String? errorMsg; - if (name.length == 0) { + if (name!.length == 0) { errorMsg = _localizationService.user__list_name_empty_error; } else if (!isFollowsListNameAllowedLength(name)) { errorMsg = @@ -460,12 +460,12 @@ class ValidationService { return errorMsg; } - String validateConnectionsCircleName(String name) { + String? validateConnectionsCircleName(String? name) { assert(name != null); - String errorMsg; + String? errorMsg; - if (name.length == 0) { + if (name!.length == 0) { errorMsg = _localizationService.user__circle_name_empty_error; } else if (!isConnectionsCircleNameAllowedLength(name)) { errorMsg = @@ -475,12 +475,12 @@ class ValidationService { return errorMsg; } - String validateCommunityName(String name) { + String? validateCommunityName(String? name) { assert(name != null); - String errorMsg; + String? errorMsg; - if (name.length == 0) { + if (name!.length == 0) { errorMsg = _localizationService.community__name_empty_error; } else if (!isCommunityNameAllowedLength(name)) { errorMsg = _localizationService @@ -492,12 +492,12 @@ class ValidationService { return errorMsg; } - String validateCommunityTitle(String title) { + String? validateCommunityTitle(String? title) { assert(title != null); - String errorMsg; + String? errorMsg; - if (title.length == 0) { + if (title!.length == 0) { errorMsg = _localizationService.community__title_empty_error; } else if (!isCommunityTitleAllowedLength(title)) { errorMsg = _localizationService @@ -506,14 +506,14 @@ class ValidationService { return errorMsg; } - String validateCommunityRules(String rules) { + String? validateCommunityRules(String? rules) { assert(rules != null); - if (rules.isEmpty) return null; + if (rules?.isEmpty ?? false) return null; - String errorMsg; + String? errorMsg; - if (rules.length == 0) { + if (rules!.length == 0) { errorMsg = _localizationService.community__rules_empty_error; } else if (!isCommunityRulesAllowedLength(rules)) { errorMsg = _localizationService @@ -522,12 +522,12 @@ class ValidationService { return errorMsg; } - String validateCommunityDescription(String description) { + String? validateCommunityDescription(String? description) { assert(description != null); - if (description.isEmpty) return null; + if (description!.isEmpty) return null; - String errorMsg; + String? errorMsg; if (!isCommunityDescriptionAllowedLength(description)) { errorMsg = _localizationService @@ -536,12 +536,12 @@ class ValidationService { return errorMsg; } - String validateCommunityUserAdjective(String userAdjective) { + String? validateCommunityUserAdjective(String? userAdjective) { assert(userAdjective != null); - if (userAdjective.isEmpty) return null; + if (userAdjective!.isEmpty) return null; - String errorMsg; + String? errorMsg; if (!isCommunityUserAdjectiveAllowedLength(userAdjective)) { errorMsg = _localizationService.community__adjectives_range_error( diff --git a/lib/services/waitlist_service.dart b/lib/services/waitlist_service.dart index dd792321b..445414a57 100644 --- a/lib/services/waitlist_service.dart +++ b/lib/services/waitlist_service.dart @@ -1,8 +1,8 @@ import 'package:Okuna/services/httpie.dart'; class WaitlistApiService { - HttpieService _httpService; - String openbookSocialApiURL; + late HttpieService _httpService; + late String openbookSocialApiURL; static const MAILCHIMP_SUBSCRIBE_PATH = 'waitlist/subscribe/'; static const HEALTH_PATH = 'health/'; @@ -15,7 +15,7 @@ class WaitlistApiService { _httpService = httpService; } - Future subscribeToBetaWaitlist({String email}) { + Future subscribeToBetaWaitlist({String? email}) { var body = {}; if (email != null && email != '') { body['email'] = email; @@ -24,4 +24,4 @@ class WaitlistApiService { ._httpService .postJSON('$openbookSocialApiURL$MAILCHIMP_SUBSCRIBE_PATH', body: body); } -} \ No newline at end of file +} diff --git a/lib/widgets/alerts/alert.dart b/lib/widgets/alerts/alert.dart index b2a58ef35..956a6889a 100644 --- a/lib/widgets/alerts/alert.dart +++ b/lib/widgets/alerts/alert.dart @@ -3,15 +3,15 @@ import 'package:Okuna/provider.dart'; import 'package:flutter/material.dart'; class OBAlert extends StatefulWidget { - final Widget child; - final double height; - final double width; - final EdgeInsets padding; - final BorderRadiusGeometry borderRadius; - final Color color; + final Widget? child; + final double? height; + final double? width; + final EdgeInsets? padding; + final BorderRadiusGeometry? borderRadius; + final Color? color; const OBAlert( - {Key key, + {Key? key, this.child, this.height, this.width, @@ -27,7 +27,7 @@ class OBAlert extends StatefulWidget { } class OBAlertState extends State { - bool isVisible; + late bool isVisible; @override void initState() { @@ -47,7 +47,7 @@ class OBAlertState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var theme = snapshot.data; var primaryColor = - themeValueParserService.parseColor(theme.primaryColor); + themeValueParserService.parseColor(theme!.primaryColor); final bool isDarkPrimaryColor = primaryColor.computeLuminance() < 0.179; diff --git a/lib/widgets/alerts/button_alert.dart b/lib/widgets/alerts/button_alert.dart index 5934db099..1244a93a8 100644 --- a/lib/widgets/alerts/button_alert.dart +++ b/lib/widgets/alerts/button_alert.dart @@ -8,16 +8,16 @@ class OBButtonAlert extends StatelessWidget { final VoidCallback onPressed; final bool isLoading; final String text; - final OBIconData buttonIcon; + final OBIconData? buttonIcon; final String buttonText; - final String assetImage; + final String? assetImage; const OBButtonAlert( - {@required this.onPressed, + {required this.onPressed, this.isLoading = false, - @required this.text, + required this.text, this.buttonIcon, - @required this.buttonText, + required this.buttonText, this.assetImage}); @override @@ -31,7 +31,7 @@ class OBButtonAlert extends StatelessWidget { padding: EdgeInsets.only(right: 30, left: 10, top: 10, bottom: 10), child: Image.asset( - assetImage, + assetImage!, height: 80, ), ) @@ -57,7 +57,7 @@ class OBButtonAlert extends StatelessWidget { OBButton( icon: buttonIcon != null ? OBIcon( - buttonIcon, + buttonIcon!, size: OBIconSize.small, ) : null, diff --git a/lib/widgets/avatars/avatar.dart b/lib/widgets/avatars/avatar.dart index a45107b0a..60e28695b 100644 --- a/lib/widgets/avatars/avatar.dart +++ b/lib/widgets/avatars/avatar.dart @@ -8,14 +8,14 @@ enum OBAvatarSize { extraSmall, small, medium, large, extraLarge } enum OBAvatarType { user, community } class OBAvatar extends StatelessWidget { - final String avatarUrl; - final File avatarFile; - final OBAvatarSize size; - final VoidCallback onPressed; - final double borderWidth; + final String? avatarUrl; + final File? avatarFile; + final OBAvatarSize? size; + final VoidCallback? onPressed; + final double? borderWidth; final bool isZoomable; - final double borderRadius; - final double customSize; + final double? borderRadius; + final double? customSize; static const double AVATAR_SIZE_EXTRA_SMALL = 20.0; static const double AVATAR_SIZE_SMALL = 30.0; @@ -27,7 +27,7 @@ class OBAvatar extends StatelessWidget { static const double avatarBorderRadius = 10.0; static double getAvatarSize(OBAvatarSize size) { - double avatarSize; + late double avatarSize; switch (size) { case OBAvatarSize.extraSmall: @@ -73,14 +73,14 @@ class OBAvatar extends StatelessWidget { height: avatarSize, width: avatarSize, placeholder: AssetImage(DEFAULT_AVATAR_ASSET), - image: FileImage(avatarFile), + image: FileImage(avatarFile!), ); } else if (avatarUrl != null) { finalAvatarImage = Image( height: avatarSize, width: avatarSize, fit: BoxFit.cover, - image: AdvancedNetworkImage(avatarUrl, + image: AdvancedNetworkImage(avatarUrl!, useDiskCache: true, fallbackAssetImage: DEFAULT_AVATAR_ASSET, retryLimit: 0)); @@ -92,7 +92,7 @@ class OBAvatar extends StatelessWidget { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.dialogService.showZoomablePhotoBoxView( - imageUrl: avatarUrl, context: context); + imageUrl: avatarUrl!, context: context); }, ); } diff --git a/lib/widgets/avatars/community_avatar.dart b/lib/widgets/avatars/community_avatar.dart index 8f94da3b3..69b3655a3 100644 --- a/lib/widgets/avatars/community_avatar.dart +++ b/lib/widgets/avatars/community_avatar.dart @@ -12,14 +12,14 @@ import 'package:tinycolor/tinycolor.dart'; class OBCommunityAvatar extends StatelessWidget { final Community community; final OBAvatarSize size; - final VoidCallback onPressed; + final VoidCallback? onPressed; final bool isZoomable; - final double borderRadius; - final double customSize; + final double? borderRadius; + final double? customSize; const OBCommunityAvatar( - {Key key, - @required this.community, + {Key? key, + required this.community, this.size = OBAvatarSize.small, this.isZoomable = false, this.borderRadius, @@ -33,14 +33,14 @@ class OBCommunityAvatar extends StatelessWidget { stream: community.updateSubject, initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community community = snapshot.data; + Community community = snapshot.data!; bool communityHasAvatar = community.hasAvatar(); Widget avatar; if (communityHasAvatar) { avatar = OBAvatar( - avatarUrl: community?.avatar, + avatarUrl: community.avatar, size: size, onPressed: onPressed, isZoomable: isZoomable, @@ -79,7 +79,7 @@ class OBCommunityAvatar extends StatelessWidget { } avatar = OBLetterAvatar( - letter: community.name[0], + letter: community.name![0], color: communityColor, size: size, onPressed: onPressed, diff --git a/lib/widgets/avatars/hashtag_avatar.dart b/lib/widgets/avatars/hashtag_avatar.dart index 97fd73581..ffb74b547 100644 --- a/lib/widgets/avatars/hashtag_avatar.dart +++ b/lib/widgets/avatars/hashtag_avatar.dart @@ -12,14 +12,14 @@ import 'package:tinycolor/tinycolor.dart'; class OBHashtagAvatar extends StatelessWidget { final Hashtag hashtag; final OBAvatarSize size; - final VoidCallback onPressed; + final VoidCallback? onPressed; final bool isZoomable; - final double borderRadius; - final double customSize; + final double? borderRadius; + final double? customSize; const OBHashtagAvatar( - {Key key, - @required this.hashtag, + {Key? key, + required this.hashtag, this.size = OBAvatarSize.small, this.isZoomable = false, this.borderRadius, @@ -33,21 +33,21 @@ class OBHashtagAvatar extends StatelessWidget { stream: hashtag.updateSubject, initialData: hashtag, builder: (BuildContext context, AsyncSnapshot snapshot) { - Hashtag hashtag = snapshot.data; + Hashtag hashtag = snapshot.data!; bool hashtagHasImage = hashtag.hasImage(); Widget avatar; if (hashtagHasImage) { avatar = OBAvatar( - avatarUrl: hashtag?.image, + avatarUrl: hashtag.image, size: size, onPressed: onPressed, isZoomable: isZoomable, borderRadius: borderRadius, customSize: customSize); } else { - String hashtagHexColor = hashtag.color; + String hashtagHexColor = hashtag.color!; OpenbookProviderState openbookProviderState = OpenbookProvider.of(context); diff --git a/lib/widgets/avatars/letter_avatar.dart b/lib/widgets/avatars/letter_avatar.dart index d106038a6..3a2666235 100644 --- a/lib/widgets/avatars/letter_avatar.dart +++ b/lib/widgets/avatars/letter_avatar.dart @@ -7,11 +7,11 @@ export 'package:Okuna/widgets/avatars/avatar.dart'; class OBLetterAvatar extends StatelessWidget { final OBAvatarSize size; final Color color; - final Color labelColor; + final Color? labelColor; final String letter; - final VoidCallback onPressed; - final double borderRadius; - final double customSize; + final VoidCallback? onPressed; + final double? borderRadius; + final double? customSize; static const double fontSizeExtraSmall = 10.0; static const double fontSizeSmall = 14.0; @@ -20,11 +20,11 @@ class OBLetterAvatar extends StatelessWidget { static const double fontSizeExtraLarge = 60.0; const OBLetterAvatar( - {Key key, + {Key? key, this.size = OBAvatarSize.medium, - @required this.color, + required this.color, this.labelColor, - @required this.letter, + required this.letter, this.onPressed, this.borderRadius, this.customSize}) @@ -37,7 +37,7 @@ class OBLetterAvatar extends StatelessWidget { double avatarSize = customSize ?? OBAvatar.getAvatarSize(size); double fontSize = getAvatarFontSize(size); Color finalLabelColor = labelColor != null - ? labelColor + ? labelColor! : (themeValueParserService.isDarkColor(color) ? Colors.white : Colors.black); diff --git a/lib/widgets/avatars/logged_in_user_avatar.dart b/lib/widgets/avatars/logged_in_user_avatar.dart index aa3e561d0..dcbad1352 100644 --- a/lib/widgets/avatars/logged_in_user_avatar.dart +++ b/lib/widgets/avatars/logged_in_user_avatar.dart @@ -7,8 +7,8 @@ import 'package:Okuna/widgets/avatars/avatar.dart'; import 'package:flutter/material.dart'; class OBLoggedInUserAvatar extends StatefulWidget { - final OBAvatarSize size; - final VoidCallback onPressed; + final OBAvatarSize? size; + final VoidCallback? onPressed; const OBLoggedInUserAvatar({this.size, this.onPressed}); @@ -21,11 +21,11 @@ class OBLoggedInUserAvatar extends StatefulWidget { /// Like the UserAvatar widget but displays the avatar of /// the logged in user. class OBLoggedInUserAvatarState extends State { - bool _needsBootstrap; - UserService _userService; - StreamSubscription _onLoggedInUserChangeSubscription; - StreamSubscription _onUserUpdateSubscription; - String _avatarUrl; + late bool _needsBootstrap; + late UserService _userService; + StreamSubscription? _onLoggedInUserChangeSubscription; + StreamSubscription? _onUserUpdateSubscription; + String? _avatarUrl; @override void initState() { @@ -37,8 +37,8 @@ class OBLoggedInUserAvatarState extends State { void dispose() { super.dispose(); if (_onLoggedInUserChangeSubscription != null) - _onLoggedInUserChangeSubscription.cancel(); - if (_onUserUpdateSubscription != null) _onUserUpdateSubscription.cancel(); + _onLoggedInUserChangeSubscription!.cancel(); + if (_onUserUpdateSubscription != null) _onUserUpdateSubscription!.cancel(); } @override @@ -52,7 +52,7 @@ class OBLoggedInUserAvatarState extends State { return OBAvatar( avatarUrl: _avatarUrl, - size: widget.size, + size: widget.size!, onPressed: widget.onPressed, ); } @@ -62,15 +62,15 @@ class OBLoggedInUserAvatarState extends State { _userService.loggedInUserChange.listen(_onLoggedInUserChange); } - void _onLoggedInUserChange(User user) { + void _onLoggedInUserChange(User? user) { if (user == null) return; - if (_onUserUpdateSubscription != null) _onUserUpdateSubscription.cancel(); + if (_onUserUpdateSubscription != null) _onUserUpdateSubscription!.cancel(); _onUserUpdateSubscription = user.updateSubject.listen(_onLoggedInUserUpdate); } void _onLoggedInUserUpdate(User user) { - _setAvatarUrl(user.getProfileAvatar()); + _setAvatarUrl(user.getProfileAvatar()!); } void _setAvatarUrl(String avatarUrl) { diff --git a/lib/widgets/badges/badge.dart b/lib/widgets/badges/badge.dart index 2a7e67ed4..95cd08a40 100644 --- a/lib/widgets/badges/badge.dart +++ b/lib/widgets/badges/badge.dart @@ -4,10 +4,10 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBBadge extends StatelessWidget { - final int count; - final double size; + final int? count; + final double? size; - const OBBadge({Key key, this.count, this.size=19}) : super(key: key); + const OBBadge({Key? key, this.count, this.size=19}) : super(key: key); @override Widget build(BuildContext context) { @@ -23,7 +23,7 @@ class OBBadge extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { var theme = snapshot.data; var primaryAccentColor = - themeValueParserService.parseGradient(theme.primaryAccentColor); + themeValueParserService.parseGradient(theme!.primaryAccentColor); return Container( width: size, height: size, @@ -35,7 +35,7 @@ class OBBadge extends StatelessWidget { count.toString(), style: TextStyle( color: Colors.white, - fontSize: count < 10 ? 12 : 10, + fontSize: count! < 10 ? 12 : 10, fontWeight: FontWeight.bold), ) : const SizedBox() ), diff --git a/lib/widgets/buttons/accent_button.dart b/lib/widgets/buttons/accent_button.dart index edb02af4c..1c3e44181 100644 --- a/lib/widgets/buttons/accent_button.dart +++ b/lib/widgets/buttons/accent_button.dart @@ -3,18 +3,18 @@ import 'package:flutter/material.dart'; class OBAccentButton extends StatelessWidget { final Widget child; - final Widget icon; + final Widget? icon; final VoidCallback onPressed; final bool isDisabled; final bool isLoading; final Color textColor; final OBButtonSize size; - final double minWidth; - final EdgeInsets padding; + final double? minWidth; + final EdgeInsets? padding; const OBAccentButton( - {@required this.child, - @required this.onPressed, + {required this.child, + required this.onPressed, this.size = OBButtonSize.medium, this.textColor = Colors.white, this.icon, diff --git a/lib/widgets/buttons/actions/approve_follow_request_button.dart b/lib/widgets/buttons/actions/approve_follow_request_button.dart index ae2796e68..265be1c89 100644 --- a/lib/widgets/buttons/actions/approve_follow_request_button.dart +++ b/lib/widgets/buttons/actions/approve_follow_request_button.dart @@ -12,11 +12,11 @@ import 'package:intl/intl.dart'; class OBApproveFollowRequestButton extends StatefulWidget { final User user; - final VoidCallback onFollowRequestApproved; + final VoidCallback? onFollowRequestApproved; final OBButtonSize size; const OBApproveFollowRequestButton(this.user, - {Key key, this.onFollowRequestApproved, this.size = OBButtonSize.medium}) + {Key? key, this.onFollowRequestApproved, this.size = OBButtonSize.medium}) : super(key: key); @override @@ -26,13 +26,13 @@ class OBApproveFollowRequestButton extends StatefulWidget { } class OBApproveFollowRequestButtonState extends State { - ToastService _toastService; - LocalizationService _localizationService; - UserService _userService; - bool _needsBootstrap; + late ToastService _toastService; + late LocalizationService _localizationService; + late UserService _userService; + late bool _needsBootstrap; - bool _isFollowRequestActionInProgress; - CancelableOperation _followRequestActionOperation; + late bool _isFollowRequestActionInProgress; + CancelableOperation? _followRequestActionOperation; @override void initState() { @@ -55,7 +55,7 @@ class OBApproveFollowRequestButtonState extends State { - UserService _userService; - ToastService _toastService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late bool _requestInProgress; @override void initState() { @@ -41,7 +41,7 @@ class OBBlockButtonState extends State { stream: widget.user.updateSubject, initialData: widget.user, builder: (BuildContext context, AsyncSnapshot snapshot) { - var user = snapshot.data; + var user = snapshot.data!; bool isBlocked = user.isBlocked ?? false; return isBlocked ? _buildUnblockButton() : _buildBlockButton(); @@ -100,8 +100,8 @@ class OBBlockButtonState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/widgets/buttons/actions/confirm_connection_button.dart b/lib/widgets/buttons/actions/confirm_connection_button.dart index f61a0ee62..13a734f2c 100644 --- a/lib/widgets/buttons/actions/confirm_connection_button.dart +++ b/lib/widgets/buttons/actions/confirm_connection_button.dart @@ -21,11 +21,11 @@ class OBConfirmConnectionButton extends StatefulWidget { } class OBConfirmConnectionButtonState extends State { - UserService _userService; - ToastService _toastService; - BottomSheetService _bottomSheetService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late BottomSheetService _bottomSheetService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -47,10 +47,10 @@ class OBConfirmConnectionButtonState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var user = snapshot.data; - if (user?.isPendingConnectionConfirmation == null || !user.isConnected) + if (user?.isPendingConnectionConfirmation == null || user?.isConnected == false) return const SizedBox(); - return user.isPendingConnectionConfirmation + return user?.isPendingConnectionConfirmation == true ? _buildConfirmConnectionButton() : _buildDisconnectButton(); }, @@ -94,9 +94,9 @@ class OBConfirmConnectionButtonState extends State { _setRequestInProgress(true); try { await _userService.confirmConnectionWithUserWithUsername( - widget.user.username, + widget.user.username!, circles: circles); - if (!widget.user.isFollowing) widget.user.incrementFollowersCount(); + if (!widget.user.isFollowing!) widget.user.incrementFollowersCount(); _toastService.success(message: 'Connection confirmed', context: context); } catch (error) { _onError(error); @@ -110,8 +110,8 @@ class OBConfirmConnectionButtonState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; @@ -122,7 +122,7 @@ class OBConfirmConnectionButtonState extends State { if (_requestInProgress) return; _setRequestInProgress(true); try { - await _userService.disconnectFromUserWithUsername(widget.user.username); + await _userService.disconnectFromUserWithUsername(widget.user.username!); widget.user.decrementFollowersCount(); _toastService.success( message: 'Disconnected successfully', context: context); diff --git a/lib/widgets/buttons/actions/deny_connection_button.dart b/lib/widgets/buttons/actions/deny_connection_button.dart index 9c7742016..310d8e9a8 100644 --- a/lib/widgets/buttons/actions/deny_connection_button.dart +++ b/lib/widgets/buttons/actions/deny_connection_button.dart @@ -19,10 +19,10 @@ class OBDenyConnectionButton extends StatefulWidget { } class OBDenyConnectionButtonState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -44,8 +44,8 @@ class OBDenyConnectionButtonState extends State { var user = snapshot.data; if (user?.isPendingConnectionConfirmation == null || - !user.isConnected || - !user.isPendingConnectionConfirmation) return const SizedBox(); + user?.isConnected == false || + user?.isPendingConnectionConfirmation == false) return const SizedBox(); return _buildDenyConnectionButton(); }, @@ -68,7 +68,7 @@ class OBDenyConnectionButtonState extends State { if (_requestInProgress) return; _setRequestInProgress(true); try { - await _userService.disconnectFromUserWithUsername(widget.user.username); + await _userService.disconnectFromUserWithUsername(widget.user.username!); widget.user.decrementFollowersCount(); _toastService.success( message: 'Disconnected successfully', context: context); @@ -84,8 +84,8 @@ class OBDenyConnectionButtonState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown service', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/widgets/buttons/actions/follow_button.dart b/lib/widgets/buttons/actions/follow_button.dart index 8780e98fe..276db4a2e 100644 --- a/lib/widgets/buttons/actions/follow_button.dart +++ b/lib/widgets/buttons/actions/follow_button.dart @@ -24,10 +24,10 @@ class OBFollowButton extends StatefulWidget { } class OBFollowButtonState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -50,9 +50,9 @@ class OBFollowButtonState extends State { if (user?.isFollowing == null) return const SizedBox(); - return user.isFollowing + return user!.isFollowing! ? _buildUnfollowButton() - : user.visibility != UserVisibility.private || user.isFollowing + : user.visibility != UserVisibility.private || user.isFollowing! ? _buildFollowButton() : _buildRequestToFollowButton(); }, @@ -63,7 +63,7 @@ class OBFollowButtonState extends State { if(widget.user.isFollowRequested == null) return const SizedBox(); final followButtonText = - widget.user.isFollowRequested + widget.user.isFollowRequested == true ? _localizationService.user__follow_button_requested_to_follow_text : getFollowButtonText(); @@ -74,7 +74,7 @@ class OBFollowButtonState extends State { style: TextStyle(fontWeight: FontWeight.bold), ), isLoading: _requestInProgress, - onPressed: widget.user.isFollowRequested ? _cancelRequestToFollowUser : _requestToFollowUser, + onPressed: widget.user.isFollowRequested == true ? _cancelRequestToFollowUser : _requestToFollowUser, ); } @@ -108,7 +108,7 @@ class OBFollowButtonState extends State { void _followUser() async { _setRequestInProgress(true); try { - await _userService.followUserWithUsername(widget.user.username); + await _userService.followUserWithUsername(widget.user.username!); widget.user.incrementFollowersCount(); } catch (error) { _onError(error); @@ -145,7 +145,7 @@ class OBFollowButtonState extends State { void _unFollowUser() async { _setRequestInProgress(true); try { - await _userService.unFollowUserWithUsername(widget.user.username); + await _userService.unFollowUserWithUsername(widget.user.username!); widget.user.decrementFollowersCount(); } catch (error) { _onError(error); @@ -155,7 +155,7 @@ class OBFollowButtonState extends State { } String getFollowButtonText(){ - return widget.user.isFollowed != null && widget.user.isFollowed + return widget.user.isFollowed != null && widget.user.isFollowed! ? _localizationService.user__follow_button_follow_back_text : _localizationService.user__follow_button_follow_text; } @@ -165,8 +165,8 @@ class OBFollowButtonState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/widgets/buttons/actions/invite_user_to_community.dart b/lib/widgets/buttons/actions/invite_user_to_community.dart index 4099b0c3f..852537928 100644 --- a/lib/widgets/buttons/actions/invite_user_to_community.dart +++ b/lib/widgets/buttons/actions/invite_user_to_community.dart @@ -13,7 +13,7 @@ class OBInviteUserToCommunityButton extends StatefulWidget { final Community community; OBInviteUserToCommunityButton( - {@required this.user, @required this.community}); + {required this.user, required this.community}); @override OBInviteUserToCommunityButtonState createState() { @@ -23,10 +23,10 @@ class OBInviteUserToCommunityButton extends StatefulWidget { class OBInviteUserToCommunityButtonState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -41,21 +41,19 @@ class OBInviteUserToCommunityButtonState _toastService = openbookProvider.toastService; _localizationService = openbookProvider.localizationService; - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; return StreamBuilder( stream: loggedInUser.updateSubject, initialData: loggedInUser, builder: (BuildContext context, AsyncSnapshot loggedInUserSnapshot) { - User latestLoggedInUser = loggedInUserSnapshot.data; - return StreamBuilder( stream: widget.user.updateSubject, initialData: widget.user, builder: (BuildContext context, AsyncSnapshot latestUserSnapshot) { - User latestUser = latestUserSnapshot.data; + User? latestUser = latestUserSnapshot.data; if (latestUser == null) return const SizedBox(); bool isCommunityMember = @@ -136,8 +134,8 @@ class OBInviteUserToCommunityButtonState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error(message: _localizationService.trans('error__unknown_error'), context: context); throw error; diff --git a/lib/widgets/buttons/actions/join_community_button.dart b/lib/widgets/buttons/actions/join_community_button.dart index db5cb9a21..fc7743f09 100644 --- a/lib/widgets/buttons/actions/join_community_button.dart +++ b/lib/widgets/buttons/actions/join_community_button.dart @@ -22,10 +22,10 @@ class OBJoinCommunityButton extends StatefulWidget { } class OBJoinCommunityButtonState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -44,7 +44,7 @@ class OBJoinCommunityButtonState extends State { stream: widget.community.updateSubject, initialData: widget.community, builder: (BuildContext context, AsyncSnapshot snapshot) { - var community = snapshot.data; + var community = snapshot.data!; bool isCreator = community.isCreator ?? true; @@ -52,9 +52,9 @@ class OBJoinCommunityButtonState extends State { bool isInvited = community.isInvited ?? false; - User loggedInUser = _userService.getLoggedInUser(); + User loggedInUser = _userService.getLoggedInUser()!; - bool isMember = community.isMember(loggedInUser) ?? false; + bool isMember = community.isMember(loggedInUser); if (community.type == CommunityType.private && !isMember && !isInvited) return SizedBox(); @@ -108,8 +108,8 @@ class OBJoinCommunityButtonState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/widgets/buttons/actions/reject_follow_request_button.dart b/lib/widgets/buttons/actions/reject_follow_request_button.dart index d8f3a5ea2..8759e42d5 100644 --- a/lib/widgets/buttons/actions/reject_follow_request_button.dart +++ b/lib/widgets/buttons/actions/reject_follow_request_button.dart @@ -11,11 +11,11 @@ import 'package:intl/intl.dart'; class OBRejectFollowRequestButton extends StatefulWidget { final User user; - final VoidCallback onFollowRequestRejected; + final VoidCallback? onFollowRequestRejected; final OBButtonSize size; const OBRejectFollowRequestButton(this.user, - {Key key, this.onFollowRequestRejected, this.size = OBButtonSize.medium}) + {Key? key, this.onFollowRequestRejected, this.size = OBButtonSize.medium}) : super(key: key); @override @@ -25,13 +25,13 @@ class OBRejectFollowRequestButton extends StatefulWidget { } class OBRejectFollowRequestButtonState extends State { - ToastService _toastService; - LocalizationService _localizationService; - UserService _userService; - bool _needsBootstrap; + late ToastService _toastService; + late LocalizationService _localizationService; + late UserService _userService; + late bool _needsBootstrap; - bool _isFollowRequestActionInProgress; - CancelableOperation _followRequestActionOperation; + late bool _isFollowRequestActionInProgress; + CancelableOperation? _followRequestActionOperation; @override void initState() { @@ -54,7 +54,7 @@ class OBRejectFollowRequestButtonState extends State boxShadow; - final TextStyle textStyle; - final Color color; - final Color textColor; + final ShapeBorder? shape; + final double? minHeight; + final List? boxShadow; + final TextStyle? textStyle; + final Color? color; + final Color? textColor; const OBButton( - {@required this.child, - @required this.onPressed, + {required this.child, + required this.onPressed, this.minHeight, this.minWidth, this.type = OBButtonType.primary, @@ -45,14 +45,14 @@ class OBButton extends StatelessWidget { var themeValueParser = provider.themeValueParserService; return color != null - ? _buildButton(color: color, textColor: textColor) + ? _buildButton(color: color!, textColor: textColor!) : StreamBuilder( stream: themeService.themeChange, initialData: themeService.getActiveTheme(), builder: (BuildContext context, AsyncSnapshot snapshot) { var theme = snapshot.data; Color buttonTextColor = _getButtonTextColorForType(type, - themeValueParser: themeValueParser, theme: theme); + themeValueParser: themeValueParser, theme: theme!); Gradient gradient = _getButtonGradientForType(type, themeValueParser: themeValueParser, theme: theme); @@ -62,9 +62,9 @@ class OBButton extends StatelessWidget { } Widget _buildButton( - {Gradient gradient, Color color, @required Color textColor}) { - EdgeInsets buttonPadding = _getButtonPaddingForSize(size); - double buttonMinWidth = minWidth ?? _getButtonMinWidthForSize(size); + {Gradient? gradient, Color? color, required Color textColor}) { + EdgeInsets buttonPadding = _getButtonPaddingForSize(size!); + double buttonMinWidth = minWidth ?? _getButtonMinWidthForSize(size!); double buttonMinHeight = minHeight ?? 20; var finalOnPressed = isLoading || isDisabled ? () {} : onPressed; var finalOnLongPressed = isLoading || isDisabled ? () {} : onLongPressed; @@ -76,7 +76,7 @@ class OBButton extends StatelessWidget { if (icon != null && !isLoading) { buttonChild = Row( children: [ - icon, + icon!, const SizedBox( width: 5, ), @@ -86,7 +86,7 @@ class OBButton extends StatelessWidget { } TextStyle defaultTextStyle = - _getButtonTextStyleForSize(size: size, color: textColor); + _getButtonTextStyleForSize(size: size!, color: textColor); if (textStyle != null) { defaultTextStyle = defaultTextStyle.merge(textStyle); @@ -128,9 +128,9 @@ class OBButton extends StatelessWidget { } Gradient _getButtonGradientForType(OBButtonType type, - {@required ThemeValueParserService themeValueParser, - @required OBTheme theme}) { - Gradient buttonGradient; + {required ThemeValueParserService themeValueParser, + required OBTheme theme}) { + late Gradient buttonGradient; switch (type) { case OBButtonType.danger: @@ -160,9 +160,9 @@ class OBButton extends StatelessWidget { } Color _getButtonTextColorForType(OBButtonType type, - {@required ThemeValueParserService themeValueParser, - @required OBTheme theme}) { - Color buttonTextColor; + {required ThemeValueParserService themeValueParser, + required OBTheme theme}) { + late Color buttonTextColor; switch (type) { case OBButtonType.danger: @@ -184,9 +184,9 @@ class OBButton extends StatelessWidget { } EdgeInsets _getButtonPaddingForSize(OBButtonSize type) { - if (padding != null) return padding; + if (padding != null) return padding!; - EdgeInsets buttonPadding; + late EdgeInsets buttonPadding; switch (size) { case OBButtonSize.large: @@ -205,8 +205,8 @@ class OBButton extends StatelessWidget { } TextStyle _getButtonTextStyleForSize( - {OBButtonSize size, @required Color color}) { - TextStyle textStyle; + {OBButtonSize? size, required Color color}) { + late TextStyle textStyle; switch (size) { case OBButtonSize.large: @@ -223,9 +223,9 @@ class OBButton extends StatelessWidget { } double _getButtonMinWidthForSize(OBButtonSize type) { - if (minWidth != null) return minWidth; + if (minWidth != null) return minWidth!; - double buttonMinWidth; + late double buttonMinWidth; switch (size) { case OBButtonSize.large: diff --git a/lib/widgets/buttons/community_button.dart b/lib/widgets/buttons/community_button.dart index 770ede6d1..92ba887ad 100644 --- a/lib/widgets/buttons/community_button.dart +++ b/lib/widgets/buttons/community_button.dart @@ -16,15 +16,15 @@ class OBCommunityButton extends StatelessWidget { static const borderRadius = 30.0; const OBCommunityButton( - {Key key, + {Key? key, this.isLoading = false, - @required this.community, - @required this.text, - @required this.onPressed}) + required this.community, + required this.text, + required this.onPressed}) : super(key: key); Widget build(BuildContext context) { - String communityHexColor = community.color; + String communityHexColor = community.color!; OpenbookProviderState openbookProviderState = OpenbookProvider.of(context); ThemeValueParserService themeValueParserService = openbookProviderState.themeValueParserService; diff --git a/lib/widgets/buttons/community_new_post_button.dart b/lib/widgets/buttons/community_new_post_button.dart index c0bd1865a..e0405bda7 100644 --- a/lib/widgets/buttons/community_new_post_button.dart +++ b/lib/widgets/buttons/community_new_post_button.dart @@ -16,11 +16,11 @@ class OBCommunityNewPostButton extends StatelessWidget { final bool isLoading; final Color textColor; final OBButtonSize size; - final double minWidth; - final EdgeInsets padding; + final double? minWidth; + final EdgeInsets? padding; final OBButtonType type; final Community community; - final ValueChanged onWantsToUploadNewPostData; + final ValueChanged? onWantsToUploadNewPostData; const OBCommunityNewPostButton({ this.type = OBButtonType.primary, @@ -30,7 +30,7 @@ class OBCommunityNewPostButton extends StatelessWidget { this.isLoading = false, this.padding, this.minWidth, - this.community, + required this.community, this.onWantsToUploadNewPostData, }); @@ -41,9 +41,9 @@ class OBCommunityNewPostButton extends StatelessWidget { stream: community.updateSubject, initialData: community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community community = snapshot.data; + Community community = snapshot.data!; - String communityHexColor = community.color; + String communityHexColor = community.color!; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); ThemeValueParserService themeValueParserService = openbookProvider.themeValueParserService; @@ -80,12 +80,12 @@ class OBCommunityNewPostButton extends StatelessWidget { onPressed: () async { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - OBNewPostData createPostData = await openbookProvider + OBNewPostData? createPostData = await openbookProvider .modalService .openCreatePost(context: context, community: community); if (createPostData != null && onWantsToUploadNewPostData != null) - onWantsToUploadNewPostData(createPostData); + onWantsToUploadNewPostData!(createPostData); }, child: OBIcon(OBIcons.createPost, size: OBIconSize.large, color: textColor))); diff --git a/lib/widgets/buttons/danger_button.dart b/lib/widgets/buttons/danger_button.dart index cbdbfb375..9dc47011d 100644 --- a/lib/widgets/buttons/danger_button.dart +++ b/lib/widgets/buttons/danger_button.dart @@ -3,18 +3,18 @@ import 'package:flutter/material.dart'; class OBDangerButton extends StatelessWidget { final Widget child; - final Widget icon; + final Widget? icon; final VoidCallback onPressed; final bool isDisabled; final bool isLoading; final Color textColor; final OBButtonSize size; - final double minWidth; - final EdgeInsets padding; + final double? minWidth; + final EdgeInsets? padding; const OBDangerButton( - {@required this.child, - @required this.onPressed, + {required this.child, + required this.onPressed, this.size = OBButtonSize.medium, this.textColor = Colors.white, this.icon, diff --git a/lib/widgets/buttons/floating_action_button.dart b/lib/widgets/buttons/floating_action_button.dart index 41e4c1c28..2ecaebdbb 100644 --- a/lib/widgets/buttons/floating_action_button.dart +++ b/lib/widgets/buttons/floating_action_button.dart @@ -3,20 +3,20 @@ import 'package:flutter/material.dart'; class OBFloatingActionButton extends StatelessWidget { final Widget child; - final Widget icon; + final Widget? icon; final VoidCallback onPressed; final bool isDisabled; final bool isLoading; final Color textColor; final OBButtonSize size; - final double minWidth; - final EdgeInsets padding; - final OBButtonType type; - final Color color; + final double? minWidth; + final EdgeInsets? padding; + final OBButtonType? type; + final Color? color; const OBFloatingActionButton( - {@required this.child, - @required this.onPressed, + {required this.child, + required this.onPressed, this.type, this.size = OBButtonSize.medium, this.textColor = Colors.white, @@ -42,7 +42,7 @@ class OBFloatingActionButton extends StatelessWidget { icon: icon, onPressed: onPressed, size: size, - type: type, + type: type ?? OBButtonType.primary, isDisabled: isDisabled, isLoading: isLoading, padding: EdgeInsets.all(0), diff --git a/lib/widgets/buttons/pill_button.dart b/lib/widgets/buttons/pill_button.dart index bc9c5bbf0..656d0086d 100644 --- a/lib/widgets/buttons/pill_button.dart +++ b/lib/widgets/buttons/pill_button.dart @@ -3,15 +3,15 @@ import 'package:flutter/material.dart'; class OBPillButton extends StatelessWidget { final String text; final Widget icon; - final Color color; - final Color textColor; + final Color? color; + final Color? textColor; final VoidCallback onPressed; const OBPillButton( - {@required this.text, - @required this.icon, - @required this.onPressed, + {required this.text, + required this.icon, + required this.onPressed, this.color, this.textColor}); diff --git a/lib/widgets/buttons/secondary_button.dart b/lib/widgets/buttons/secondary_button.dart index f5947bfe5..dfbb8ee30 100644 --- a/lib/widgets/buttons/secondary_button.dart +++ b/lib/widgets/buttons/secondary_button.dart @@ -18,8 +18,8 @@ class OBSecondaryButton extends StatelessWidget { final bool isFullWidth; const OBSecondaryButton( - {@required this.child, - @required this.onPressed, + {required this.child, + required this.onPressed, this.isLarge = false, this.isFullWidth = false}); diff --git a/lib/widgets/buttons/see_all_button.dart b/lib/widgets/buttons/see_all_button.dart index 55bd152a3..7c649f3fe 100644 --- a/lib/widgets/buttons/see_all_button.dart +++ b/lib/widgets/buttons/see_all_button.dart @@ -12,11 +12,11 @@ class OBSeeAllButton extends StatelessWidget { final int resourcesCount; const OBSeeAllButton( - {Key key, - @required this.onPressed, - @required this.resourceName, - @required this.previewedResourcesCount, - @required this.resourcesCount}) + {Key? key, + required this.onPressed, + required this.resourceName, + required this.previewedResourcesCount, + required this.resourcesCount}) : super(key: key); @override diff --git a/lib/widgets/buttons/stream_load_more_button.dart b/lib/widgets/buttons/stream_load_more_button.dart index dd1572309..8c3c4420a 100644 --- a/lib/widgets/buttons/stream_load_more_button.dart +++ b/lib/widgets/buttons/stream_load_more_button.dart @@ -5,10 +5,10 @@ import 'package:Okuna/widgets/theming/text.dart'; import 'package:flutter/material.dart'; class OBStreamLoadMoreButton extends StatelessWidget { - final VoidCallback onPressed; - final String text; + final VoidCallback? onPressed; + final String? text; - const OBStreamLoadMoreButton({Key key, this.onPressed, this.text}) + const OBStreamLoadMoreButton({Key? key, this.onPressed, this.text}) : super(key: key); @override diff --git a/lib/widgets/buttons/success_button.dart b/lib/widgets/buttons/success_button.dart index 8df0ba8c1..99d6641a8 100644 --- a/lib/widgets/buttons/success_button.dart +++ b/lib/widgets/buttons/success_button.dart @@ -3,17 +3,17 @@ import 'package:flutter/material.dart'; class OBSuccessButton extends StatelessWidget { final Widget child; - final Widget icon; + final Widget? icon; final VoidCallback onPressed; final bool isDisabled; final bool isLoading; final OBButtonSize size; - final double minWidth; - final EdgeInsets padding; + final double? minWidth; + final EdgeInsets? padding; const OBSuccessButton( - {@required this.child, - @required this.onPressed, + {required this.child, + required this.onPressed, this.icon, this.size = OBButtonSize.medium, this.isDisabled = false, diff --git a/lib/widgets/categories_picker.dart b/lib/widgets/categories_picker.dart index 4a4ecb1b0..e3a33b827 100644 --- a/lib/widgets/categories_picker.dart +++ b/lib/widgets/categories_picker.dart @@ -10,15 +10,15 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBCategoriesPicker extends StatefulWidget { - final List initialCategories; + final List? initialCategories; final ValueChanged> onChanged; final maxSelections; const OBCategoriesPicker( - {Key key, + {Key? key, this.initialCategories, this.maxSelections, - @required this.onChanged}) + required this.onChanged}) : super(key: key); @override @@ -28,16 +28,16 @@ class OBCategoriesPicker extends StatefulWidget { } class OBCategoriesPickerState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _hasError; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _hasError; - bool _needsBootstrap; - bool _requestInProgress; + late bool _needsBootstrap; + late bool _requestInProgress; - List _categories; - List _pickedCategories; + late List _categories; + late List _pickedCategories; @override void initState() { @@ -45,7 +45,7 @@ class OBCategoriesPickerState extends State { _categories = []; _pickedCategories = widget.initialCategories == null ? [] - : widget.initialCategories.toList(); + : widget.initialCategories!.toList(); _needsBootstrap = true; _requestInProgress = true; _hasError = true; @@ -131,9 +131,9 @@ class OBCategoriesPickerState extends State { }); } - void _setCategories(List categories) { + void _setCategories(List? categories) { setState(() { - _categories = categories; + _categories = categories ?? []; }); } @@ -154,8 +154,8 @@ class OBCategoriesPickerState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/widgets/category_badge.dart b/lib/widgets/category_badge.dart index bf18aa862..77acde48a 100644 --- a/lib/widgets/category_badge.dart +++ b/lib/widgets/category_badge.dart @@ -9,11 +9,11 @@ class OBCategoryBadge extends StatelessWidget { final Category category; final OBCategoryBadgeSize size; final bool isEnabled; - final ValueChanged onPressed; + final ValueChanged? onPressed; const OBCategoryBadge({ - Key key, - this.category, + Key? key, + required this.category, this.size = OBCategoryBadgeSize.medium, this.isEnabled = true, this.onPressed, @@ -37,7 +37,7 @@ class OBCategoryBadge extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { var theme = snapshot.data; var primaryColor = - themeValueParserService.parseColor(theme.primaryColor); + themeValueParserService.parseColor(theme!.primaryColor); final bool isDarkPrimaryColor = themeValueParserService.isDarkColor(primaryColor); @@ -52,7 +52,7 @@ class OBCategoryBadge extends StatelessWidget { Widget _buildEnabledBadge(BuildContext context) { ThemeValueParserService themeValueParserService = OpenbookProvider.of(context).themeValueParserService; - Color badgeColor = themeValueParserService.parseColor(category.color); + Color badgeColor = themeValueParserService.parseColor(category.color!); final bool badgeIsDark = themeValueParserService.isDarkColor(badgeColor); return _buildBadge( @@ -60,7 +60,7 @@ class OBCategoryBadge extends StatelessWidget { textColor: badgeIsDark ? Colors.white : Colors.black); } - Widget _buildBadge({@required Color color, @required Color textColor}) { + Widget _buildBadge({required Color color, required Color textColor}) { return GestureDetector( onTap: _onTapped, child: Container( @@ -68,7 +68,7 @@ class OBCategoryBadge extends StatelessWidget { BoxDecoration(color: color, borderRadius: BorderRadius.circular(5)), padding: _getPadding(), child: Text( - category.name, + category.name!, style: TextStyle( color: textColor, //fontWeight: isEnabled ? FontWeight.bold : FontWeight.normal, @@ -119,7 +119,7 @@ class OBCategoryBadge extends StatelessWidget { } void _onTapped() { - if (onPressed != null) onPressed(category); + if (onPressed != null) onPressed!(category); } } diff --git a/lib/widgets/checkbox.dart b/lib/widgets/checkbox.dart index 12bdd96a6..e3785aaf9 100644 --- a/lib/widgets/checkbox.dart +++ b/lib/widgets/checkbox.dart @@ -6,8 +6,8 @@ class OBCheckbox extends StatelessWidget { final OBCheckboxSize size; const OBCheckbox({ - Key key, - this.value, + Key? key, + this.value = false, this.size = OBCheckboxSize.medium, }) : super(key: key); diff --git a/lib/widgets/circle_color_preview.dart b/lib/widgets/circle_color_preview.dart index 5e22f1b8c..6e9782a77 100644 --- a/lib/widgets/circle_color_preview.dart +++ b/lib/widgets/circle_color_preview.dart @@ -21,7 +21,7 @@ class OBCircleColorPreview extends StatelessWidget { height: circleSize, width: circleSize, decoration: BoxDecoration( - color: Pigment.fromString(circle.color), + color: Pigment.fromString(circle.color!), border: Border.all(color: Color.fromARGB(10, 0, 0, 0), width: 3), borderRadius: BorderRadius.circular(50)), ); diff --git a/lib/widgets/circles_horizontal_list/circles_horizontal_list.dart b/lib/widgets/circles_horizontal_list/circles_horizontal_list.dart index e8094b30a..00395d2cc 100644 --- a/lib/widgets/circles_horizontal_list/circles_horizontal_list.dart +++ b/lib/widgets/circles_horizontal_list/circles_horizontal_list.dart @@ -9,14 +9,14 @@ class OBCirclesHorizontalList extends StatelessWidget { final List circles; final List selectedCircles; final List disabledCircles; - final List previouslySelectedCircles; + final List? previouslySelectedCircles; final VoidCallback onWantsToCreateANewCircle; OBCirclesHorizontalList(this.circles, - {@required this.onCirclePressed, - @required this.selectedCircles, - @required this.disabledCircles, - @required this.onWantsToCreateANewCircle, + {required this.onCirclePressed, + required this.selectedCircles, + required this.disabledCircles, + required this.onWantsToCreateANewCircle, this.previouslySelectedCircles}); @override @@ -40,7 +40,7 @@ class OBCirclesHorizontalList extends StatelessWidget { bool isSelected = selectedCircles.contains(circle); bool isDisabled = disabledCircles.contains(circle); bool wasPreviouslySelected = previouslySelectedCircles != null && - previouslySelectedCircles.contains(circle); + previouslySelectedCircles!.contains(circle); listItem = OBCircleHorizontalListItem(circle, wasPreviouslySelected: wasPreviouslySelected, onCirclePressed: onCirclePressed, diff --git a/lib/widgets/circles_horizontal_list/widgets/circle_horizontal_list_item.dart b/lib/widgets/circles_horizontal_list/widgets/circle_horizontal_list_item.dart index 7b9f91f7a..4dd899164 100644 --- a/lib/widgets/circles_horizontal_list/widgets/circle_horizontal_list_item.dart +++ b/lib/widgets/circles_horizontal_list/widgets/circle_horizontal_list_item.dart @@ -13,18 +13,18 @@ class OBCircleHorizontalListItem extends StatelessWidget { final bool isSelected; final bool isDisabled; final Circle circle; - final OnCirclePressed onCirclePressed; + final OnCirclePressed? onCirclePressed; final bool wasPreviouslySelected; OBCircleHorizontalListItem(this.circle, - {@required this.onCirclePressed, - this.isSelected, - this.isDisabled, + {required this.onCirclePressed, + this.isSelected = false, + this.isDisabled = false, this.wasPreviouslySelected = false}); @override Widget build(BuildContext context) { - int usersCount = circle.usersCount; + int usersCount = circle.usersCount!; LocalizationService localizationService = OpenbookProvider.of(context).localizationService; if (wasPreviouslySelected) { @@ -39,7 +39,7 @@ class OBCircleHorizontalListItem extends StatelessWidget { Widget item = GestureDetector( onTap: () { if (this.onCirclePressed != null && !isDisabled) { - this.onCirclePressed(circle); + this.onCirclePressed!(circle); } }, child: ConstrainedBox( @@ -67,7 +67,7 @@ class OBCircleHorizontalListItem extends StatelessWidget { height: 10, ), OBText( - circle.name, + circle.name!, maxLines: 1, style: TextStyle( fontSize: 14, diff --git a/lib/widgets/circles_horizontal_list/widgets/new_circle_horizontal_list_item.dart b/lib/widgets/circles_horizontal_list/widgets/new_circle_horizontal_list_item.dart index f1019d38c..80921a317 100644 --- a/lib/widgets/circles_horizontal_list/widgets/new_circle_horizontal_list_item.dart +++ b/lib/widgets/circles_horizontal_list/widgets/new_circle_horizontal_list_item.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; class OBNewCircleHorizontalListItem extends StatelessWidget { final VoidCallback onPressed; - OBNewCircleHorizontalListItem({@required this.onPressed}); + OBNewCircleHorizontalListItem({required this.onPressed}); @override Widget build(BuildContext context) { diff --git a/lib/widgets/cirles_wrap.dart b/lib/widgets/cirles_wrap.dart index 981670030..44c43f10b 100644 --- a/lib/widgets/cirles_wrap.dart +++ b/lib/widgets/cirles_wrap.dart @@ -5,13 +5,13 @@ import 'package:flutter/material.dart'; export 'package:Okuna/widgets/circle_color_preview.dart'; class OBCirclesWrap extends StatelessWidget { - final List circles; - final Widget leading; + final List? circles; + final Widget? leading; final OBTextSize textSize; final OBCircleColorPreviewSize circlePreviewSize; const OBCirclesWrap( - {Key key, + {Key? key, this.circles, this.leading, this.textSize = OBTextSize.medium, @@ -22,9 +22,9 @@ class OBCirclesWrap extends StatelessWidget { Widget build(BuildContext context) { List connectionItems = []; - if (leading != null) connectionItems.add(leading); + if (leading != null) connectionItems.add(leading!); - circles.forEach((Circle circle) { + circles?.forEach((Circle circle) { connectionItems.add(Row( mainAxisSize: MainAxisSize.min, children: [ @@ -36,7 +36,7 @@ class OBCirclesWrap extends StatelessWidget { width: 5, ), OBText( - circle.name, + circle.name!, size: textSize, ) ], diff --git a/lib/widgets/contextual_search_boxes/contextual_account_search_box.dart b/lib/widgets/contextual_search_boxes/contextual_account_search_box.dart index 09e76d592..ff50fec21 100644 --- a/lib/widgets/contextual_search_boxes/contextual_account_search_box.dart +++ b/lib/widgets/contextual_search_boxes/contextual_account_search_box.dart @@ -14,13 +14,13 @@ import 'package:flutter/material.dart'; import 'package:async/async.dart'; class OBContextualAccountSearchBox extends StatefulWidget { - final ValueChanged onPostParticipantPressed; - final Post post; - final OBContextualAccountSearchBoxController controller; - final String initialSearchQuery; + final ValueChanged? onPostParticipantPressed; + final Post? post; + final OBContextualAccountSearchBoxController? controller; + final String? initialSearchQuery; const OBContextualAccountSearchBox( - {Key key, + {Key? key, this.onPostParticipantPressed, // If passed, searches for post participants, if not all users using the global search API this.post, @@ -36,28 +36,28 @@ class OBContextualAccountSearchBox extends StatefulWidget { class OBContextualAccountSearchBoxState extends State { - UserService _userService; - LocalizationService _localizationService; - ToastService _toastService; + late UserService _userService; + late LocalizationService _localizationService; + late ToastService _toastService; - bool _needsBootstrap; + late bool _needsBootstrap; - CancelableOperation _getAllOperation; - CancelableOperation _searchParticipantsOperation; + CancelableOperation? _getAllOperation; + CancelableOperation? _searchParticipantsOperation; - String _searchQuery; - List _all; - bool _getAllInProgress; - List _searchResults; - bool _searchInProgress; - bool _isInPostContext; + late String _searchQuery; + late List _all; + late bool _getAllInProgress; + late List _searchResults; + late bool _searchInProgress; + late bool _isInPostContext; @override void initState() { super.initState(); _isInPostContext = widget.post != null; _needsBootstrap = true; - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); _all = []; _searchResults = []; _searchQuery = ''; @@ -82,11 +82,11 @@ class OBContextualAccountSearchBoxState _bootstrap(); _needsBootstrap = false; if (widget.initialSearchQuery != null && - widget.initialSearchQuery.isNotEmpty) { - _searchQuery = widget.initialSearchQuery; + widget.initialSearchQuery!.isNotEmpty) { + _searchQuery = widget.initialSearchQuery!; _searchInProgress = true; Future.delayed(Duration(milliseconds: 0), () { - search(widget.initialSearchQuery); + search(widget.initialSearchQuery!); }); } } @@ -184,7 +184,7 @@ class OBContextualAccountSearchBoxState } Future refreshAll() async { - if (_getAllOperation != null) _getAllOperation.cancel(); + if (_getAllOperation != null) _getAllOperation!.cancel(); _setGetAllInProgress(true); @@ -192,10 +192,10 @@ class OBContextualAccountSearchBoxState try { _getAllOperation = CancelableOperation.fromFuture(_isInPostContext - ? _userService.getPostParticipants(post: widget.post) + ? _userService.getPostParticipants(post: widget.post!) : _userService.getLinkedUsers()); - UsersList all = await _getAllOperation.value; - _setAll(all.users); + UsersList all = await _getAllOperation!.value; + _setAll(all.users!); } catch (error) { _onError(error); } finally { @@ -206,7 +206,7 @@ class OBContextualAccountSearchBoxState Future search(String searchQuery) async { if (_searchParticipantsOperation != null) - _searchParticipantsOperation.cancel(); + _searchParticipantsOperation!.cancel(); _setSearchInProgress(true); debugLog('Searching post participants with query:$searchQuery'); @@ -222,10 +222,10 @@ class OBContextualAccountSearchBoxState _searchParticipantsOperation = CancelableOperation.fromFuture( _isInPostContext ? _userService.searchPostParticipants( - query: searchQuery, post: widget.post) + query: searchQuery, post: widget.post!) : _userService.getUsersWithQuery(searchQuery)); - UsersList searchResults = await _searchParticipantsOperation.value; - _setSearchResults(searchResults.users); + UsersList searchResults = await _searchParticipantsOperation!.value; + _setSearchResults(searchResults.users!); } catch (error) { _onError(error); } finally { @@ -239,8 +239,8 @@ class OBContextualAccountSearchBoxState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -282,7 +282,7 @@ class OBContextualAccountSearchBoxState debugLog('Clearing search'); setState(() { if (_searchParticipantsOperation != null) - _searchParticipantsOperation.cancel(); + _searchParticipantsOperation!.cancel(); _searchInProgress = false; _searchQuery = ''; _searchResults = []; @@ -295,8 +295,8 @@ class OBContextualAccountSearchBoxState } class OBContextualAccountSearchBoxController { - OBContextualAccountSearchBoxState _state; - String _lastSearchQuery; + OBContextualAccountSearchBoxState? _state; + String? _lastSearchQuery; void attach(OBContextualAccountSearchBoxState state) { _state = state; @@ -305,20 +305,20 @@ class OBContextualAccountSearchBoxController { Future search(String searchQuery) async { _lastSearchQuery = searchQuery; - if (_state == null || !_state.mounted) { + if (_state == null || (_state != null && !_state!.mounted)) { debugLog('Tried to search without mounted state'); return null; } - return _state.search(searchQuery); + return _state!.search(searchQuery); } void clearSearch() { _lastSearchQuery = null; - _state.clearSearch(); + _state?.clearSearch(); } - String getLastSearchQuery() { + String? getLastSearchQuery() { return _lastSearchQuery; } diff --git a/lib/widgets/contextual_search_boxes/contextual_community_search_box.dart b/lib/widgets/contextual_search_boxes/contextual_community_search_box.dart index a3a1a3a5b..e38c32c95 100644 --- a/lib/widgets/contextual_search_boxes/contextual_community_search_box.dart +++ b/lib/widgets/contextual_search_boxes/contextual_community_search_box.dart @@ -13,12 +13,12 @@ import 'package:flutter/material.dart'; import 'package:async/async.dart'; class OBContextualCommunitySearchBox extends StatefulWidget { - final ValueChanged onCommunityPressed; - final OBContextualCommunitySearchBoxController controller; - final String initialSearchQuery; + final ValueChanged? onCommunityPressed; + final OBContextualCommunitySearchBoxController? controller; + final String? initialSearchQuery; const OBContextualCommunitySearchBox( - {Key key, + {Key? key, this.onCommunityPressed, this.controller, this.initialSearchQuery}) @@ -32,26 +32,26 @@ class OBContextualCommunitySearchBox extends StatefulWidget { class OBContextualCommunitySearchBoxState extends State { - UserService _userService; - LocalizationService _localizationService; - ToastService _toastService; + late UserService _userService; + late LocalizationService _localizationService; + late ToastService _toastService; - bool _needsBootstrap; + late bool _needsBootstrap; - CancelableOperation _getAllOperation; - CancelableOperation _searchParticipantsOperation; + CancelableOperation? _getAllOperation; + CancelableOperation? _searchParticipantsOperation; - String _searchQuery; - List _all; - bool _getAllInProgress; - List _searchResults; - bool _searchInProgress; + late String _searchQuery; + late List _all; + late bool _getAllInProgress; + late List _searchResults; + late bool _searchInProgress; @override void initState() { super.initState(); _needsBootstrap = true; - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); _all = []; _searchResults = []; _searchQuery = ''; @@ -76,11 +76,11 @@ class OBContextualCommunitySearchBoxState _bootstrap(); _needsBootstrap = false; if (widget.initialSearchQuery != null && - widget.initialSearchQuery.isNotEmpty) { - _searchQuery = widget.initialSearchQuery; + widget.initialSearchQuery!.isNotEmpty) { + _searchQuery = widget.initialSearchQuery!; _searchInProgress = true; Future.delayed(Duration(milliseconds: 0), () { - search(widget.initialSearchQuery); + search(widget.initialSearchQuery!); }); } } @@ -186,7 +186,7 @@ class OBContextualCommunitySearchBoxState } Future refreshAll() async { - if (_getAllOperation != null) _getAllOperation.cancel(); + if (_getAllOperation != null) _getAllOperation!.cancel(); _setGetAllInProgress(true); @@ -195,8 +195,8 @@ class OBContextualCommunitySearchBoxState try { _getAllOperation = CancelableOperation.fromFuture(_userService.getJoinedCommunities()); - CommunitiesList all = await _getAllOperation.value; - _setAll(all.communities); + CommunitiesList all = await _getAllOperation!.value; + _setAll(all.communities!); } catch (error) { _onError(error); } finally { @@ -207,7 +207,7 @@ class OBContextualCommunitySearchBoxState Future search(String searchQuery) async { if (_searchParticipantsOperation != null) - _searchParticipantsOperation.cancel(); + _searchParticipantsOperation!.cancel(); _setSearchInProgress(true); debugLog('Searching post participants with query:$searchQuery'); @@ -222,8 +222,8 @@ class OBContextualCommunitySearchBoxState try { _searchParticipantsOperation = CancelableOperation.fromFuture( _userService.searchCommunitiesWithQuery(searchQuery)); - CommunitiesList searchResults = await _searchParticipantsOperation.value; - _setSearchResults(searchResults.communities); + CommunitiesList searchResults = await _searchParticipantsOperation!.value; + _setSearchResults(searchResults.communities!); } catch (error) { _onError(error); } finally { @@ -237,8 +237,8 @@ class OBContextualCommunitySearchBoxState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -280,7 +280,7 @@ class OBContextualCommunitySearchBoxState debugLog('Clearing search'); setState(() { if (_searchParticipantsOperation != null) - _searchParticipantsOperation.cancel(); + _searchParticipantsOperation!.cancel(); _searchInProgress = false; _searchQuery = ''; _searchResults = []; @@ -293,8 +293,8 @@ class OBContextualCommunitySearchBoxState } class OBContextualCommunitySearchBoxController { - OBContextualCommunitySearchBoxState _state; - String _lastSearchQuery; + OBContextualCommunitySearchBoxState? _state; + String? _lastSearchQuery; void attach(OBContextualCommunitySearchBoxState state) { _state = state; @@ -303,20 +303,20 @@ class OBContextualCommunitySearchBoxController { Future search(String searchQuery) async { _lastSearchQuery = searchQuery; - if (_state == null || !_state.mounted) { + if (_state == null || (_state != null && !_state!.mounted)) { debugLog('Tried to search without mounted state'); return null; } - return _state.search(searchQuery); + return _state!.search(searchQuery); } void clearSearch() { _lastSearchQuery = null; - _state.clearSearch(); + _state?.clearSearch(); } - String getLastSearchQuery() { + String? getLastSearchQuery() { return _lastSearchQuery; } diff --git a/lib/widgets/contextual_search_boxes/contextual_hashtag_search_box.dart b/lib/widgets/contextual_search_boxes/contextual_hashtag_search_box.dart index 3f708ddcb..c0d711b90 100644 --- a/lib/widgets/contextual_search_boxes/contextual_hashtag_search_box.dart +++ b/lib/widgets/contextual_search_boxes/contextual_hashtag_search_box.dart @@ -13,12 +13,12 @@ import 'package:flutter/material.dart'; import 'package:async/async.dart'; class OBContextualHashtagSearchBox extends StatefulWidget { - final ValueChanged onHashtagPressed; - final OBContextualHashtagSearchBoxController controller; - final String initialSearchQuery; + final ValueChanged? onHashtagPressed; + final OBContextualHashtagSearchBoxController? controller; + final String? initialSearchQuery; const OBContextualHashtagSearchBox( - {Key key, + {Key? key, this.onHashtagPressed, this.controller, this.initialSearchQuery}) @@ -32,24 +32,24 @@ class OBContextualHashtagSearchBox extends StatefulWidget { class OBContextualHashtagSearchBoxState extends State { - UserService _userService; - LocalizationService _localizationService; - ToastService _toastService; + late UserService _userService; + late LocalizationService _localizationService; + late ToastService _toastService; - bool _needsBootstrap; + late bool _needsBootstrap; - CancelableOperation _getAllOperation; - CancelableOperation _searchParticipantsOperation; + CancelableOperation? _getAllOperation; + CancelableOperation? _searchParticipantsOperation; - String _searchQuery; - List _searchResults; - bool _searchInProgress; + late String _searchQuery; + late List _searchResults; + late bool _searchInProgress; @override void initState() { super.initState(); _needsBootstrap = true; - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); _searchResults = []; _searchQuery = ''; _searchInProgress = false; @@ -72,11 +72,11 @@ class OBContextualHashtagSearchBoxState _bootstrap(); _needsBootstrap = false; if (widget.initialSearchQuery != null && - widget.initialSearchQuery.isNotEmpty) { - _searchQuery = widget.initialSearchQuery; + widget.initialSearchQuery!.isNotEmpty) { + _searchQuery = widget.initialSearchQuery!; _searchInProgress = true; Future.delayed(Duration(milliseconds: 0), () { - search(widget.initialSearchQuery); + search(widget.initialSearchQuery!); }); } } @@ -119,7 +119,11 @@ class OBContextualHashtagSearchBoxState child: const OBIcon(OBIcons.happy), ), title: OBText(_localizationService.contextual_hashtag_search_box__be_the_first(_searchQuery)), - onTap: () => widget.onHashtagPressed(Hashtag(name: _searchQuery)), + onTap: () => { + if (widget.onHashtagPressed != null) { + widget.onHashtagPressed!(Hashtag(name: _searchQuery)) + } + }, ); } else { return const SizedBox(); @@ -139,7 +143,7 @@ class OBContextualHashtagSearchBoxState Future search(String searchQuery) async { if (_searchParticipantsOperation != null) - _searchParticipantsOperation.cancel(); + _searchParticipantsOperation!.cancel(); _setSearchInProgress(true); debugLog('Searching post participants with query:$searchQuery'); @@ -154,8 +158,8 @@ class OBContextualHashtagSearchBoxState try { _searchParticipantsOperation = CancelableOperation.fromFuture( _userService.getHashtagsWithQuery(searchQuery)); - HashtagsList searchResults = await _searchParticipantsOperation.value; - _setSearchResults(searchResults.hashtags); + HashtagsList searchResults = await _searchParticipantsOperation!.value; + _setSearchResults(searchResults.hashtags!); } catch (error) { _onError(error); } finally { @@ -169,8 +173,8 @@ class OBContextualHashtagSearchBoxState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -200,7 +204,7 @@ class OBContextualHashtagSearchBoxState debugLog('Clearing search'); setState(() { if (_searchParticipantsOperation != null) - _searchParticipantsOperation.cancel(); + _searchParticipantsOperation!.cancel(); _searchInProgress = false; _searchQuery = ''; _searchResults = []; @@ -213,8 +217,8 @@ class OBContextualHashtagSearchBoxState } class OBContextualHashtagSearchBoxController { - OBContextualHashtagSearchBoxState _state; - String _lastSearchQuery; + OBContextualHashtagSearchBoxState? _state; + String? _lastSearchQuery; void attach(OBContextualHashtagSearchBoxState state) { _state = state; @@ -223,20 +227,20 @@ class OBContextualHashtagSearchBoxController { Future search(String searchQuery) async { _lastSearchQuery = searchQuery; - if (_state == null || !_state.mounted) { + if (_state == null || (_state != null && !_state!.mounted)) { debugLog('Tried to search without mounted state'); return null; } - return _state.search(searchQuery); + return _state!.search(searchQuery); } void clearSearch() { _lastSearchQuery = null; - _state.clearSearch(); + _state?.clearSearch(); } - String getLastSearchQuery() { + String? getLastSearchQuery() { return _lastSearchQuery; } diff --git a/lib/widgets/contextual_search_boxes/contextual_search_box_state.dart b/lib/widgets/contextual_search_boxes/contextual_search_box_state.dart index 40a7076db..699950755 100644 --- a/lib/widgets/contextual_search_boxes/contextual_search_box_state.dart +++ b/lib/widgets/contextual_search_boxes/contextual_search_box_state.dart @@ -10,17 +10,17 @@ import 'package:flutter/material.dart'; abstract class OBContextualSearchBoxState extends State { - TextAutocompletionService _textAutocompletionService; - OBContextualAccountSearchBoxController _contextualAccountSearchBoxController; - OBContextualCommunitySearchBoxController + late TextAutocompletionService _textAutocompletionService; + late OBContextualAccountSearchBoxController _contextualAccountSearchBoxController; + late OBContextualCommunitySearchBoxController _contextualCommunitySearchBoxController; - OBContextualHashtagSearchBoxController _contextualHashtagSearchBoxController; + late OBContextualHashtagSearchBoxController _contextualHashtagSearchBoxController; - TextAutocompletionType _autocompletionType; + TextAutocompletionType? _autocompletionType; - TextEditingController _autocompleteTextController; + TextEditingController? _autocompleteTextController; - bool isAutocompleting; + late bool isAutocompleting; @override void initState() { @@ -99,38 +99,42 @@ abstract class OBContextualSearchBoxState } void _onAccountSearchBoxUserPressed(User user) { - autocompleteFoundAccountUsername(user.username); + autocompleteFoundAccountUsername(user.username!); } void _onCommunitySearchBoxUserPressed(Community community) { - autocompleteFoundCommunityName(community.name); + autocompleteFoundCommunityName(community.name!); } void _onHashtagSearchBoxUserPressed(Hashtag hashtag) { - autocompleteFoundHashtagName(hashtag.name); + autocompleteFoundHashtagName(hashtag.name!); } void _checkForAutocomplete() { - TextAutocompletionResult result = _textAutocompletionService - .checkTextForAutocompletion(_autocompleteTextController); + TextAutocompletionResult? result = _autocompleteTextController != null + ? _textAutocompletionService + .checkTextForAutocompletion(_autocompleteTextController!) + : null; - if (result.isAutocompleting) { + if (result != null && result.isAutocompleting) { debugLog('Wants to autocomplete with type ${result.type} searchQuery:' + - result.autocompleteQuery); + (result.autocompleteQuery ?? 'null')); _setIsAutocompleting(true); _setAutocompletionType(result.type); switch (result.type) { case TextAutocompletionType.hashtag: _contextualHashtagSearchBoxController - .search(result.autocompleteQuery); + .search(result.autocompleteQuery ?? ''); break; case TextAutocompletionType.account: _contextualAccountSearchBoxController - .search(result.autocompleteQuery); + .search(result.autocompleteQuery ?? ''); break; case TextAutocompletionType.community: _contextualCommunitySearchBoxController - .search(result.autocompleteQuery); + .search(result.autocompleteQuery ?? ''); + break; + case null: break; } } else if (isAutocompleting) { @@ -148,8 +152,10 @@ abstract class OBContextualSearchBoxState debugLog('Autocompleting with username:$foundAccountUsername'); setState(() { - _textAutocompletionService.autocompleteTextWithUsername( - _autocompleteTextController, foundAccountUsername); + if (_autocompleteTextController != null) { + _textAutocompletionService.autocompleteTextWithUsername( + _autocompleteTextController!, foundAccountUsername); + } }); } @@ -162,8 +168,10 @@ abstract class OBContextualSearchBoxState debugLog('Autocompleting with name:$foundCommunityName'); setState(() { - _textAutocompletionService.autocompleteTextWithCommunityName( - _autocompleteTextController, foundCommunityName); + if (_autocompleteTextController != null) { + _textAutocompletionService.autocompleteTextWithCommunityName( + _autocompleteTextController!, foundCommunityName); + } }); } @@ -176,8 +184,10 @@ abstract class OBContextualSearchBoxState debugLog('Autocompleting with name:$foundHashtagName'); setState(() { - _textAutocompletionService.autocompleteTextWithHashtagName( - _autocompleteTextController, foundHashtagName); + if (_autocompleteTextController != null) { + _textAutocompletionService.autocompleteTextWithHashtagName( + _autocompleteTextController!, foundHashtagName); + } }); } @@ -187,7 +197,7 @@ abstract class OBContextualSearchBoxState }); } - void _setAutocompletionType(TextAutocompletionType autocompletionType) { + void _setAutocompletionType(TextAutocompletionType? autocompletionType) { setState(() { _autocompletionType = autocompletionType; }); diff --git a/lib/widgets/cover.dart b/lib/widgets/cover.dart index a7350a623..c06a03b1f 100644 --- a/lib/widgets/cover.dart +++ b/lib/widgets/cover.dart @@ -6,8 +6,8 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; class OBCover extends StatelessWidget { - final String coverUrl; - final File coverFile; + final String? coverUrl; + final File? coverFile; static const double largeSizeHeight = 230.0; static const double mediumSizedHeight = 190.0; static const double smallSizeHeight = 160.0; @@ -25,7 +25,7 @@ class OBCover extends StatelessWidget { Widget build(BuildContext context) { Widget image; - double coverHeight; + late double coverHeight; switch (size) { case OBCoverSize.large: @@ -44,7 +44,7 @@ class OBCover extends StatelessWidget { if (coverFile != null) { image = FadeInImage( placeholder: AssetImage(COVER_PLACEHOLDER), - image: FileImage(coverFile), + image: FileImage(coverFile!), fit: BoxFit.cover, height: double.infinity, width: double.infinity, @@ -55,13 +55,13 @@ class OBCover extends StatelessWidget { } else { image = CachedNetworkImage( fit: BoxFit.cover, - imageUrl: coverUrl != null ? coverUrl : '', + imageUrl: coverUrl ?? '', placeholder: (BuildContext context, String url) { return const Center( child: const CircularProgressIndicator(), ); }, - errorWidget: (BuildContext context, String url, Object error) { + errorWidget: (BuildContext context, String url, dynamic error) { return const SizedBox( child: const Center( child: const OBText('Could not load cover'), @@ -80,7 +80,7 @@ class OBCover extends StatelessWidget { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.dialogService - .showZoomablePhotoBoxView(imageUrl: coverUrl, context: context); + .showZoomablePhotoBoxView(imageUrl: coverUrl!, context: context); }, ); } diff --git a/lib/widgets/emoji_picker/emoji_picker.dart b/lib/widgets/emoji_picker/emoji_picker.dart index ff22ba629..a29a9f216 100644 --- a/lib/widgets/emoji_picker/emoji_picker.dart +++ b/lib/widgets/emoji_picker/emoji_picker.dart @@ -10,7 +10,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class OBEmojiPicker extends StatefulWidget { - final OnEmojiPicked onEmojiPicked; + final OnEmojiPicked? onEmojiPicked; final bool isReactionsPicker; final bool hasSearch; @@ -26,14 +26,14 @@ class OBEmojiPicker extends StatefulWidget { } class OBEmojiPickerState extends State { - UserService _userService; + late UserService _userService; - bool _needsBootstrap; - bool _hasSearch; + late bool _needsBootstrap; + late bool _hasSearch; - List _emojiGroups; - List _emojiSearchResults; - String _emojiSearchQuery; + late List _emojiGroups; + late List _emojiSearchResults; + late String _emojiSearchQuery; @override void initState() { @@ -79,8 +79,12 @@ class OBEmojiPickerState extends State { ); } - void _onEmojiPressed(Emoji pressedEmoji, EmojiGroup emojiGroup) { - widget.onEmojiPicked(pressedEmoji, emojiGroup); + void _onEmojiPressed(Emoji pressedEmoji, EmojiGroup? emojiGroup) { + if (widget.onEmojiPicked == null) { + return; + } + + widget.onEmojiPicked!(pressedEmoji, emojiGroup); } void _onSearch(String searchString) { @@ -95,9 +99,9 @@ class OBEmojiPickerState extends State { List searchResults = _emojiGroups.map((EmojiGroup emojiGroup) { - List groupEmojis = emojiGroup.getEmojis(); + List groupEmojis = emojiGroup.getEmojis()!; List groupSearchResults = groupEmojis.where((Emoji emoji) { - return emoji.keyword.toLowerCase().contains(standarisedSearchStr); + return emoji.keyword!.toLowerCase().contains(standarisedSearchStr); }).toList(); return EmojiGroupSearchResults( group: emojiGroup, searchResults: groupSearchResults); @@ -111,7 +115,7 @@ class OBEmojiPickerState extends State { EmojiGroupList emojiGroupList = await (widget.isReactionsPicker ? _userService.getReactionEmojiGroups() : _userService.getEmojiGroups()); - this._setEmojiGroups(emojiGroupList.emojisGroups); + this._setEmojiGroups(emojiGroupList.emojisGroups!); } void _setEmojiGroups(List emojiGroups) { @@ -142,11 +146,11 @@ class OBEmojiPickerState extends State { enum OBEmojiPickerStatus { searching, suggesting, overview } -typedef void OnEmojiPicked(Emoji pickedEmoji, EmojiGroup emojiGroup); +typedef void OnEmojiPicked(Emoji pickedEmoji, EmojiGroup? emojiGroup); class EmojiGroupSearchResults { final EmojiGroup group; final List searchResults; - EmojiGroupSearchResults({@required this.group, @required this.searchResults}); + EmojiGroupSearchResults({required this.group, required this.searchResults}); } diff --git a/lib/widgets/emoji_picker/widgets/emoji_groups/emoji_groups.dart b/lib/widgets/emoji_picker/widgets/emoji_groups/emoji_groups.dart index 183fafe81..7a3d67021 100644 --- a/lib/widgets/emoji_picker/widgets/emoji_groups/emoji_groups.dart +++ b/lib/widgets/emoji_picker/widgets/emoji_groups/emoji_groups.dart @@ -4,7 +4,7 @@ import 'package:Okuna/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_gr import 'package:flutter/material.dart'; class OBEmojiGroups extends StatelessWidget { - final OnEmojiPressed onEmojiPressed; + final OnEmojiPressed? onEmojiPressed; final List emojiGroups; OBEmojiGroups(this.emojiGroups, {this.onEmojiPressed}); diff --git a/lib/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_group/emoji_group.dart b/lib/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_group/emoji_group.dart index 2bbebc6ad..171d0c7dc 100644 --- a/lib/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_group/emoji_group.dart +++ b/lib/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_group/emoji_group.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; class OBEmojiGroup extends StatelessWidget { final EmojiGroup emojiGroup; - final OnEmojiPressed onEmojiPressed; + final OnEmojiPressed? onEmojiPressed; OBEmojiGroup(this.emojiGroup, {this.onEmojiPressed}); @@ -17,14 +17,14 @@ class OBEmojiGroup extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - OBText(emojiGroup.keyword, + OBText(emojiGroup.keyword ?? '', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0)), const SizedBox( height: 10.0, ), Wrap( spacing: 20.0, - children: this.emojiGroup.emojis.emojis.map((Emoji emoji) { + children: this.emojiGroup.emojis!.emojis!.map((Emoji emoji) { return OBEmoji( emoji, emojiGroup: emojiGroup, diff --git a/lib/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_group/widgets/emoji.dart b/lib/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_group/widgets/emoji.dart index 8c1729168..28d40f5c5 100644 --- a/lib/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_group/widgets/emoji.dart +++ b/lib/widgets/emoji_picker/widgets/emoji_groups/widgets/emoji_group/widgets/emoji.dart @@ -7,8 +7,8 @@ enum OBEmojiSize { small, medium, large } class OBEmoji extends StatelessWidget { final Emoji emoji; - final EmojiGroup emojiGroup; - final OnEmojiPressed onEmojiPressed; + final EmojiGroup? emojiGroup; + final OnEmojiPressed? onEmojiPressed; final OBEmojiSize size; OBEmoji(this.emoji, @@ -21,17 +21,17 @@ class OBEmoji extends StatelessWidget { return IconButton( icon: Image( height: dimensions, - image: AdvancedNetworkImage(emoji.image, useDiskCache: true), + image: AdvancedNetworkImage(emoji.image!, useDiskCache: true), ), onPressed: onEmojiPressed != null ? () { - onEmojiPressed(emoji, emojiGroup); + onEmojiPressed!(emoji, emojiGroup); } : null); } double getIconDimensions(OBEmojiSize size) { - double iconSize; + late double iconSize; switch (size) { case OBEmojiSize.large: @@ -50,4 +50,4 @@ class OBEmoji extends StatelessWidget { } } -typedef void OnEmojiPressed(Emoji pressedEmoji, EmojiGroup emojiGroup); +typedef void OnEmojiPressed(Emoji pressedEmoji, EmojiGroup? emojiGroup); diff --git a/lib/widgets/emoji_picker/widgets/emoji_search_results.dart b/lib/widgets/emoji_picker/widgets/emoji_search_results.dart index 80895afbf..6e6ec5f7a 100644 --- a/lib/widgets/emoji_picker/widgets/emoji_search_results.dart +++ b/lib/widgets/emoji_picker/widgets/emoji_search_results.dart @@ -16,7 +16,7 @@ class OBEmojiSearchResults extends StatelessWidget { final OnEmojiPressed onEmojiPressed; OBEmojiSearchResults(this.results, this.searchQuery, - {Key key, @required this.onEmojiPressed}) + {Key? key, required this.onEmojiPressed}) : super(key: key); @override @@ -41,16 +41,16 @@ class OBEmojiSearchResults extends StatelessWidget { leading: ConstrainedBox( constraints: BoxConstraints(maxHeight: 25), child: CachedNetworkImage( - imageUrl: emoji.image, + imageUrl: emoji.image!, errorWidget: - (BuildContext context, String url, Object error) { + (BuildContext context, String url, dynamic error) { return const SizedBox( child: Center(child: const OBText('?')), ); }, ), ), - title: OBText(emoji.keyword), + title: OBText(emoji.keyword!), ); }).toList(); diff --git a/lib/widgets/emoji_preview.dart b/lib/widgets/emoji_preview.dart index 3ab0e77ba..ce9f7a491 100644 --- a/lib/widgets/emoji_preview.dart +++ b/lib/widgets/emoji_preview.dart @@ -20,11 +20,11 @@ class OBEmojiPreview extends StatelessWidget { return CachedNetworkImage( height: emojiSize, width: emojiSize, - imageUrl: emoji.image, + imageUrl: emoji.image!, placeholder: (BuildContext context, String url) { return const CircularProgressIndicator(); }, - errorWidget: (BuildContext context, String url, Object error) { + errorWidget: (BuildContext context, String url, dynamic error) { return const OBIcon(OBIcons.error); }, ); diff --git a/lib/widgets/fields/categories_field.dart b/lib/widgets/fields/categories_field.dart index 2e8de3f4c..be6ccd7f0 100644 --- a/lib/widgets/fields/categories_field.dart +++ b/lib/widgets/fields/categories_field.dart @@ -9,21 +9,21 @@ import 'package:flutter/material.dart'; import '../../provider.dart'; class OBCategoriesField extends StatefulWidget { - final OBCategoriesFieldController controller; + final OBCategoriesFieldController? controller; final String title; final int max; final int min; final bool displayErrors; final ValueChanged> onChanged; - final List initialCategories; + final List? initialCategories; const OBCategoriesField( - {Key key, + {Key? key, this.controller, - @required this.title, - @required this.max, - @required this.min, - @required this.onChanged, + required this.title, + required this.max, + required this.min, + required this.onChanged, this.displayErrors = false, this.initialCategories}) : super(key: key); @@ -35,18 +35,18 @@ class OBCategoriesField extends StatefulWidget { } class OBCategoriesFieldState extends State { - bool _isValid; - LocalizationService _localizationService; + late bool _isValid; + late LocalizationService _localizationService; @override void initState() { super.initState(); if (widget.controller != null) { - widget.controller.attach(this); + widget.controller!.attach(this); } _isValid = widget.initialCategories == null ? false - : _categoriesLengthIsValid(widget.initialCategories); + : _categoriesLengthIsValid(widget.initialCategories!); } @override @@ -122,13 +122,13 @@ class OBCategoriesFieldState extends State { } class OBCategoriesFieldController { - OBCategoriesFieldState _state; + OBCategoriesFieldState? _state; void attach(OBCategoriesFieldState state) { _state = state; } bool isValid() { - return _state == null ? false : _state._isValid; + return _state == null ? false : _state!._isValid; } } diff --git a/lib/widgets/fields/checkbox_field.dart b/lib/widgets/fields/checkbox_field.dart index 20f05ce57..01605d8fb 100644 --- a/lib/widgets/fields/checkbox_field.dart +++ b/lib/widgets/fields/checkbox_field.dart @@ -6,19 +6,19 @@ import 'package:flutter/material.dart'; class OBCheckboxField extends StatelessWidget { final bool value; - final VoidCallback onTap; - final Widget leading; + final VoidCallback? onTap; + final Widget? leading; final String title; - final String subtitle; + final String? subtitle; final bool isDisabled; - final TextStyle titleStyle; + final TextStyle? titleStyle; OBCheckboxField( - {@required this.value, + {required this.value, this.subtitle, this.onTap, this.leading, - @required this.title, + required this.title, this.isDisabled = false, this.titleStyle}); @@ -35,7 +35,7 @@ class OBCheckboxField extends StatelessWidget { title, style: finalTitleStyle, ), - subtitle: subtitle != null ? OBSecondaryText(subtitle) : null, + subtitle: subtitle != null ? OBSecondaryText(subtitle!) : null, trailing: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, @@ -47,7 +47,7 @@ class OBCheckboxField extends StatelessWidget { ], ), onTap: () { - if (!isDisabled && onTap != null) onTap(); + if (!isDisabled && onTap != null) onTap!(); }), ); diff --git a/lib/widgets/fields/color_field.dart b/lib/widgets/fields/color_field.dart index 3b3a95473..082e64865 100644 --- a/lib/widgets/fields/color_field.dart +++ b/lib/widgets/fields/color_field.dart @@ -8,16 +8,16 @@ import 'package:flutter/material.dart'; import 'package:pigment/pigment.dart'; class OBColorField extends StatefulWidget { - final String initialColor; - final String labelText; - final String hintText; + final String? initialColor; + final String? labelText; + final String? hintText; final OnNewColor onNewColor; const OBColorField( - {Key key, + {Key? key, this.initialColor, this.labelText, - @required this.onNewColor, + required this.onNewColor, this.hintText}) : super(key: key); @@ -28,15 +28,15 @@ class OBColorField extends StatefulWidget { } class OBColorFieldState extends State { - String _color; - ThemeService _themeService; - DialogService _dialogService; + String? _color; + late ThemeService _themeService; + late DialogService _dialogService; @override void initState() { super.initState(); _color = widget.initialColor != null - ? widget.initialColor + ? widget.initialColor! : generateRandomHexColor(); } @@ -51,17 +51,20 @@ class OBColorFieldState extends State { MergeSemantics( child: ListTile( title: OBText( - widget.labelText, + widget.labelText ?? '', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), ), subtitle: - widget.hintText != null ? OBText(widget.hintText) : null, + widget.hintText != null ? OBText(widget.hintText!) : null, trailing: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(50), color: _color == null - ? const SizedBox() - : Pigment.fromString(_color), + // ? const SizedBox() + // TODO: not sure if this is a very good practice, but + // it's complaining about SizedBox not being a color + ? Colors.white + : Pigment.fromString(_color!), ), height: 30, width: 30, @@ -75,7 +78,7 @@ class OBColorFieldState extends State { void _pickColor() { _dialogService.showColorPicker( - initialColor: Pigment.fromString(_color), + initialColor: Pigment.fromString(_color!), onColorChanged: _onPickerColor, context: context); } @@ -90,7 +93,7 @@ class OBColorFieldState extends State { void _setColor(String color) { setState(() { _color = color; - widget.onNewColor(_color); + widget.onNewColor(_color!); }); } diff --git a/lib/widgets/fields/community_type_field.dart b/lib/widgets/fields/community_type_field.dart index 65737d0a1..b8a4379b3 100644 --- a/lib/widgets/fields/community_type_field.dart +++ b/lib/widgets/fields/community_type_field.dart @@ -11,14 +11,14 @@ import 'package:flutter/material.dart'; class OBCommunityTypeField extends StatelessWidget { final CommunityType value; - final ValueChanged onChanged; + final ValueChanged? onChanged; final String title; - final String hintText; + final String? hintText; const OBCommunityTypeField( - {@required this.value, + {required this.value, this.onChanged, - @required this.title, + required this.title, this.hintText}); @override @@ -59,7 +59,7 @@ class OBCommunityTypeField extends StatelessWidget { ) ], ), - subtitle: hintText != null ? OBText(hintText) : null, + subtitle: hintText != null ? OBText(hintText!) : null, trailing: Row( mainAxisSize: MainAxisSize.min, children: [ diff --git a/lib/widgets/fields/date_field.dart b/lib/widgets/fields/date_field.dart index 56f7c1932..50f8b7070 100644 --- a/lib/widgets/fields/date_field.dart +++ b/lib/widgets/fields/date_field.dart @@ -7,17 +7,17 @@ import 'package:intl/intl.dart'; class OBDateField extends StatefulWidget { final String title; final DateTime initialDate; - final ValueChanged onChanged; + final ValueChanged? onChanged; final DateTime minimumDate; final DateTime maximumDate; const OBDateField( - {Key key, - @required this.title, - @required this.initialDate, + {Key? key, + required this.title, + required this.initialDate, this.onChanged, - @required this.minimumDate, - @required this.maximumDate}) + required this.minimumDate, + required this.maximumDate}) : super(key: key); @override @@ -27,7 +27,7 @@ class OBDateField extends StatefulWidget { } class OBDateFieldState extends State { - DateTime _currentDate; + late DateTime _currentDate; @override void initState() { @@ -59,7 +59,9 @@ class OBDateFieldState extends State { _currentDate = newDate; }); - widget.onChanged(newDate); + if (widget.onChanged != null) { + widget.onChanged!(newDate); + } }); }, ), diff --git a/lib/widgets/fields/emoji_field.dart b/lib/widgets/fields/emoji_field.dart index 4087b0e15..b49acd895 100644 --- a/lib/widgets/fields/emoji_field.dart +++ b/lib/widgets/fields/emoji_field.dart @@ -8,14 +8,14 @@ import 'package:flutter/material.dart'; import '../../provider.dart'; class OBEmojiField extends StatelessWidget { - final Emoji emoji; - final String subtitle; - final String labelText; - final String errorText; - final OnEmojiFieldTapped onEmojiFieldTapped; + final Emoji? emoji; + final String? subtitle; + final String? labelText; + final String? errorText; + final OnEmojiFieldTapped? onEmojiFieldTapped; const OBEmojiField( - {Key key, + {Key? key, this.emoji, this.subtitle, this.labelText, @@ -31,15 +31,15 @@ class OBEmojiField extends StatelessWidget { MergeSemantics( child: ListTile( title: OBText( - labelText, + labelText ?? '', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), ), subtitle: errorText != null - ? Text(errorText, style: TextStyle(color: Colors.red)) + ? Text(errorText!, style: TextStyle(color: Colors.red)) : null, - trailing: emoji == null ? OBText(_localizationService.user__emoji_field_none_selected) : OBEmoji(emoji), + trailing: emoji == null ? OBText(_localizationService.user__emoji_field_none_selected) : OBEmoji(emoji!), onTap: () { - if (onEmojiFieldTapped != null) onEmojiFieldTapped(emoji); + if (onEmojiFieldTapped != null) onEmojiFieldTapped!(emoji); }), ), OBDivider(), @@ -48,4 +48,4 @@ class OBEmojiField extends StatelessWidget { } } -typedef void OnEmojiFieldTapped(Emoji currentEmoji); +typedef void OnEmojiFieldTapped(Emoji? currentEmoji); diff --git a/lib/widgets/fields/text_field.dart b/lib/widgets/fields/text_field.dart index 1e8de70b7..e71df2436 100644 --- a/lib/widgets/fields/text_field.dart +++ b/lib/widgets/fields/text_field.dart @@ -3,16 +3,16 @@ import 'package:Okuna/provider.dart'; import 'package:flutter/material.dart'; class OBTextField extends StatelessWidget { - final TextStyle style; - final FocusNode focusNode; - final TextEditingController controller; - final InputDecoration decoration; + final TextStyle? style; + final FocusNode? focusNode; + final TextEditingController? controller; + final InputDecoration? decoration; final bool autocorrect; final bool autofocus; final TextInputAction textInputAction; - final TextInputType keyboardType; - final int maxLines; - final FormFieldValidator validator; + final TextInputType? keyboardType; + final int? maxLines; + final FormFieldValidator? validator; final bool obscureText; final TextCapitalization textCapitalization; @@ -44,7 +44,7 @@ class OBTextField extends StatelessWidget { TextStyle themedTextStyle = TextStyle( color: - themeValueParserService.parseColor(theme.primaryTextColor)); + themeValueParserService.parseColor(theme!.primaryTextColor)); if (style != null) { themedTextStyle = themedTextStyle.merge(style); @@ -54,8 +54,8 @@ class OBTextField extends StatelessWidget { color: themeValueParserService.parseColor(theme.secondaryTextColor)); - if (decoration != null && decoration.hintStyle != null) { - hintTextStyle = hintTextStyle.merge(decoration.hintStyle); + if (decoration != null && decoration!.hintStyle != null) { + hintTextStyle = hintTextStyle.merge(decoration!.hintStyle); } var primaryColor = @@ -76,10 +76,10 @@ class OBTextField extends StatelessWidget { isDarkPrimaryColor ? Brightness.dark : Brightness.light, decoration: InputDecoration( isDense: true, - hintText: decoration.hintText, + hintText: decoration?.hintText, hintStyle: hintTextStyle, - contentPadding: decoration.contentPadding, - border: decoration.border), + contentPadding: decoration?.contentPadding, + border: decoration?.border), autocorrect: autocorrect, autofocus: autofocus, ); diff --git a/lib/widgets/fields/text_form_field.dart b/lib/widgets/fields/text_form_field.dart index 2b1d870d9..ea09ec5af 100644 --- a/lib/widgets/fields/text_form_field.dart +++ b/lib/widgets/fields/text_form_field.dart @@ -5,20 +5,20 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class OBTextFormField extends StatelessWidget { - final TextEditingController controller; - final FormFieldValidator validator; + final TextEditingController? controller; + final FormFieldValidator? validator; final bool autofocus; final bool readOnly; - final InputDecoration decoration; - final int maxLines; - final TextInputType keyboardType; + final InputDecoration? decoration; + final int? maxLines; + final TextInputType? keyboardType; final TextInputAction textInputAction; final OBTextFormFieldSize size; final bool obscureText; final TextCapitalization textCapitalization; final bool autocorrect; - final List inputFormatters; - final FocusNode focusNode; + final List? inputFormatters; + final FocusNode? focusNode; final TextStyle style; final bool hasBorder; @@ -72,7 +72,7 @@ class OBTextFormField extends StatelessWidget { TextStyle finalStyle = style.merge(TextStyle( fontSize: fontSize, color: - themeValueParserService.parseColor(theme.primaryTextColor))); + themeValueParserService.parseColor(theme!.primaryTextColor))); var primaryColor = themeValueParserService.parseColor(theme.primaryColor); diff --git a/lib/widgets/fields/toggle_field.dart b/lib/widgets/fields/toggle_field.dart index ce898a447..7245624da 100644 --- a/lib/widgets/fields/toggle_field.dart +++ b/lib/widgets/fields/toggle_field.dart @@ -5,22 +5,22 @@ import 'package:flutter/material.dart'; class OBToggleField extends StatelessWidget { final bool value; - final ValueChanged onChanged; - final VoidCallback onTap; - final Widget leading; + final ValueChanged? onChanged; + final VoidCallback? onTap; + final Widget? leading; final String title; - final Widget subtitle; + final Widget? subtitle; final bool hasDivider; - final TextStyle titleStyle; + final TextStyle? titleStyle; final bool isLoading; const OBToggleField( - {Key key, - @required this.value, + {Key? key, + required this.value, this.onChanged, this.onTap, this.leading, - @required this.title, + required this.title, this.subtitle, this.hasDivider = true, this.titleStyle, diff --git a/lib/widgets/follows_lists_horizontal_list/follows_lists_horizontal_list.dart b/lib/widgets/follows_lists_horizontal_list/follows_lists_horizontal_list.dart index 1f91c5052..d54bdb65c 100644 --- a/lib/widgets/follows_lists_horizontal_list/follows_lists_horizontal_list.dart +++ b/lib/widgets/follows_lists_horizontal_list/follows_lists_horizontal_list.dart @@ -7,13 +7,13 @@ class OBFollowsListsHorizontalList extends StatelessWidget { final OnFollowsListPressed onFollowsListPressed; final List followsLists; final List selectedFollowsLists; - final List previouslySelectedFollowsLists; + final List? previouslySelectedFollowsLists; final VoidCallback onWantsToCreateANewFollowsList; OBFollowsListsHorizontalList(this.followsLists, - {@required this.onFollowsListPressed, - @required this.selectedFollowsLists, - @required this.onWantsToCreateANewFollowsList, + {required this.onFollowsListPressed, + required this.selectedFollowsLists, + required this.onWantsToCreateANewFollowsList, this.previouslySelectedFollowsLists}); @override @@ -37,7 +37,7 @@ class OBFollowsListsHorizontalList extends StatelessWidget { var followsList = followsLists[index]; bool isSelected = selectedFollowsLists.contains(followsList); bool wasPreviouslySelected = previouslySelectedFollowsLists != null && - previouslySelectedFollowsLists.contains(followsList); + previouslySelectedFollowsLists!.contains(followsList); listItem = OBFollowsListHorizontalListItem(followsList, wasPreviouslySelected: wasPreviouslySelected, onFollowsListPressed: onFollowsListPressed, @@ -53,4 +53,4 @@ class OBFollowsListsHorizontalList extends StatelessWidget { } } -typedef void OnFollowsListPressed(FollowsList list); \ No newline at end of file +typedef void OnFollowsListPressed(FollowsList list); diff --git a/lib/widgets/follows_lists_horizontal_list/widgets/follows_lists_horizontal_list_item.dart b/lib/widgets/follows_lists_horizontal_list/widgets/follows_lists_horizontal_list_item.dart index 369263134..a649929b2 100644 --- a/lib/widgets/follows_lists_horizontal_list/widgets/follows_lists_horizontal_list_item.dart +++ b/lib/widgets/follows_lists_horizontal_list/widgets/follows_lists_horizontal_list_item.dart @@ -12,18 +12,18 @@ import '../../../provider.dart'; class OBFollowsListHorizontalListItem extends StatelessWidget { final bool isSelected; final FollowsList followsList; - final OnFollowsListPressed onFollowsListPressed; + final OnFollowsListPressed? onFollowsListPressed; final bool wasPreviouslySelected; OBFollowsListHorizontalListItem(this.followsList, - {@required this.onFollowsListPressed, - this.isSelected, + {required this.onFollowsListPressed, + this.isSelected = false, this.wasPreviouslySelected = false}); @override Widget build(BuildContext context) { LocalizationService _localizationService = OpenbookProvider.of(context).localizationService; - int usersCount = followsList.followsCount; + int usersCount = followsList.followsCount!; if (wasPreviouslySelected) { if (!isSelected) { @@ -37,7 +37,7 @@ class OBFollowsListHorizontalListItem extends StatelessWidget { return GestureDetector( onTap: () { if (this.onFollowsListPressed != null) { - this.onFollowsListPressed(followsList); + this.onFollowsListPressed!(followsList); } }, child: ConstrainedBox( @@ -48,7 +48,7 @@ class OBFollowsListHorizontalListItem extends StatelessWidget { Stack( overflow: Overflow.visible, children: [ - OBEmoji(followsList.emoji, size: OBEmojiSize.large,), + OBEmoji(followsList.emoji!, size: OBEmojiSize.large,), Positioned( child: OBCheckbox( value: isSelected, @@ -62,7 +62,7 @@ class OBFollowsListHorizontalListItem extends StatelessWidget { height: 10, ), OBText( - followsList.name, + followsList.name!, maxLines: 1, style: TextStyle( fontSize: 14, diff --git a/lib/widgets/follows_lists_horizontal_list/widgets/new_follows_list_horizontal_list_item.dart b/lib/widgets/follows_lists_horizontal_list/widgets/new_follows_list_horizontal_list_item.dart index 972871d14..9aa6c7d16 100644 --- a/lib/widgets/follows_lists_horizontal_list/widgets/new_follows_list_horizontal_list_item.dart +++ b/lib/widgets/follows_lists_horizontal_list/widgets/new_follows_list_horizontal_list_item.dart @@ -5,7 +5,7 @@ import 'package:flutter/material.dart'; class OBNewFollowsListHorizontalListItem extends StatelessWidget { final VoidCallback onPressed; - OBNewFollowsListHorizontalListItem({@required this.onPressed}); + OBNewFollowsListHorizontalListItem({required this.onPressed}); @override Widget build(BuildContext context) { diff --git a/lib/widgets/hashtag.dart b/lib/widgets/hashtag.dart index 6be0fd015..100316952 100644 --- a/lib/widgets/hashtag.dart +++ b/lib/widgets/hashtag.dart @@ -7,14 +7,14 @@ import 'package:flutter_advanced_networkimage/provider.dart'; class OBHashtag extends StatelessWidget { final Hashtag hashtag; - final ValueChanged onPressed; - final TextStyle textStyle; - final String rawHashtagName; - final EdgeInsets discoDisplayMargin; + final ValueChanged? onPressed; + final TextStyle? textStyle; + final String? rawHashtagName; + final EdgeInsets? discoDisplayMargin; const OBHashtag( - {Key key, - @required this.hashtag, + {Key? key, + required this.hashtag, this.onPressed, this.discoDisplayMargin, this.textStyle, @@ -29,7 +29,7 @@ class OBHashtag extends StatelessWidget { if (textStyle != null) finalTextStyle = finalTextStyle.merge(textStyle); - String finalHashtagText = rawHashtagName ?? hashtag.name; + String finalHashtagText = rawHashtagName ?? hashtag.name!; return StreamBuilder( stream: openbookProvider @@ -53,12 +53,12 @@ class OBHashtag extends StatelessWidget { } Widget _buildDiscoHashtag( - {@required BuildContext context, - @required TextStyle style, - @required String text, - @required OpenbookProviderState provider}) { + {required BuildContext context, + required TextStyle style, + required String text, + required OpenbookProviderState provider}) { Color hashtagBackgroundColor = - provider.utilsService.parseHexColor(hashtag.color); + provider.utilsService.parseHexColor(hashtag.color!); Widget content = Container( decoration: BoxDecoration( @@ -79,9 +79,9 @@ class OBHashtag extends StatelessWidget { } Widget _buildTraditionalHashtag( - {@required BuildContext context, - @required TextStyle style, - @required String text}) { + {required BuildContext context, + required TextStyle style, + required String text}) { Widget content = OBText( '#$text', style: style, @@ -94,7 +94,7 @@ class OBHashtag extends StatelessWidget { Widget _wrapWithGestureDetector(Widget child) { return GestureDetector( - onTap: onPressed != null ? () => onPressed(hashtag) : null, + onTap: onPressed != null ? () => onPressed!(hashtag) : null, child: child); } @@ -108,7 +108,7 @@ class OBHashtag extends StatelessWidget { child: Image( height: 15, image: - AdvancedNetworkImage(hashtag.emoji.image, useDiskCache: true), + AdvancedNetworkImage(hashtag.emoji!.image!, useDiskCache: true), )), ], ); diff --git a/lib/widgets/http_list.dart b/lib/widgets/http_list.dart index 46bbd07fe..7207bdc20 100644 --- a/lib/widgets/http_list.dart +++ b/lib/widgets/http_list.dart @@ -20,32 +20,32 @@ import 'checkbox.dart'; class OBHttpList extends StatefulWidget { final OBHttpListItemBuilder listItemBuilder; - final OBHttpListItemBuilder selectedListItemBuilder; - final OBHttpListItemBuilder searchResultListItemBuilder; - final OBHttpListSearcher listSearcher; + final OBHttpListItemBuilder? selectedListItemBuilder; + final OBHttpListItemBuilder? searchResultListItemBuilder; + final OBHttpListSearcher? listSearcher; final OBHttpListRefresher listRefresher; final OBHttpListOnScrollLoader listOnScrollLoader; - final OBHttpListController controller; + final OBHttpListController? controller; final String resourceSingularName; final String resourcePluralName; final EdgeInsets padding; - final IndexedWidgetBuilder separatorBuilder; + final IndexedWidgetBuilder? separatorBuilder; final ScrollPhysics physics; - final List prependedItems; - final OBHttpListSecondaryRefresher secondaryRefresher; - final OBHttpListSelectionChangedListener onSelectionChanged; - final OBHttpListSelectionChangedListener onSelectionSubmitted; - final OBHttpListSelectionSubmitter selectionSubmitter; + final List? prependedItems; + final OBHttpListSecondaryRefresher? secondaryRefresher; + final OBHttpListSelectionChangedListener? onSelectionChanged; + final OBHttpListSelectionChangedListener? onSelectionSubmitted; + final OBHttpListSelectionSubmitter? selectionSubmitter; final bool hasSearchBar; final bool isSelectable; const OBHttpList( - {Key key, - @required this.listItemBuilder, - @required this.listRefresher, - @required this.listOnScrollLoader, - @required this.resourceSingularName, - @required this.resourcePluralName, + {Key? key, + required this.listItemBuilder, + required this.listRefresher, + required this.listOnScrollLoader, + required this.resourceSingularName, + required this.resourcePluralName, this.physics = const ClampingScrollPhysics(), this.padding = const EdgeInsets.all(0), this.listSearcher, @@ -69,37 +69,37 @@ class OBHttpList extends StatefulWidget { } class OBHttpListState extends State> { - ToastService _toastService; - LocalizationService _localizationService; + late ToastService _toastService; + late LocalizationService _localizationService; GlobalKey _listRefreshIndicatorKey = GlobalKey(); - ScrollController _listScrollController; + late ScrollController _listScrollController; List _list = []; List _listSearchResults = []; List _listSelection = []; - List _prependedItems; - - bool _hasSearch; - String _searchQuery; - bool _needsBootstrap; - bool _refreshInProgress; - bool _searchRequestInProgress; - bool _selectionSubmissionInProgress; - bool _loadingFinished; - bool _wasBootstrapped; - - CancelableOperation _searchOperation; - CancelableOperation _refreshOperation; - CancelableOperation _loadMoreOperation; - CancelableOperation _submitSelectionOperation; + late List _prependedItems; + + late bool _hasSearch; + late String _searchQuery; + late bool _needsBootstrap; + late bool _refreshInProgress; + late bool _searchRequestInProgress; + late bool _selectionSubmissionInProgress; + late bool _loadingFinished; + late bool _wasBootstrapped; + + CancelableOperation? _searchOperation; + CancelableOperation? _refreshOperation; + CancelableOperation? _loadMoreOperation; + CancelableOperation? _submitSelectionOperation; ScrollPhysics noItemsPhysics = const AlwaysScrollableScrollPhysics(); @override void initState() { super.initState(); - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); _listScrollController = ScrollController(); _loadingFinished = false; _needsBootstrap = true; @@ -111,7 +111,7 @@ class OBHttpListState extends State> { _list = []; _searchQuery = ''; _prependedItems = - widget.prependedItems != null ? widget.prependedItems.toList() : []; + widget.prependedItems != null ? widget.prependedItems!.toList() : []; } void insertListItem(T listItem, @@ -144,9 +144,9 @@ class OBHttpListState extends State> { void dispose() { super.dispose(); - if (_searchOperation != null) _searchOperation.cancel(); - if (_loadMoreOperation != null) _loadMoreOperation.cancel(); - if (_refreshOperation != null) _refreshOperation.cancel(); + if (_searchOperation != null) _searchOperation!.cancel(); + if (_loadMoreOperation != null) _loadMoreOperation!.cancel(); + if (_refreshOperation != null) _refreshOperation!.cancel(); _submitSelectionOperation?.cancel(); } @@ -246,7 +246,7 @@ class OBHttpListState extends State> { }, child: widget.separatorBuilder != null ? ListView.separated( - separatorBuilder: widget.separatorBuilder, + separatorBuilder: widget.separatorBuilder!, padding: widget.padding, physics: physics, itemCount: listItemCount, @@ -283,7 +283,7 @@ class OBHttpListState extends State> { T listItem = _listSearchResults[index]; Widget listItemWidget = - widget.searchResultListItemBuilder(context, listItem); + widget.searchResultListItemBuilder!(context, listItem); if (!widget.isSelectable) return listItemWidget; @@ -301,7 +301,7 @@ class OBHttpListState extends State> { delegate: OBHttpListLoadMoreDelegate(_localizationService), child: widget.separatorBuilder != null ? ListView.separated( - separatorBuilder: widget.separatorBuilder, + separatorBuilder: widget.separatorBuilder!, controller: _listScrollController, physics: widget.physics, padding: widget.padding, @@ -320,8 +320,8 @@ class OBHttpListState extends State> { Widget _buildNoList() { List items = []; - if (widget.prependedItems != null && widget.prependedItems.isNotEmpty) { - items.addAll(widget.prependedItems); + if (widget.prependedItems != null && widget.prependedItems!.isNotEmpty) { + items.addAll(widget.prependedItems!); } items.add(Column( @@ -395,7 +395,7 @@ class OBHttpListState extends State> { void _bootstrap() async { Future.delayed(Duration(milliseconds: 0), () async { - await _refreshWithRefreshIndicator(); + _refreshWithRefreshIndicator(); setState(() { _wasBootstrapped = true; }); @@ -403,18 +403,18 @@ class OBHttpListState extends State> { } Future _refreshList() async { - if (_refreshOperation != null) _refreshOperation.cancel(); + if (_refreshOperation != null) _refreshOperation!.cancel(); _setLoadingFinished(false); _setRefreshInProgress(true); try { List> refreshFutures = [widget.listRefresher()]; if (widget.secondaryRefresher != null) - refreshFutures.add(widget.secondaryRefresher()); + refreshFutures.add(widget.secondaryRefresher!()); _refreshOperation = CancelableOperation.fromFuture(Future.wait(refreshFutures)); - List results = await _refreshOperation.value; + List results = await _refreshOperation?.value; List list = results[0]; _setList(list); @@ -429,9 +429,12 @@ class OBHttpListState extends State> { Future refreshList( {bool shouldScrollToTop = false, bool shouldUseRefreshIndicator = false}) async { - await (shouldUseRefreshIndicator - ? _refreshWithRefreshIndicator() - : _refreshList()); + if (shouldUseRefreshIndicator) { + _refreshWithRefreshIndicator(); + } else { + _refreshList(); + } + if (shouldScrollToTop && _listScrollController.hasClients && _listScrollController.offset != 0) { @@ -441,10 +444,10 @@ class OBHttpListState extends State> { void _refreshWithRefreshIndicator(){ // Deactivate if active - _listRefreshIndicatorKey.currentState.deactivate(); + _listRefreshIndicatorKey.currentState?.deactivate(); // Activate - _listRefreshIndicatorKey.currentState.show(); + _listRefreshIndicatorKey.currentState?.show(); } Future _loadMoreListItems() async { @@ -456,7 +459,7 @@ class OBHttpListState extends State> { try { _loadMoreOperation = CancelableOperation.fromFuture(widget.listOnScrollLoader(_list)); - List moreListItems = await _loadMoreOperation.value; + List moreListItems = await _loadMoreOperation?.value; if (moreListItems.length == 0) { _setLoadingFinished(true); @@ -485,15 +488,15 @@ class OBHttpListState extends State> { } Future _searchWithQuery(String query) async { - if (_searchOperation != null) _searchOperation.cancel(); + if (_searchOperation != null) _searchOperation!.cancel(); _setSearchRequestInProgress(true); try { _searchOperation = - CancelableOperation.fromFuture(widget.listSearcher(_searchQuery)); + CancelableOperation.fromFuture(widget.listSearcher!(_searchQuery)); - List listSearchResults = await _searchOperation.value; + List listSearchResults = await _searchOperation?.value; _setListSearchResults(listSearchResults); } catch (error) { _onError(error); @@ -508,14 +511,14 @@ class OBHttpListState extends State> { } void _onSubmitSelection() async { - if (_submitSelectionOperation != null) _submitSelectionOperation.cancel(); + if (_submitSelectionOperation != null) _submitSelectionOperation!.cancel(); _setSelectionSubmissionInProgress(true); try { _submitSelectionOperation = CancelableOperation.fromFuture( - widget.selectionSubmitter(_listSelection)); - widget.onSelectionSubmitted(_listSelection); + widget.selectionSubmitter!(_listSelection)); + widget.onSelectionSubmitted!(_listSelection); } catch (error) { _onError(error); } finally { @@ -532,7 +535,7 @@ class OBHttpListState extends State> { } if (widget.onSelectionChanged != null) - widget.onSelectionChanged(_listSelection.toList()); + widget.onSelectionChanged!(_listSelection.toList()); } void _resetListSearchResults() { @@ -617,8 +620,8 @@ class OBHttpListState extends State> { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.trans('error__unknown_error'), context: context); } else { _toastService.error( message: _localizationService.trans('error__unknown_error'), @@ -629,7 +632,7 @@ class OBHttpListState extends State> { } class OBHttpListController { - OBHttpListState _state; + OBHttpListState? _state; void attach(OBHttpListState state) { _state = state; @@ -637,47 +640,47 @@ class OBHttpListController { void insertListItem(T listItem, {bool shouldScrollToTop = true, bool shouldRefresh = false}) { - if (!_isAttached() || !_state.mounted) { + if (!_isAttached() || !_state!.mounted) { debugPrint('Tried to insertListItem in unattached OBHttpList'); return; } - _state.insertListItem(listItem, + _state!.insertListItem(listItem, shouldScrollToTop: shouldScrollToTop, shouldRefresh: shouldRefresh); } void removeListItem(T listItem) { - if (!_isAttached() || !_state.mounted) return; - _state.removeListItem(listItem); + if (!_isAttached() || !_state!.mounted) return; + _state!.removeListItem(listItem); } void scrollToTop() { - if (!_isAttached() || !_state.mounted) return; - _state.scrollToTop(); + if (!_isAttached() || !_state!.mounted) return; + _state!.scrollToTop(); } Future refresh( {bool shouldScrollToTop = false, bool shouldUseRefreshIndicator = false}) async { - if (_state == null || !_state.mounted) return; - _state.refreshList( + if (_state == null || !_state!.mounted) return; + _state!.refreshList( shouldScrollToTop: shouldScrollToTop, shouldUseRefreshIndicator: shouldUseRefreshIndicator); } Future search(String query) { - return _state._onSearch(query); + return _state!._onSearch(query); } Future clearSearch() { - return _state._onSearch(''); + return _state!._onSearch(''); } bool hasItems() { - return _state._list.isNotEmpty; + return _state!._list.isNotEmpty; } T firstItem() { - return _state._list.first; + return _state!._list.first; } bool _isAttached() { diff --git a/lib/widgets/icon.dart b/lib/widgets/icon.dart index 07e8819c1..794704d31 100644 --- a/lib/widgets/icon.dart +++ b/lib/widgets/icon.dart @@ -6,11 +6,11 @@ enum OBIconSize { small, medium, large, extraLarge } class OBIcon extends StatelessWidget { final OBIconData iconData; - final OBIconSize size; - final double customSize; - final Color color; - final OBIconThemeColor themeColor; - final String semanticLabel; + final OBIconSize? size; + final double? customSize; + final Color? color; + final OBIconThemeColor? themeColor; + final String? semanticLabel; static const double EXTRA_LARGE = 45.0; static const double LARGE_SIZE = 30.0; @@ -18,7 +18,7 @@ class OBIcon extends StatelessWidget { static const double SMALL_SIZE = 15.0; const OBIcon(this.iconData, - {Key key, + {Key? key, this.size, this.customSize, this.color, @@ -29,10 +29,10 @@ class OBIcon extends StatelessWidget { @override Widget build(BuildContext context) { - double iconSize; + late double iconSize; if (this.customSize != null) { - iconSize = this.customSize; + iconSize = this.customSize!; } else { var finalSize = size ?? OBIconSize.medium; switch (finalSize) { @@ -65,35 +65,35 @@ class OBIcon extends StatelessWidget { Widget icon; if (iconData.nativeIcon != null) { - Color iconColor; - Gradient iconGradient; + Color? iconColor; + Gradient? iconGradient; if (color != null) { - iconColor = color; + iconColor = color!; } else { switch (themeColor) { case OBIconThemeColor.primary: - iconColor = themeValueParser.parseColor(theme.primaryColor); + iconColor = themeValueParser.parseColor(theme!.primaryColor); break; case OBIconThemeColor.primaryText: iconColor = - themeValueParser.parseColor(theme.primaryTextColor); + themeValueParser.parseColor(theme!.primaryTextColor); break; case OBIconThemeColor.secondaryText: iconColor = - themeValueParser.parseColor(theme.secondaryTextColor); + themeValueParser.parseColor(theme!.secondaryTextColor); break; case OBIconThemeColor.primaryAccent: iconGradient = - themeValueParser.parseGradient(theme.primaryAccentColor); + themeValueParser.parseGradient(theme!.primaryAccentColor); break; case OBIconThemeColor.danger: iconGradient = - themeValueParser.parseGradient(theme.dangerColor); + themeValueParser.parseGradient(theme!.dangerColor); break; default: iconColor = - themeValueParser.parseColor(theme.primaryTextColor); + themeValueParser.parseColor(theme!.primaryTextColor); } } @@ -108,7 +108,7 @@ class OBIcon extends StatelessWidget { icon = ShaderMask( blendMode: BlendMode.srcIn, shaderCallback: (Rect bounds) { - return iconGradient.createShader(bounds); + return iconGradient!.createShader(bounds); }, child: Icon( iconData.nativeIcon, @@ -118,7 +118,7 @@ class OBIcon extends StatelessWidget { ); } } else { - String iconName = iconData.filename; + String iconName = iconData.filename!; icon = Image.asset('assets/images/icons/$iconName', height: iconSize); } @@ -292,8 +292,8 @@ class OBIcons { @immutable class OBIconData { - final String filename; - final IconData nativeIcon; + final String? filename; + final IconData? nativeIcon; const OBIconData({ this.nativeIcon, diff --git a/lib/widgets/icon_button.dart b/lib/widgets/icon_button.dart index 6bd9f2445..d0e96cf45 100644 --- a/lib/widgets/icon_button.dart +++ b/lib/widgets/icon_button.dart @@ -3,11 +3,11 @@ import 'package:flutter/material.dart'; class OBIconButton extends StatelessWidget { final OBIconData iconData; - final OBIconSize size; - final double customSize; - final Color color; - final OBIconThemeColor themeColor; - final VoidCallback onPressed; + final OBIconSize? size; + final double? customSize; + final Color? color; + final OBIconThemeColor? themeColor; + final VoidCallback? onPressed; OBIconButton(this.iconData, {this.size, diff --git a/lib/widgets/linear_progress_indicator.dart b/lib/widgets/linear_progress_indicator.dart index 0f1543b73..662213134 100644 --- a/lib/widgets/linear_progress_indicator.dart +++ b/lib/widgets/linear_progress_indicator.dart @@ -16,7 +16,7 @@ class OBLinearProgressIndicator extends StatelessWidget { var theme = snapshot.data; var primaryColor = - themeValueParserService.parseColor(theme.primaryColor); + themeValueParserService.parseColor(theme!.primaryColor); final bool isDarkPrimaryColor = primaryColor.computeLuminance() < 0.179; diff --git a/lib/widgets/link_preview.dart b/lib/widgets/link_preview.dart index 07a94d128..a04f41ce1 100644 --- a/lib/widgets/link_preview.dart +++ b/lib/widgets/link_preview.dart @@ -20,12 +20,12 @@ import 'package:flutter_svg/svg.dart'; import 'package:async/async.dart'; class OBLinkPreview extends StatefulWidget { - final LinkPreview linkPreview; - final String link; - final ValueChanged onLinkPreviewRetrieved; + final LinkPreview? linkPreview; + final String? link; + final ValueChanged? onLinkPreviewRetrieved; const OBLinkPreview( - {this.linkPreview, this.link, this.onLinkPreviewRetrieved}); + {required this.linkPreview, this.link, this.onLinkPreviewRetrieved}); @override State createState() { @@ -37,24 +37,24 @@ class OBLinkPreviewState extends State { static double iconSize = 16; static double linkPreviewHeight = 300; - LinkPreview _linkPreview; - UrlLauncherService _urlLauncherService; - LocalizationService _localizationService; - UtilsService _utilsService; - UserService _userService; - UserPreferencesService _userPreferencesService; + LinkPreview? _linkPreview; + late UrlLauncherService _urlLauncherService; + late LocalizationService _localizationService; + late UtilsService _utilsService; + late UserService _userService; + late UserPreferencesService _userPreferencesService; - HttpieService _httpieService; + late HttpieService _httpieService; - bool _linkPreviewRequestInProgress; - CancelableOperation _fetchLinkPreviewOperation; + late bool _linkPreviewRequestInProgress; + CancelableOperation? _fetchLinkPreviewOperation; - bool _needsBootstrap; - bool _failedToPreviewLink; + late bool _needsBootstrap; + late bool _failedToPreviewLink; - StreamSubscription _linkPreviewsAreEnabledChangeSubscription; + StreamSubscription? _linkPreviewsAreEnabledChangeSubscription; - bool _linkPreviewsAreEnabled; + late bool _linkPreviewsAreEnabled; @override void initState() { @@ -70,16 +70,16 @@ class OBLinkPreviewState extends State { String previousLinkUrl; if (oldWidget.link != null) { - previousLinkUrl = oldWidget.link; + previousLinkUrl = oldWidget.link!; } else { - previousLinkUrl = oldWidget.linkPreview.url; + previousLinkUrl = oldWidget.linkPreview!.url!; } String newLinkUrl; if (widget.link != null) { - newLinkUrl = widget.link; + newLinkUrl = widget.link!; } else { - newLinkUrl = widget.linkPreview.url; + newLinkUrl = widget.linkPreview!.url!; } if (previousLinkUrl != newLinkUrl) { @@ -227,7 +227,7 @@ class OBLinkPreviewState extends State { ], )), onTap: () { - _urlLauncherService.launchUrl(_linkPreview.url ?? widget.link); + _urlLauncherService.launchUrl(_linkPreview?.url ?? widget.link!); }, ); } @@ -243,7 +243,7 @@ class OBLinkPreviewState extends State { } Widget _buildPreviewImage() { - if (_linkPreview.image == null) { + if (_linkPreview?.image == null) { return Semantics( label: 'Link preview image', child: Container( @@ -257,13 +257,13 @@ class OBLinkPreviewState extends State { ); } - return _buildLinkPreviewImageFromUrl(_linkPreview.image.url); + return _buildLinkPreviewImageFromUrl(_linkPreview!.image!.url!); } Widget _buildLinkPreviewImageFromUrl(String url) { String proxiedImageUrl = _utilsService.getProxiedContentLink(url); - String proxyAuthToken = _httpieService.getAuthorizationToken(); + String proxyAuthToken = _httpieService.getAuthorizationToken()!; return _buildCrossCompatImageForSource(proxiedImageUrl, semanticsLabel: 'Link preview image', @@ -281,7 +281,7 @@ class OBLinkPreviewState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ - _linkPreview.icon != null + _linkPreview?.icon != null ? _buildLinkPreviewIcon() : const SizedBox(), OBSecondaryText(_getLinkPreviewDomain(), @@ -291,22 +291,22 @@ class OBLinkPreviewState extends State { ], ), ), - _linkPreview.title != null + _linkPreview?.title != null ? Padding( padding: const EdgeInsets.only(top: 5), child: OBText( - _linkPreview.title, + _linkPreview!.title!, maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(fontWeight: FontWeight.bold), ), ) : const SizedBox(), - _linkPreview.description != null + _linkPreview?.description != null ? Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: OBSecondaryText( - _linkPreview.description, + _linkPreview!.description!, size: OBTextSize.mediumSecondary, maxLines: 3, overflow: TextOverflow.ellipsis, @@ -322,8 +322,8 @@ class OBLinkPreviewState extends State { Widget iconWidget; String proxiedIconImageUrl = - _utilsService.getProxiedContentLink(_linkPreview.icon.url); - String proxyAuthToken = _httpieService.getAuthorizationToken(); + _utilsService.getProxiedContentLink(_linkPreview!.icon!.url!); + String proxyAuthToken = _httpieService.getAuthorizationToken()!; iconWidget = _buildCrossCompatImageForSource(proxiedIconImageUrl, semanticsLabel: 'Icon', @@ -343,7 +343,7 @@ class OBLinkPreviewState extends State { } Widget _buildCrossCompatImageForSource(String imageSource, - {String semanticsLabel, Map headers}) { + {String? semanticsLabel, Map? headers}) { String iconExtension = imageSource.split('.').last; Widget image; @@ -401,7 +401,7 @@ class OBLinkPreviewState extends State { if (_fetchLinkPreviewOperation != null) return; _setLinkPreviewRequestInProgress(true); - String link = widget.link; + String link = widget.link!; debugLog('Retrieving link preview for url: $link'); @@ -409,10 +409,10 @@ class OBLinkPreviewState extends State { _fetchLinkPreviewOperation = CancelableOperation.fromFuture(_userService.previewLink(link: link)); - LinkPreview linkPreview = await _fetchLinkPreviewOperation.value; + LinkPreview? linkPreview = await _fetchLinkPreviewOperation?.value; if (widget.onLinkPreviewRetrieved != null) - widget.onLinkPreviewRetrieved(linkPreview); + widget.onLinkPreviewRetrieved!(linkPreview); if (linkPreview != null) { _setLinkPreview(linkPreview); debugLog('Retrieved link preview for url: $link'); @@ -436,9 +436,9 @@ class OBLinkPreviewState extends State { } String _getLinkPreviewDomain() { - return (_linkPreview != null && _linkPreview.domain != null - ? _linkPreview.domain - : Uri.parse(widget.link).host) + return (_linkPreview != null && _linkPreview!.domain != null + ? _linkPreview!.domain! + : Uri.parse(widget.link!).host) .toUpperCase(); } diff --git a/lib/widgets/load_more.dart b/lib/widgets/load_more.dart index 6ea163584..5f650e599 100644 --- a/lib/widgets/load_more.dart +++ b/lib/widgets/load_more.dart @@ -18,24 +18,24 @@ class LoadMore extends StatefulWidget { /// return true is refresh success /// /// return false or null is fail - final FutureCallBack onLoadMore; + final FutureCallBack? onLoadMore; /// if [isFinish] is true, then loadMoreWidget status is [LoadMoreStatus.nomore]. final bool isFinish; /// see [LoadMoreDelegate] - final LoadMoreDelegate delegate; + final LoadMoreDelegate? delegate; /// see [LoadMoreTextBuilder] - final LoadMoreTextBuilder textBuilder; + final LoadMoreTextBuilder? textBuilder; /// when [whenEmptyLoad] is true, and when listView children length is 0,or the itemCount is 0,not build loadMoreWidget final bool whenEmptyLoad; const LoadMore({ - Key key, - @required this.child, - @required this.onLoadMore, + Key? key, + required this.child, + required this.onLoadMore, this.textBuilder, this.isFinish = false, this.delegate, @@ -68,7 +68,7 @@ class _LoadMoreState extends State { return child; } if (child is ListView) { - return _buildListView(child); + return _buildListView(child as ListView); } return child; } @@ -79,16 +79,16 @@ class _LoadMoreState extends State { var delegate = listView.childrenDelegate; outer: if (delegate is SliverChildBuilderDelegate) { - SliverChildBuilderDelegate delegate = listView.childrenDelegate; + SliverChildBuilderDelegate delegate = listView.childrenDelegate as SliverChildBuilderDelegate; if (!widget.whenEmptyLoad && delegate.estimatedChildCount == 0) { break outer; } - var viewCount = delegate.estimatedChildCount + 1; + var viewCount = (delegate.estimatedChildCount ?? 0) + 1; IndexedWidgetBuilder builder = (context, index) { if (index == viewCount - 1) { return _buildLoadMoreView(); } - return delegate.builder(context, index); + return delegate.builder(context, index)!; }; return ListView.builder( @@ -108,7 +108,7 @@ class _LoadMoreState extends State { shrinkWrap: listView.shrinkWrap, ); } else if (delegate is SliverChildListDelegate) { - SliverChildListDelegate delegate = listView.childrenDelegate; + SliverChildListDelegate delegate = listView.childrenDelegate as SliverChildListDelegate; if (!widget.whenEmptyLoad && delegate.estimatedChildCount == 0) { break outer; @@ -185,8 +185,12 @@ class _LoadMoreState extends State { } void loadMore() { + if (widget.onLoadMore == null) { + return; + } + _updateStatus(LoadMoreStatus.loading); - widget.onLoadMore().then((v) { + widget.onLoadMore!().then((v) { if (v == true) { // 成功,切换状态为空闲 _updateStatus(LoadMoreStatus.idle); @@ -225,10 +229,10 @@ class DefaultLoadMoreView extends StatefulWidget { final LoadMoreDelegate delegate; final LoadMoreTextBuilder textBuilder; const DefaultLoadMoreView({ - Key key, + Key? key, this.status = LoadMoreStatus.idle, - @required this.delegate, - @required this.textBuilder, + required this.delegate, + required this.textBuilder, }) : super(key: key); @override diff --git a/lib/widgets/loadmore/loadmore_delegate.dart b/lib/widgets/loadmore/loadmore_delegate.dart index 3e3821e27..facc908ce 100644 --- a/lib/widgets/loadmore/loadmore_delegate.dart +++ b/lib/widgets/loadmore/loadmore_delegate.dart @@ -12,7 +12,7 @@ class OBHomePostsLoadMoreDelegate extends LoadMoreDelegate { String text = builder(status); if (status == LoadMoreStatus.fail) { - return OBRetryTile(text: 'Tap to retry loading posts'); + return OBRetryTile(text: 'Tap to retry loading posts', onWantsToRetry: () {},); } if (status == LoadMoreStatus.idle) { // No clue why is this even a state. diff --git a/lib/widgets/markdown.dart b/lib/widgets/markdown.dart index 37f4a48f0..dd526aa83 100644 --- a/lib/widgets/markdown.dart +++ b/lib/widgets/markdown.dart @@ -9,11 +9,11 @@ class OBMarkdown extends StatelessWidget { static final double pFontSize = 16; final String data; - final OBTheme theme; + final OBTheme? theme; final bool onlyBody; const OBMarkdown( - {Key key, @required this.data, this.theme, this.onlyBody = false}) + {Key? key, required this.data, this.theme, this.onlyBody = false}) : super(key: key); @override @@ -23,7 +23,7 @@ class OBMarkdown extends StatelessWidget { var urlLauncherService = openbookProvider.urlLauncherService; if (theme != null) - return _buildWithTheme(theme, + return _buildWithTheme(theme!, context: context, themeValueParserService: themeValueParserService, urlLauncherService: urlLauncherService); @@ -35,7 +35,7 @@ class OBMarkdown extends StatelessWidget { initialData: themeService.getActiveTheme(), builder: (BuildContext context, AsyncSnapshot snapshot) { var currentTheme = snapshot.data; - return _buildWithTheme(currentTheme, + return _buildWithTheme(currentTheme!, context: context, themeValueParserService: themeValueParserService, urlLauncherService: urlLauncherService); @@ -44,9 +44,9 @@ class OBMarkdown extends StatelessWidget { } Widget _buildWithTheme(OBTheme theme, - {@required ThemeValueParserService themeValueParserService, - @required UrlLauncherService urlLauncherService, - @required BuildContext context}) { + {required ThemeValueParserService themeValueParserService, + required UrlLauncherService urlLauncherService, + required BuildContext context}) { var primaryColor = themeValueParserService.parseColor(theme.primaryColor); final bool isDarkPrimaryColor = primaryColor.computeLuminance() < 0.179; Color primaryTextColor = @@ -65,22 +65,22 @@ class OBMarkdown extends StatelessWidget { code: new TextStyle( color: primaryTextColor, fontFamily: "monospace", - fontSize: flutterTheme.textTheme.body1.fontSize * 0.85), - h1: flutterTheme.textTheme.headline + fontSize: flutterTheme.textTheme.bodyText2!.fontSize! * 0.85), + h1: flutterTheme.textTheme.headline5! .copyWith(color: primaryTextColor, fontWeight: FontWeight.bold), - h2: flutterTheme.textTheme.title + h2: flutterTheme.textTheme.headline6! .copyWith(color: primaryTextColor, fontWeight: FontWeight.bold), - h3: flutterTheme.textTheme.subhead + h3: flutterTheme.textTheme.subtitle1! .copyWith(color: primaryTextColor, fontWeight: FontWeight.bold), - h4: flutterTheme.textTheme.body2 + h4: flutterTheme.textTheme.bodyText1! .copyWith(color: primaryTextColor, fontWeight: FontWeight.bold), - h5: flutterTheme.textTheme.body2 + h5: flutterTheme.textTheme.bodyText1! .copyWith(color: primaryTextColor, fontWeight: FontWeight.bold), - h6: flutterTheme.textTheme.body2 + h6: flutterTheme.textTheme.bodyText1! .copyWith(color: primaryTextColor, fontWeight: FontWeight.bold), em: const TextStyle(fontStyle: FontStyle.italic), strong: const TextStyle(fontWeight: FontWeight.bold), - img: flutterTheme.textTheme.body1.copyWith(color: primaryTextColor), + img: flutterTheme.textTheme.bodyText2!.copyWith(color: primaryTextColor), codeblockDecoration: new BoxDecoration( color: Colors.grey.shade100, borderRadius: new BorderRadius.circular(2.0)), @@ -90,15 +90,19 @@ class OBMarkdown extends StatelessWidget { ), blockSpacing: 10.0, listIndent: 32.0, - blockquotePadding: 10.0, - p: flutterTheme.textTheme.body1 + blockquotePadding: EdgeInsets.all(10.0), + p: flutterTheme.textTheme.bodyText2! .copyWith(color: primaryTextColor, fontSize: pFontSize), a: TextStyle(color: actionsForegroundColor, fontSize: pFontSize), blockquoteDecoration: BoxDecoration( color: accentColor, borderRadius: new BorderRadius.circular(5.0))); - Function onTapLink = (String tappedLink) async { + void Function(String, String?, String) onTapLink = (String text, String? tappedLink, String title) async { + if (tappedLink == null) { + return; + } + bool canLaunchUrl = await urlLauncherService.canLaunchUrl(tappedLink); if (canLaunchUrl) { urlLauncherService.launchUrl(tappedLink); diff --git a/lib/widgets/moderated_object_status_circle.dart b/lib/widgets/moderated_object_status_circle.dart index fc0262112..ffe0c3972 100644 --- a/lib/widgets/moderated_object_status_circle.dart +++ b/lib/widgets/moderated_object_status_circle.dart @@ -11,7 +11,7 @@ class OBModeratedObjectStatusCircle extends StatelessWidget { static double statusCircleSize = 10; static String pendingColor = '#f48c42'; - const OBModeratedObjectStatusCircle({Key key, @required this.status}) + const OBModeratedObjectStatusCircle({Key? key, required this.status}) : super(key: key); @override @@ -19,7 +19,7 @@ class OBModeratedObjectStatusCircle extends StatelessWidget { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); OBTheme currentTheme = openbookProvider.themeService.getActiveTheme(); - String circleColor; + late String circleColor; switch (status) { case ModeratedObjectStatus.rejected: circleColor = currentTheme.dangerColor; diff --git a/lib/widgets/more_buttons/hashtag_more_button.dart b/lib/widgets/more_buttons/hashtag_more_button.dart index 14b2a2ac7..68050d209 100644 --- a/lib/widgets/more_buttons/hashtag_more_button.dart +++ b/lib/widgets/more_buttons/hashtag_more_button.dart @@ -7,7 +7,7 @@ import 'package:Okuna/services/bottom_sheet.dart'; class OBHashtagMoreButton extends StatelessWidget { final Hashtag hashtag; - const OBHashtagMoreButton({Key key, @required this.hashtag}) + const OBHashtagMoreButton({Key? key, required this.hashtag}) : super(key: key); @override @@ -16,7 +16,7 @@ class OBHashtagMoreButton extends StatelessWidget { stream: hashtag.updateSubject, initialData: hashtag, builder: (BuildContext context, AsyncSnapshot snapshot) { - var hashtag = snapshot.data; + var hashtag = snapshot.data!; return IconButton( icon: const OBIcon( diff --git a/lib/widgets/nav_bars/colored_nav_bar.dart b/lib/widgets/nav_bars/colored_nav_bar.dart index cdf8d2d80..2610593a2 100644 --- a/lib/widgets/nav_bars/colored_nav_bar.dart +++ b/lib/widgets/nav_bars/colored_nav_bar.dart @@ -7,16 +7,16 @@ import 'package:flutter/material.dart'; class OBColoredNavBar extends StatelessWidget implements ObstructingPreferredSizeWidget { final Color color; - final Color textColor; - final Color actionsColor; - final Widget leading; - final Widget middle; - final Widget trailing; - final String title; + final Color? textColor; + final Color? actionsColor; + final Widget? leading; + final Widget? middle; + final Widget? trailing; + final String? title; const OBColoredNavBar( - {Key key, - @required this.color, + {Key? key, + required this.color, this.leading, this.trailing, this.title, @@ -47,7 +47,7 @@ class OBColoredNavBar extends StatelessWidget leading: leading, middle: middle ?? Text( - title, + title ?? '', style: TextStyle(color: textColor ?? finalActionsColor), ), transitionBetweenRoutes: false, diff --git a/lib/widgets/nav_bars/image_nav_bar.dart b/lib/widgets/nav_bars/image_nav_bar.dart index 63fda0665..0b8967c15 100644 --- a/lib/widgets/nav_bars/image_nav_bar.dart +++ b/lib/widgets/nav_bars/image_nav_bar.dart @@ -9,15 +9,15 @@ import 'package:flutter_advanced_networkimage/provider.dart'; class OBImageNavBar extends StatelessWidget implements ObstructingPreferredSizeWidget { final String imageSrc; - final Color textColor; - final Widget leading; - final Widget middle; - final Widget trailing; - final String title; + final Color? textColor; + final Widget? leading; + final Widget? middle; + final Widget? trailing; + final String? title; const OBImageNavBar( - {Key key, - @required this.imageSrc, + {Key? key, + required this.imageSrc, this.leading, this.trailing, this.title, @@ -45,12 +45,11 @@ class OBImageNavBar extends StatelessWidget ), ), OBCupertinoNavigationBar( - border: null, leading: leading, actionsForegroundColor: Colors.white, middle: middle ?? Text( - title, + title ?? '', style: TextStyle(color: textColor ?? Colors.white), ), transitionBetweenRoutes: false, diff --git a/lib/widgets/nav_bars/themed_nav_bar.dart b/lib/widgets/nav_bars/themed_nav_bar.dart index 7f07080b9..288727b5a 100644 --- a/lib/widgets/nav_bars/themed_nav_bar.dart +++ b/lib/widgets/nav_bars/themed_nav_bar.dart @@ -7,11 +7,11 @@ import 'package:flutter/material.dart'; /// A navigation bar that uses the current theme colours class OBThemedNavigationBar extends StatelessWidget implements ObstructingPreferredSizeWidget { - final Widget leading; - final String title; - final Widget trailing; - final String previousPageTitle; - final Widget middle; + final Widget? leading; + final String? title; + final Widget? trailing; + final String? previousPageTitle; + final Widget? middle; OBThemedNavigationBar({ this.leading, @@ -34,7 +34,7 @@ class OBThemedNavigationBar extends StatelessWidget var theme = snapshot.data; Color actionsForegroundColor = themeValueParserService - .parseGradient(theme.primaryAccentColor) + .parseGradient(theme!.primaryAccentColor) .colors[1]; Color actionsColor = actionsForegroundColor != null @@ -55,7 +55,7 @@ class OBThemedNavigationBar extends StatelessWidget middle: middle ?? (title != null ? OBText( - title, + title!, ) : const SizedBox()), transitionBetweenRoutes: false, diff --git a/lib/widgets/new_post_data_uploader.dart b/lib/widgets/new_post_data_uploader.dart index c2362c591..4d9d6da10 100644 --- a/lib/widgets/new_post_data_uploader.dart +++ b/lib/widgets/new_post_data_uploader.dart @@ -25,10 +25,10 @@ class OBNewPostDataUploader extends StatefulWidget { final ValueChanged onCancelled; const OBNewPostDataUploader( - {Key key, - @required this.data, - @required this.onPostPublished, - @required this.onCancelled}) + {Key? key, + required this.data, + required this.onPostPublished, + required this.onCancelled}) : super(key: key); @override @@ -39,22 +39,22 @@ class OBNewPostDataUploader extends StatefulWidget { class OBNewPostDataUploaderState extends State with AutomaticKeepAliveClientMixin { - UserService _userService; - LocalizationService _localizationService; - MediaService _mediaPickerService; + late UserService _userService; + late LocalizationService _localizationService; + late MediaService _mediaPickerService; - bool _needsBootstrap; - OBPostUploaderStatus _status; + late bool _needsBootstrap; + late OBPostUploaderStatus _status; String _statusMessage = ''; static double mediaPreviewSize = 40; - Timer _checkPostStatusTimer; + Timer? _checkPostStatusTimer; - CancelableOperation _getPostStatusOperation; - CancelableOperation _uploadPostOperation; - OBNewPostData _data; + CancelableOperation? _getPostStatusOperation; + CancelableOperation? _uploadPostOperation; + late OBNewPostData _data; @override void initState() { @@ -146,7 +146,7 @@ class OBNewPostDataUploaderState extends State _data.createdDraftPost = await _createPost(); } - if (_data.remainingMediaToCompress.isNotEmpty) { + if (_data.remainingMediaToCompress != null && _data.remainingMediaToCompress!.isNotEmpty) { _setStatusMessage( _localizationService.post_uploader__compressing_media); _setStatus(OBPostUploaderStatus.compressingPostMedia); @@ -176,14 +176,14 @@ class OBNewPostDataUploaderState extends State Timer.periodic(new Duration(seconds: 1), (timer) async { if (_getPostStatusOperation != null) return; _getPostStatusOperation = CancelableOperation.fromFuture( - _userService.getPostStatus(post: _data.createdDraftPost)); - OBPostStatus status = await _getPostStatusOperation.value; + _userService.getPostStatus(post: _data.createdDraftPost!)); + OBPostStatus status = await _getPostStatusOperation?.value; debugLog( 'Polling for post published status, got status: ${status.toString()}'); _data.createdDraftPostStatus = status; if (_data.createdDraftPostStatus == OBPostStatus.published) { debugLog('Received post status is published'); - _checkPostStatusTimer.cancel(); + _checkPostStatusTimer?.cancel(); _getPublishedPost(); } _getPostStatusOperation = null; @@ -195,8 +195,8 @@ class OBNewPostDataUploaderState extends State if (error is HttpieConnectionRefusedError) { _setStatusMessage(error.toHumanReadableMessage()); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _setStatusMessage(errorMessage); + String? errorMessage = await error.toHumanReadableMessage(); + _setStatusMessage(errorMessage ?? _localizationService.error__unknown_error); } else { _setStatusMessage( _localizationService.post_uploader__generic_upload_failed); @@ -213,7 +213,7 @@ class OBNewPostDataUploaderState extends State if (_data.community != null) { debugLog('Creating community post'); - draftPost = await _userService.createPostForCommunity(_data.community, + draftPost = await _userService.createPostForCommunity(_data.community!, text: _data.text, isDraft: true); } else { debugLog('Creating circles post'); @@ -231,7 +231,7 @@ class OBNewPostDataUploaderState extends State debugLog('Retrieving the published post'); Post publishedPost = - await _userService.getPostWithUuid(_data.createdDraftPost.uuid); + await _userService.getPostWithUuid(_data.createdDraftPost!.uuid!); widget.onPostPublished(publishedPost, widget.data); _removeMediaFromCache(); } @@ -240,12 +240,12 @@ class OBNewPostDataUploaderState extends State debugLog('Compressing post media'); return Future.wait( - _data.remainingMediaToCompress.map(_compressPostMediaItem).toList()); + _data.remainingMediaToCompress!.map(_compressPostMediaItem).toList()); } Future _compressPostMediaItem(File postMediaItem) async { - String mediaMime = lookupMimeType(postMediaItem.path); - String mediaMimeType = mediaMime.split('/')[0]; + String? mediaMime = lookupMimeType(postMediaItem.path); + String? mediaMimeType = mediaMime?.split('/')[0]; if (mediaMimeType == 'image') { File compressedImage = @@ -268,7 +268,7 @@ class OBNewPostDataUploaderState extends State } else { debugLog('Unsupported media type for compression'); } - _data.remainingMediaToCompress.remove(postMediaItem); + _data.remainingMediaToCompress!.remove(postMediaItem); } Future _addPostMedia() { @@ -280,7 +280,7 @@ class OBNewPostDataUploaderState extends State } Future _uploadPostMediaItem(File file) async { - await _userService.addMediaToPost(file: file, post: _data.createdDraftPost); + await _userService.addMediaToPost(file: file, post: _data.createdDraftPost!); _data.remainingCompressedMediaToUpload.remove(file); } @@ -294,7 +294,7 @@ class OBNewPostDataUploaderState extends State builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data == null) return const SizedBox(); - File mediaThumbnail = snapshot.data; + File mediaThumbnail = snapshot.data!; return ClipRRect( borderRadius: BorderRadius.circular(8.0), child: Image( @@ -309,13 +309,13 @@ class OBNewPostDataUploaderState extends State } Future _getMediaThumbnail() async { - if (_data.mediaThumbnail != null) return _data.mediaThumbnail; + if (_data.mediaThumbnail != null) return _data.mediaThumbnail!; - File mediaToPreview = _data.media.first; - File mediaThumbnail; + File mediaToPreview = _data.media!.first; + late File mediaThumbnail; - String mediaMime = lookupMimeType(mediaToPreview.path); - String mediaMimeType = mediaMime.split('/')[0]; + String? mediaMime = lookupMimeType(mediaToPreview.path); + String? mediaMimeType = mediaMime?.split('/')[0]; if (mediaMimeType == 'image') { mediaThumbnail = mediaToPreview; @@ -406,7 +406,7 @@ class OBNewPostDataUploaderState extends State if (_data.createdDraftPost != null) { debugLog('Deleting post'); try { - await _userService.deletePost(_data.createdDraftPost); + await _userService.deletePost(_data.createdDraftPost!); debugLog('Successfully deleted post'); } catch (error) { // If it doesnt work, will get cleaned up by a scheduled job @@ -424,15 +424,15 @@ class OBNewPostDataUploaderState extends State _data.media?.forEach((File mediaObject) { if (mediaObject.existsSync()) mediaObject.delete(); }); - _data.compressedMedia?.forEach((File mediaObject) => mediaObject.delete()); - if (_data.mediaThumbnail != _data.media.first) { + _data.compressedMedia.forEach((File mediaObject) => mediaObject.delete()); + if (_data.mediaThumbnail != _data.media?.first) { _data.mediaThumbnail?.delete(); } } Future _publishPost() async { debugLog('Publishing post'); - return _userService.publishPost(post: _data.createdDraftPost); + return _userService.publishPost(post: _data.createdDraftPost!); } void _setStatus(OBPostUploaderStatus status) { @@ -452,8 +452,8 @@ class OBNewPostDataUploaderState extends State } void _ensurePostStatusTimerIsCancelled() { - if (_checkPostStatusTimer != null && _checkPostStatusTimer.isActive) - _checkPostStatusTimer.cancel(); + if (_checkPostStatusTimer != null && _checkPostStatusTimer!.isActive) + _checkPostStatusTimer?.cancel(); } void debugLog(String log) { @@ -465,32 +465,32 @@ class OBNewPostDataUploaderState extends State } class OBNewPostData { - String text; - List media; - Community community; - List circles; + String? text; + List? media; + Community? community; + List? circles; // State persistence variables - Post createdDraftPost; - OBPostStatus createdDraftPostStatus; - List remainingMediaToCompress; + Post? createdDraftPost; + OBPostStatus? createdDraftPostStatus; + List? remainingMediaToCompress; List compressedMedia = []; List remainingCompressedMediaToUpload = []; bool postPublishRequested = false; - File mediaThumbnail; + File? mediaThumbnail; - String _cachedKey; + String? _cachedKey; OBNewPostData({this.text, this.media, this.community, this.circles}) { - remainingMediaToCompress = media.toList(); + remainingMediaToCompress = media?.toList(); } bool hasMedia() { - return media != null && media.isNotEmpty; + return media != null && media!.isNotEmpty; } List getMedia() { - return hasMedia() ? media.toList() : []; + return hasMedia() ? media!.toList() : []; } void setCircles(List circles) { @@ -502,16 +502,16 @@ class OBNewPostData { } List getCircles() { - return circles.toList(); + return circles!.toList(); } String getUniqueKey() { - if (_cachedKey != null) return _cachedKey; + if (_cachedKey != null) return _cachedKey!; String key = ''; - if (text != null) key += text; + if (text != null) key += text!; if (hasMedia()) { - media.forEach((File mediaItem) { + media!.forEach((File mediaItem) { key += mediaItem.path; }); } @@ -521,7 +521,7 @@ class OBNewPostData { _cachedKey = digest.toString(); - return _cachedKey; + return _cachedKey!; } } diff --git a/lib/widgets/page_scaffold.dart b/lib/widgets/page_scaffold.dart index 8a884efb3..2b4c7e3d1 100644 --- a/lib/widgets/page_scaffold.dart +++ b/lib/widgets/page_scaffold.dart @@ -18,11 +18,11 @@ import 'package:flutter/widgets.dart'; class OBCupertinoPageScaffold extends StatelessWidget { /// Creates a layout for pages with a navigation bar at the top. const OBCupertinoPageScaffold({ - Key key, + Key? key, this.navigationBar, this.backgroundColor = CupertinoColors.white, this.resizeToAvoidBottomInset = true, - @required this.child, + required this.child, }) : assert(child != null), assert(resizeToAvoidBottomInset != null), super(key: key); @@ -35,7 +35,7 @@ class OBCupertinoPageScaffold extends StatelessWidget { /// /// The scaffold assumes the navigation bar will consume the [MediaQuery] top padding. // TODO(xster): document its page transition animation when ready - final ObstructingPreferredSizeWidget navigationBar; + final ObstructingPreferredSizeWidget? navigationBar; /// Widget to show in the main content area. /// @@ -70,7 +70,7 @@ class OBCupertinoPageScaffold extends StatelessWidget { // TODO(xster): Use real size after partial layout instead of preferred size. // https://github.com/flutter/flutter/issues/12912 final double topPadding = - navigationBar.preferredSize.height + existingMediaQuery.padding.top; + navigationBar!.preferredSize.height + existingMediaQuery.padding.top; // Propagate bottom padding and include viewInsets if appropriate @@ -87,7 +87,7 @@ class OBCupertinoPageScaffold extends StatelessWidget { // If navigation bar is opaquely obstructing, directly shift the main content // down. If translucent, let main content draw behind navigation bar but hint the // obstructed area. - if (navigationBar.shouldFullyObstruct(context)) { + if (navigationBar!.shouldFullyObstruct(context)) { paddedContent = Padding( padding: EdgeInsets.only(top: topPadding, bottom: bottomPadding), child: child, @@ -115,7 +115,7 @@ class OBCupertinoPageScaffold extends StatelessWidget { top: 0.0, left: 0.0, right: 0.0, - child: navigationBar, + child: navigationBar!, )); } diff --git a/lib/widgets/post/post.dart b/lib/widgets/post/post.dart index fa750c9c8..df8c6620f 100644 --- a/lib/widgets/post/post.dart +++ b/lib/widgets/post/post.dart @@ -14,17 +14,17 @@ import 'package:inview_notifier_list/inview_notifier_list.dart'; class OBPost extends StatelessWidget { final Post post; final ValueChanged onPostDeleted; - final ValueChanged onPostIsInView; - final OnTextExpandedChange onTextExpandedChange; - final String inViewId; - final Function onCommunityExcluded; - final Function onUndoCommunityExcluded; - final ValueChanged onPostCommunityExcludedFromProfilePosts; + final ValueChanged? onPostIsInView; + final OnTextExpandedChange? onTextExpandedChange; + final String? inViewId; + final Function? onCommunityExcluded; + final Function? onUndoCommunityExcluded; + final ValueChanged? onPostCommunityExcludedFromProfilePosts; final OBPostDisplayContext displayContext; const OBPost(this.post, - {Key key, - @required this.onPostDeleted, + {Key? key, + required this.onPostDeleted, this.onPostIsInView, this.onCommunityExcluded, this.onUndoCommunityExcluded, @@ -36,9 +36,9 @@ class OBPost extends StatelessWidget { @override Widget build(BuildContext context) { - String postInViewId; + String? postInViewId; if (this.displayContext == OBPostDisplayContext.topPosts) - postInViewId = inViewId + '_' + post.id.toString(); + postInViewId = (inViewId ?? '') + '_' + post.id.toString(); _bootstrap(context, postInViewId); @@ -75,15 +75,15 @@ class OBPost extends StatelessWidget { ); } - void _bootstrap(BuildContext context, String postInViewId) { - InViewState _inViewState; + void _bootstrap(BuildContext context, String? postInViewId) { + InViewState? _inViewState; if (postInViewId != null) { _inViewState = InViewNotifierList.of(context); - _inViewState.addContext(context: context, id: postInViewId); + _inViewState!.addContext(context: context, id: postInViewId); if (this.displayContext == OBPostDisplayContext.topPosts) { _inViewState.addListener( - () => _onInViewStateChanged(_inViewState, postInViewId)); + () => _onInViewStateChanged(_inViewState!, postInViewId)); } } } @@ -91,7 +91,7 @@ class OBPost extends StatelessWidget { void _onInViewStateChanged(InViewState _inViewState, String postInViewId) { final bool isInView = _inViewState.inView(postInViewId); if (isInView) { - if (onPostIsInView != null) onPostIsInView(post); + if (onPostIsInView != null) onPostIsInView!(post); } } } diff --git a/lib/widgets/post/widgets/post-actions/post_actions.dart b/lib/widgets/post/widgets/post-actions/post_actions.dart index 019fa65e7..e6f3bfae5 100644 --- a/lib/widgets/post/widgets/post-actions/post_actions.dart +++ b/lib/widgets/post/widgets/post-actions/post_actions.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; class OBPostActions extends StatelessWidget { final Post _post; - final VoidCallback onWantsToCommentPost; + final VoidCallback? onWantsToCommentPost; OBPostActions(this._post, {this.onWantsToCommentPost}); @@ -24,7 +24,7 @@ class OBPostActions extends StatelessWidget { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); canDisableOrEnableCommentsForPost = openbookProvider.userService .getLoggedInUser() - .canDisableOrEnableCommentsForPost(_post); + ?.canDisableOrEnableCommentsForPost(_post) ?? false; } if (commentsEnabled || canDisableOrEnableCommentsForPost) { diff --git a/lib/widgets/post/widgets/post-actions/widgets/post_action_comment.dart b/lib/widgets/post/widgets/post-actions/widgets/post_action_comment.dart index 75c114960..39ab3195e 100644 --- a/lib/widgets/post/widgets/post-actions/widgets/post_action_comment.dart +++ b/lib/widgets/post/widgets/post-actions/widgets/post_action_comment.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; class OBPostActionComment extends StatelessWidget { final Post _post; - final VoidCallback onWantsToCommentPost; + final VoidCallback? onWantsToCommentPost; OBPostActionComment(this._post, {this.onWantsToCommentPost}); @@ -35,7 +35,7 @@ class OBPostActionComment extends StatelessWidget { ), onPressed: () { if (onWantsToCommentPost != null) { - onWantsToCommentPost(); + onWantsToCommentPost!(); } else { navigationService.navigateToCommentPost( post: _post, context: context); diff --git a/lib/widgets/post/widgets/post-actions/widgets/post_action_react.dart b/lib/widgets/post/widgets/post-actions/widgets/post_action_react.dart index 03877b9b1..406389164 100644 --- a/lib/widgets/post/widgets/post-actions/widgets/post_action_react.dart +++ b/lib/widgets/post/widgets/post-actions/widgets/post_action_react.dart @@ -23,9 +23,9 @@ class OBPostActionReact extends StatefulWidget { } class OBPostActionReactState extends State { - CancelableOperation _clearPostReactionOperation; - bool _clearPostReactionInProgress; - LocalizationService _localizationService; + CancelableOperation? _clearPostReactionOperation; + late bool _clearPostReactionInProgress; + late LocalizationService _localizationService; @override void initState() { @@ -37,7 +37,7 @@ class OBPostActionReactState extends State { void dispose() { super.dispose(); if (_clearPostReactionOperation != null) - _clearPostReactionOperation.cancel(); + _clearPostReactionOperation!.cancel(); } @override @@ -49,8 +49,8 @@ class OBPostActionReactState extends State { stream: widget.post.updateSubject, initialData: widget.post, builder: (BuildContext context, AsyncSnapshot snapshot) { - Post post = snapshot.data; - PostReaction reaction = post.reaction; + Post post = snapshot.data!; + PostReaction? reaction = post.reaction; bool hasReaction = reaction != null; Widget buttonChild = Row( @@ -59,9 +59,9 @@ class OBPostActionReactState extends State { hasReaction ? CachedNetworkImage( height: 18.0, - imageUrl: reaction.getEmojiImage(), + imageUrl: reaction.getEmojiImage()!, errorWidget: - (BuildContext context, String url, Object error) { + (BuildContext context, String url, dynamic error) { return SizedBox( child: Center(child: Text('?')), ); @@ -75,7 +75,7 @@ class OBPostActionReactState extends State { width: 10.0, ), OBText( - hasReaction ? reaction.getEmojiKeyword() : _localizationService.post__action_react, + hasReaction ? reaction.getEmojiKeyword()! : _localizationService.post__action_react, style: TextStyle( color: hasReaction ? Colors.white : null, fontWeight: hasReaction ? FontWeight.bold : FontWeight.normal, @@ -112,9 +112,9 @@ class OBPostActionReactState extends State { try { _clearPostReactionOperation = CancelableOperation.fromFuture( openbookProvider.userService.deletePostReaction( - postReaction: widget.post.reaction, post: widget.post)); + postReaction: widget.post.reaction!, post: widget.post)); - await _clearPostReactionOperation.value; + await _clearPostReactionOperation?.value; widget.post.clearReaction(); } catch (error) { _onError(error: error, openbookProvider: openbookProvider); @@ -131,16 +131,16 @@ class OBPostActionReactState extends State { } void _onError( - {@required error, - @required OpenbookProviderState openbookProvider}) async { + {required error, + required OpenbookProviderState openbookProvider}) async { ToastService toastService = openbookProvider.toastService; if (error is HttpieConnectionRefusedError) { toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/widgets/post/widgets/post-body/post_body.dart b/lib/widgets/post/widgets/post-body/post_body.dart index 2bee1ef87..02216db04 100644 --- a/lib/widgets/post/widgets/post-body/post_body.dart +++ b/lib/widgets/post/widgets/post-body/post_body.dart @@ -7,11 +7,11 @@ import 'package:flutter/material.dart'; class OBPostBody extends StatelessWidget { final Post post; - final OnTextExpandedChange onTextExpandedChange; - final String inViewId; + final OnTextExpandedChange? onTextExpandedChange; + final String? inViewId; const OBPostBody(this.post, - {Key key, this.onTextExpandedChange, this.inViewId}) + {Key? key, this.onTextExpandedChange, this.inViewId}) : super(key: key); @override diff --git a/lib/widgets/post/widgets/post-body/widgets/post_body_link_preview.dart b/lib/widgets/post/widgets/post-body/widgets/post_body_link_preview.dart index befccbb78..64e1bb222 100644 --- a/lib/widgets/post/widgets/post-body/widgets/post_body_link_preview.dart +++ b/lib/widgets/post/widgets/post-body/widgets/post_body_link_preview.dart @@ -4,36 +4,37 @@ import 'package:Okuna/widgets/link_preview.dart'; import 'package:flutter/material.dart'; class OBPostBodyLinkPreview extends StatelessWidget { - final Post post; + final Post? post; - const OBPostBodyLinkPreview({Key key, this.post}) : super(key: key); + const OBPostBodyLinkPreview({Key? key, this.post}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only(bottom: 10), child: StreamBuilder( - stream: post.updateSubject, + stream: post?.updateSubject, initialData: post, builder: _buildLinkPreview), ); } Widget _buildLinkPreview(BuildContext context, AsyncSnapshot snapshot) { - if (post.linkPreview != null) { + if (post?.linkPreview != null) { return OBLinkPreview( - linkPreview: post.linkPreview, + linkPreview: post!.linkPreview, ); } - var linkToPreview = post.getLinkToPreview(); + var linkToPreview = post!.getLinkToPreview()!; return OBLinkPreview( + linkPreview: null, link: linkToPreview.link, onLinkPreviewRetrieved: _onLinkPreviewRetrieved); } - void _onLinkPreviewRetrieved(LinkPreview linkPreview) { - post.setLinkPreview(linkPreview); + void _onLinkPreviewRetrieved(LinkPreview? linkPreview) { + post?.setLinkPreview(linkPreview); } } diff --git a/lib/widgets/post/widgets/post-body/widgets/post_body_media/post_body_media.dart b/lib/widgets/post/widgets/post-body/widgets/post_body_media/post_body_media.dart index c2ed3cb82..31ccffb03 100644 --- a/lib/widgets/post/widgets/post-body/widgets/post_body_media/post_body_media.dart +++ b/lib/widgets/post/widgets/post-body/widgets/post_body_media/post_body_media.dart @@ -18,10 +18,10 @@ import 'package:flutter_advanced_networkimage/provider.dart'; import 'package:flutter_advanced_networkimage/transition.dart'; class OBPostBodyMedia extends StatefulWidget { - final Post post; - final String inViewId; + final Post? post; + final String? inViewId; - const OBPostBodyMedia({Key key, this.post, this.inViewId}) : super(key: key); + const OBPostBodyMedia({Key? key, this.post, this.inViewId}) : super(key: key); @override OBPostBodyMediaState createState() { @@ -30,17 +30,17 @@ class OBPostBodyMedia extends StatefulWidget { } class OBPostBodyMediaState extends State { - UserService _userService; - LocalizationService _localizationService; - bool _needsBootstrap; - String _errorMessage; + late UserService _userService; + late LocalizationService _localizationService; + late bool _needsBootstrap; + late String _errorMessage; - CancelableOperation _retrievePostMediaOperation; - bool _retrievePostMediaInProgress; + CancelableOperation? _retrievePostMediaOperation; + late bool _retrievePostMediaInProgress; - double _mediaHeight; - double _mediaWidth; - bool _mediaIsConstrained; + double? _mediaHeight; + double? _mediaWidth; + late bool _mediaIsConstrained; @override void initState() { @@ -116,17 +116,17 @@ class OBPostBodyMediaState extends State { Widget _buildMediaItems() { return StreamBuilder( - stream: widget.post.updateSubject, + stream: widget.post!.updateSubject, initialData: widget.post, builder: (BuildContext context, AsyncSnapshot snapshot) { - List postMediaItems = widget.post.getMedia(); + List postMediaItems = widget.post!.getMedia() ?? []; return _buildPostMediaItems(postMediaItems); }, ); } Widget _buildPostMediaItemsThumbnail() { - String thumbnailUrl = widget.post.mediaThumbnail; + String? thumbnailUrl = widget.post?.mediaThumbnail; return TransitionToImage( height: _mediaHeight, @@ -136,7 +136,7 @@ class OBPostBodyMediaState extends State { ), fit: BoxFit.cover, alignment: Alignment.center, - image: AdvancedNetworkImage(thumbnailUrl, + image: AdvancedNetworkImage(thumbnailUrl ?? '', useDiskCache: true, fallbackAssetImage: 'assets/images/fallbacks/post-fallback.png', retryLimit: 3, @@ -188,13 +188,13 @@ class OBPostBodyMediaState extends State { double screenHeight = MediaQuery.of(context).size.height; double maxBoxHeight = screenHeight * .70; - double imageAspectRatio = widget.post.mediaWidth / widget.post.mediaHeight; + double imageAspectRatio = widget.post!.mediaWidth! / widget.post!.mediaHeight!; double imageHeight = (screenWidth / imageAspectRatio); _mediaHeight = min(imageHeight, maxBoxHeight); if (_mediaHeight == maxBoxHeight) _mediaIsConstrained = true; _mediaWidth = screenWidth; - if (widget.post.media != null) { + if (widget.post?.media != null) { _retrievePostMediaInProgress = false; return; } @@ -206,9 +206,9 @@ class OBPostBodyMediaState extends State { _setRetrievePostMediaInProgress(true); try { _retrievePostMediaOperation = CancelableOperation.fromFuture( - _userService.getMediaForPost(post: widget.post), onCancel: _onRetrievePostMediaOperationCancelled); - PostMediaList mediaList = await _retrievePostMediaOperation.value; - widget.post.setMedia(mediaList); + _userService.getMediaForPost(post: widget.post!), onCancel: _onRetrievePostMediaOperationCancelled); + PostMediaList mediaList = await _retrievePostMediaOperation!.value; + widget.post!.setMedia(mediaList); } catch (error) { _onError(error); } finally { @@ -225,8 +225,8 @@ class OBPostBodyMediaState extends State { if (error is HttpieConnectionRefusedError) { _setErrorMessage(error.toHumanReadableMessage()); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _setErrorMessage(errorMessage); + String? errorMessage = await error.toHumanReadableMessage(); + _setErrorMessage(errorMessage ?? _localizationService.error__unknown_error); } else { _setErrorMessage(_localizationService.error__unknown_error); throw error; diff --git a/lib/widgets/post/widgets/post-body/widgets/post_body_media/widgets/post_body_image.dart b/lib/widgets/post/widgets/post-body/widgets/post_body_media/widgets/post_body_image.dart index 02ee4807b..b64365fcf 100644 --- a/lib/widgets/post/widgets/post-body/widgets/post_body_media/widgets/post_body_image.dart +++ b/lib/widgets/post/widgets/post-body/widgets/post_body_media/widgets/post_body_image.dart @@ -8,13 +8,13 @@ import 'package:flutter/material.dart'; import 'dart:math'; class OBPostBodyImage extends StatelessWidget { - final PostImage postImage; + final PostImage? postImage; final bool hasExpandButton; - final double height; - final double width; + final double? height; + final double? width; const OBPostBodyImage( - {Key key, + {Key? key, this.postImage, this.hasExpandButton = false, this.height, @@ -23,10 +23,10 @@ class OBPostBodyImage extends StatelessWidget { @override Widget build(BuildContext context) { - String imageUrl = postImage.image; + String imageUrl = postImage!.image!; List stackItems = [ - _buildImageWidget(imageUrl: imageUrl, width: width, height: height) + _buildImageWidget(imageUrl: imageUrl, width: width!, height: height!) ]; if (hasExpandButton) { @@ -45,12 +45,12 @@ class OBPostBodyImage extends StatelessWidget { ); } - Widget _buildImageWidget({String imageUrl, double height, double width}) { + Widget _buildImageWidget({String? imageUrl, double? height, double? width}) { return Image( height: height, width: width, fit: BoxFit.cover, - image: AdvancedNetworkImage(imageUrl, + image: AdvancedNetworkImage(imageUrl ?? '', useDiskCache: true, fallbackAssetImage: 'assets/images/fallbacks/post-fallback.png', retryLimit: 3, diff --git a/lib/widgets/post/widgets/post-body/widgets/post_body_media/widgets/post_body_video.dart b/lib/widgets/post/widgets/post-body/widgets/post_body_media/widgets/post_body_video.dart index a6d9f63b4..93a984f06 100644 --- a/lib/widgets/post/widgets/post-body/widgets/post_body_media/widgets/post_body_video.dart +++ b/lib/widgets/post/widgets/post-body/widgets/post_body_media/widgets/post_body_video.dart @@ -10,16 +10,16 @@ import 'package:inview_notifier_list/inview_notifier_list.dart'; import 'package:async/async.dart'; class OBPostBodyVideo extends StatefulWidget { - final double height; - final double width; - final Post post; - final PostVideo postVideo; - final String inViewId; - final bool hasExpandButton; + final double? height; + final double? width; + final Post? post; + final PostVideo? postVideo; + final String? inViewId; + final bool? hasExpandButton; final bool isConstrained; const OBPostBodyVideo( - {Key key, + {Key? key, this.post, this.postVideo, this.inViewId, @@ -36,20 +36,20 @@ class OBPostBodyVideo extends StatefulWidget { } class OBPostVideoState extends State { - OBVideoPlayerController _obVideoPlayerController; - bool _needsBootstrap; - StreamSubscription _videosSoundSettingsChangeSubscription; - Navigator _navigator; - NavigatorObserver _navigatorObserver; - ModalRoute _route; - bool _wasPlaying; + late OBVideoPlayerController _obVideoPlayerController; + late bool _needsBootstrap; + StreamSubscription? _videosSoundSettingsChangeSubscription; + Navigator? _navigator; + NavigatorObserver? _navigatorObserver; + ModalRoute? _route; + bool? _wasPlaying; - bool _videosAutoPlayAreEnabled; - StreamSubscription _videosAutoPlayAreEnabledChangeSubscription; + late bool _videosAutoPlayAreEnabled; + StreamSubscription? _videosAutoPlayAreEnabledChangeSubscription; - CancelableOperation _digestInViewStateChangeOperation; + CancelableOperation? _digestInViewStateChangeOperation; - InViewState _inViewState; + InViewState? _inViewState; @override void initState() { @@ -66,21 +66,21 @@ class OBPostVideoState extends State { _videosSoundSettingsChangeSubscription?.cancel(); _digestInViewStateChangeOperation?.cancel(); _inViewState?.removeListener(_onInViewStateChanged); - _navigator.observers.remove(_navigatorObserver); + _navigator?.observers.remove(_navigatorObserver); } void _bootstrap(BuildContext context) async { if (widget.inViewId != null) { // Subscribe for visibility changes _inViewState = InViewNotifierList.of(context); - _inViewState.addContext(context: context, id: widget.inViewId); - _inViewState.addListener(_onInViewStateChanged); + _inViewState!.addContext(context: context, id: widget.inViewId!); + _inViewState!.addListener(_onInViewStateChanged); } _route = ModalRoute.of(context); _navigatorObserver = PostVideoNavigatorObserver(this); _navigator = Navigator.of(context).widget; - _navigator.observers.add(_navigatorObserver); + _navigator!.observers.add(_navigatorObserver!); // Subscribe for autoplay changes OpenbookProviderState openbookProvider = OpenbookProvider.of(context); @@ -112,22 +112,22 @@ class OBPostVideoState extends State { Widget _buildVideoPlayer() { OBVideoFormat videoFormat = - widget.postVideo.getVideoFormatOfType(OBVideoFormatType.mp4SD); + widget.postVideo!.getVideoFormatOfType(OBVideoFormatType.mp4SD)!; - String videoUrl = videoFormat.file; + String videoUrl = videoFormat.file!; return OBVideoPlayer( videoUrl: videoUrl, - thumbnailUrl: widget.postVideo.thumbnail, - height: widget.height, - width: widget.width, + thumbnailUrl: widget.postVideo!.thumbnail!, + height: widget.height!, + width: widget.width!, isConstrained: widget.isConstrained, controller: _obVideoPlayerController, ); } void _onInViewStateChanged() { - final bool isVideoInView = _inViewState.inView(widget.inViewId); + final bool isVideoInView = _inViewState?.inView(widget.inViewId!) ?? false; _digestInViewStateChangeOperation?.cancel(); _digestInViewStateChangeOperation = CancelableOperation.fromFuture( @@ -160,17 +160,17 @@ class OBPostVideoState extends State { } class PostVideoNavigatorObserver extends NavigatorObserver { - OBPostVideoState _state; + late OBPostVideoState _state; PostVideoNavigatorObserver(OBPostVideoState state) { _state = state; } @override - void didPush(Route route, Route previousRoute) { + void didPush(Route route, Route? previousRoute) { if (identical(previousRoute, _state._route)) { _state._wasPlaying = _state._obVideoPlayerController.isPlaying(); - if (_state._wasPlaying) { + if (_state._wasPlaying == true) { debugLog('Pausing video due to another route opened.'); _state._obVideoPlayerController.pause(); } @@ -178,11 +178,11 @@ class PostVideoNavigatorObserver extends NavigatorObserver { } @override - void didPop(Route route, Route previousRoute) { + void didPop(Route route, Route? previousRoute) { if (identical(previousRoute, _state._route) && _state != null && _state.mounted && - _state._wasPlaying != null && _state._wasPlaying) { + _state._wasPlaying != null && _state._wasPlaying!) { debugLog('Resuming video as blocking route has been popped.'); _state._obVideoPlayerController.play(); } diff --git a/lib/widgets/post/widgets/post-body/widgets/post_body_text.dart b/lib/widgets/post/widgets/post-body/widgets/post_body_text.dart index 25f9f51ab..89a0178c4 100644 --- a/lib/widgets/post/widgets/post-body/widgets/post_body_text.dart +++ b/lib/widgets/post/widgets/post-body/widgets/post_body_text.dart @@ -11,7 +11,7 @@ import 'package:flutter/services.dart'; class OBPostBodyText extends StatefulWidget { final Post post; - final OnTextExpandedChange onTextExpandedChange; + final OnTextExpandedChange? onTextExpandedChange; OBPostBodyText(this.post, {this.onTextExpandedChange}) : super(); @@ -24,12 +24,12 @@ class OBPostBodyText extends StatefulWidget { class OBPostBodyTextState extends State { static const int MAX_LENGTH_LIMIT = 1300; - ToastService _toastService; - UserService _userService; - LocalizationService _localizationService; - String _translatedText; - bool _translationInProgress; - bool _needsBootstrap; + late ToastService _toastService; + late UserService _userService; + late LocalizationService _localizationService; + String? _translatedText; + late bool _translationInProgress; + late bool _needsBootstrap; @override void initState() { @@ -76,7 +76,7 @@ class OBPostBodyTextState extends State { } Future _translatePostText() async { - String translatedText; + late String translatedText; try { _setTranslationInProgress(true); translatedText = await _userService.translatePost(post: widget.post); @@ -89,7 +89,7 @@ class OBPostBodyTextState extends State { } Widget _buildActionablePostText() { - if (widget.post.isEdited != null && widget.post.isEdited) { + if (widget.post.isEdited != null && widget.post.isEdited!) { return OBCollapsibleSmartText( text: _translatedText != null ? _translatedText : widget.post.text, trailingSmartTextElement: SecondaryTextElement(' (edited)'), @@ -111,7 +111,7 @@ class OBPostBodyTextState extends State { Widget _buildTranslationButton() { if (_userService.getLoggedInUser() != null && - !_userService.getLoggedInUser().canTranslatePost(widget.post)) { + !_userService.getLoggedInUser()!.canTranslatePost(widget.post)) { return SizedBox(); } @@ -173,7 +173,7 @@ class OBPostBodyTextState extends State { }); } - void _setTranslatedText(String translatedText) { + void _setTranslatedText(String? translatedText) { setState(() { _translatedText = translatedText; }); @@ -181,4 +181,4 @@ class OBPostBodyTextState extends State { } typedef void OnTextExpandedChange( - {@required Post post, @required bool isExpanded}); + {required Post post, required bool isExpanded}); diff --git a/lib/widgets/post/widgets/post_circles.dart b/lib/widgets/post/widgets/post_circles.dart index e7997f8e8..db66ab016 100644 --- a/lib/widgets/post/widgets/post_circles.dart +++ b/lib/widgets/post/widgets/post_circles.dart @@ -37,8 +37,8 @@ class OBPostCircles extends StatelessWidget { ), ), ); - } else if (_post.isEncircled != null && _post.isEncircled) { - String postCreatorUsername = _post.creator.username; + } else if (_post.isEncircled != null && _post.isEncircled!) { + String postCreatorUsername = _post.creator!.username!; return Padding( padding: const EdgeInsets.only(left: 20, right: 20, top: 10), diff --git a/lib/widgets/post/widgets/post_comments/post_comments.dart b/lib/widgets/post/widgets/post_comments/post_comments.dart index 527ed7f2b..0740b9a25 100644 --- a/lib/widgets/post/widgets/post_comments/post_comments.dart +++ b/lib/widgets/post/widgets/post_comments/post_comments.dart @@ -19,7 +19,7 @@ class OBPostComments extends StatelessWidget { stream: _post.updateSubject, initialData: _post, builder: (BuildContext context, AsyncSnapshot snapshot) { - int commentsCount = _post.commentsCount; + int? commentsCount = _post.commentsCount; var openbookProvider = OpenbookProvider.of(context); var navigationService = openbookProvider.navigationService; LocalizationService _localizationService = openbookProvider.localizationService; @@ -32,7 +32,7 @@ class OBPostComments extends StatelessWidget { if (!areCommentsEnabled) { canDisableOrEnableCommentsForPost = openbookProvider.userService .getLoggedInUser() - .canDisableOrEnableCommentsForPost(_post); + ?.canDisableOrEnableCommentsForPost(_post) ?? false; } List rowItems = []; diff --git a/lib/widgets/post/widgets/post_header/post_header.dart b/lib/widgets/post/widgets/post_header/post_header.dart index 016eac51c..e4eb00a85 100644 --- a/lib/widgets/post/widgets/post_header/post_header.dart +++ b/lib/widgets/post/widgets/post_header/post_header.dart @@ -8,18 +8,18 @@ import 'package:flutter/material.dart'; class OBPostHeader extends StatelessWidget { final Post post; - final OnPostDeleted onPostDeleted; - final ValueChanged onPostReported; + final OnPostDeleted? onPostDeleted; + final ValueChanged? onPostReported; final bool hasActions; - final OBPostDisplayContext displayContext; - final Function onCommunityExcluded; - final Function onUndoCommunityExcluded; - final ValueChanged onPostCommunityExcludedFromProfilePosts; + final OBPostDisplayContext? displayContext; + final Function? onCommunityExcluded; + final Function? onUndoCommunityExcluded; + final ValueChanged? onPostCommunityExcludedFromProfilePosts; const OBPostHeader({ - Key key, + Key? key, this.onPostDeleted, - this.post, + required this.post, this.onPostReported, this.onCommunityExcluded, this.onUndoCommunityExcluded, @@ -42,7 +42,7 @@ class OBPostHeader extends StatelessWidget { onPostCommunityExcludedFromProfilePosts, displayContext: displayContext) : OBUserPostHeader(post, - onPostDeleted: onPostDeleted, + onPostDeleted: onPostDeleted!, onPostReported: onPostReported, displayContext: displayContext, hasActions: hasActions); diff --git a/lib/widgets/post/widgets/post_header/widgets/community_post_header/community_post_header.dart b/lib/widgets/post/widgets/post_header/widgets/community_post_header/community_post_header.dart index 9a2158bd4..0db258b5b 100644 --- a/lib/widgets/post/widgets/post_header/widgets/community_post_header/community_post_header.dart +++ b/lib/widgets/post/widgets/post_header/widgets/community_post_header/community_post_header.dart @@ -18,20 +18,20 @@ import 'package:flutter/material.dart'; class OBCommunityPostHeader extends StatelessWidget { final Post _post; - final OnPostDeleted onPostDeleted; - final ValueChanged onPostReported; + final OnPostDeleted? onPostDeleted; + final ValueChanged? onPostReported; final bool hasActions; - final OBPostDisplayContext displayContext; + final OBPostDisplayContext? displayContext; // What are we using these 2 for? - final Function onCommunityExcluded; - final Function onUndoCommunityExcluded; + final Function? onCommunityExcluded; + final Function? onUndoCommunityExcluded; - final ValueChanged onPostCommunityExcludedFromProfilePosts; + final ValueChanged? onPostCommunityExcludedFromProfilePosts; const OBCommunityPostHeader(this._post, - {Key key, - @required this.onPostDeleted, + {Key? key, + required this.onPostDeleted, this.onPostReported, this.hasActions = true, this.onCommunityExcluded, @@ -49,10 +49,10 @@ class OBCommunityPostHeader extends StatelessWidget { var utilsService = openbookProvider.utilsService; return StreamBuilder( - stream: _post.community.updateSubject, + stream: _post.community?.updateSubject, initialData: _post.community, builder: (BuildContext context, AsyncSnapshot snapshot) { - Community community = snapshot.data; + Community community = snapshot.data!; return displayContext == OBPostDisplayContext.ownProfilePosts || displayContext == OBPostDisplayContext.foreignProfilePosts @@ -72,31 +72,31 @@ class OBCommunityPostHeader extends StatelessWidget { } Widget _buildCommunityHighlightHeader( - {BuildContext context, - Community community, - NavigationService navigationService, - BottomSheetService bottomSheetService, - UtilsService utilsService, - LocalizationService localizationService}) { - String created = utilsService.timeAgo(_post.created, localizationService); + {BuildContext? context, + Community? community, + NavigationService? navigationService, + BottomSheetService? bottomSheetService, + UtilsService? utilsService, + LocalizationService? localizationService}) { + String created = utilsService!.timeAgo(_post.created!, localizationService!); return ListTile( leading: OBCommunityAvatar( - community: community, + community: community!, size: OBAvatarSize.medium, onPressed: () { - navigationService.navigateToCommunity( - community: community, context: context); + navigationService!.navigateToCommunity( + community: community, context: context!); }, ), trailing: hasActions ? IconButton( icon: const OBIcon(OBIcons.moreVertical), onPressed: () { - bottomSheetService.showPostActions( - context: context, + bottomSheetService!.showPostActions( + context: context!, post: _post, - displayContext: displayContext, + displayContext: displayContext ?? OBPostDisplayContext.timelinePosts, onCommunityExcluded: onCommunityExcluded, onUndoCommunityExcluded: onUndoCommunityExcluded, onPostCommunityExcludedFromProfilePosts: @@ -107,25 +107,25 @@ class OBCommunityPostHeader extends StatelessWidget { : null, title: GestureDetector( onTap: () { - navigationService.navigateToCommunity( - community: community, context: context); + navigationService!.navigateToCommunity( + community: community, context: context!); }, child: OBText( - community.title, + community.title!, style: TextStyle(fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis, ), ), subtitle: GestureDetector( onTap: () { - navigationService.navigateToCommunity( - community: community, context: context); + navigationService!.navigateToCommunity( + community: community, context: context!); }, child: Row( children: [ Expanded( child: OBSecondaryText( - 'c/' + community.name + ' · $created', + 'c/' + community.name! + ' · $created', style: TextStyle(fontSize: 12), overflow: TextOverflow.ellipsis, ), @@ -136,27 +136,27 @@ class OBCommunityPostHeader extends StatelessWidget { } Widget _buildUserHighlightHeader( - {BuildContext context, - Community community, - NavigationService navigationService, - BottomSheetService bottomSheetService}) { + {BuildContext? context, + Community? community, + NavigationService? navigationService, + BottomSheetService? bottomSheetService}) { return ListTile( leading: OBAvatar( - avatarUrl: _post.creator.getProfileAvatar(), + avatarUrl: _post.creator!.getProfileAvatar(), size: OBAvatarSize.medium, onPressed: () { - navigationService.navigateToUserProfile( - user: _post.creator, context: context); + navigationService!.navigateToUserProfile( + user: _post.creator!, context: context!); }, ), trailing: hasActions ? IconButton( icon: const OBIcon(OBIcons.moreVertical), onPressed: () { - bottomSheetService.showPostActions( - context: context, + bottomSheetService!.showPostActions( + context: context!, post: _post, - displayContext: displayContext, + displayContext: displayContext ?? OBPostDisplayContext.timelinePosts, onCommunityExcluded: onCommunityExcluded, onUndoCommunityExcluded: onUndoCommunityExcluded, onPostCommunityExcludedFromProfilePosts: @@ -167,18 +167,18 @@ class OBCommunityPostHeader extends StatelessWidget { : null, title: GestureDetector( onTap: () { - navigationService.navigateToCommunity( - community: community, context: context); + navigationService!.navigateToCommunity( + community: community!, context: context!); }, child: Row( children: [ OBCommunityAvatar( borderRadius: 4, customSize: 16, - community: community, + community: community!, onPressed: () { - navigationService.navigateToCommunity( - community: community, context: context); + navigationService!.navigateToCommunity( + community: community, context: context!); }, size: OBAvatarSize.extraSmall, ), @@ -187,7 +187,7 @@ class OBCommunityPostHeader extends StatelessWidget { ), Expanded( child: OBText( - 'c/' + community.name, + 'c/' + community.name!, style: TextStyle(fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis, ), @@ -198,8 +198,8 @@ class OBCommunityPostHeader extends StatelessWidget { subtitle: OBCommunityPostCreatorIdentifier( post: _post, onUsernamePressed: () { - navigationService.navigateToUserProfile( - user: _post.creator, context: context); + navigationService!.navigateToUserProfile( + user: _post.creator!, context: context!); }, ), ); diff --git a/lib/widgets/post/widgets/post_header/widgets/community_post_header/widgets/community_post_creator_identifier.dart b/lib/widgets/post/widgets/post_header/widgets/community_post_header/widgets/community_post_creator_identifier.dart index 9f1e90726..e53225914 100644 --- a/lib/widgets/post/widgets/post_header/widgets/community_post_header/widgets/community_post_creator_identifier.dart +++ b/lib/widgets/post/widgets/post_header/widgets/community_post_header/widgets/community_post_creator_identifier.dart @@ -13,9 +13,9 @@ class OBCommunityPostCreatorIdentifier extends StatelessWidget { static int postCommentMaxVisibleLength = 500; OBCommunityPostCreatorIdentifier({ - Key key, - @required this.onUsernamePressed, - @required this.post, + Key? key, + required this.onUsernamePressed, + required this.post, }) : super(key: key); @override @@ -30,14 +30,14 @@ class OBCommunityPostCreatorIdentifier extends StatelessWidget { stream: themeService.themeChange, initialData: themeService.getActiveTheme(), builder: (BuildContext context, AsyncSnapshot snapshot) { - OBTheme theme = snapshot.data; + OBTheme theme = snapshot.data!; Color secondaryTextColor = themeValueParserService.parseColor(theme.secondaryTextColor); - String commenterUsername = post.creator.username; - String commenterName = post.creator.getProfileName(); - String created = utilsService.timeAgo(post.created, localizationService); + String commenterUsername = post.creator!.username!; + String commenterName = post.creator!.getProfileName()!; + String created = utilsService.timeAgo(post.created!, localizationService); return GestureDetector( onTap: onUsernamePressed, diff --git a/lib/widgets/post/widgets/post_header/widgets/user_post_header/user_post_header.dart b/lib/widgets/post/widgets/post_header/widgets/user_post_header/user_post_header.dart index 637326123..421b0aaaa 100644 --- a/lib/widgets/post/widgets/post_header/widgets/user_post_header/user_post_header.dart +++ b/lib/widgets/post/widgets/post_header/widgets/user_post_header/user_post_header.dart @@ -14,13 +14,13 @@ import 'package:flutter/material.dart'; class OBUserPostHeader extends StatelessWidget { final Post _post; final OnPostDeleted onPostDeleted; - final ValueChanged onPostReported; - final OBPostDisplayContext displayContext; + final ValueChanged? onPostReported; + final OBPostDisplayContext? displayContext; final bool hasActions; const OBUserPostHeader(this._post, - {Key key, - @required this.onPostDeleted, + {Key? key, + required this.onPostDeleted, this.onPostReported, this.hasActions = true, this.displayContext}) @@ -36,26 +36,24 @@ class OBUserPostHeader extends StatelessWidget { if (_post.creator == null) return const SizedBox(); - String subtitle = '@${_post.creator.username}'; + String subtitle = '@${_post.creator!.username}'; if (_post.created != null) subtitle = - '$subtitle · ${utilsService.timeAgo(_post.created, localizationService)}'; + '$subtitle · ${utilsService.timeAgo(_post.created!, localizationService)}'; - Function navigateToUserProfile = () { + VoidCallback navigateToUserProfile = () { navigationService.navigateToUserProfile( - user: _post.creator, context: context); + user: _post.creator!, context: context); }; return ListTile( onTap: navigateToUserProfile, leading: StreamBuilder( - stream: _post.creator.updateSubject, + stream: _post.creator!.updateSubject, initialData: _post.creator, builder: (BuildContext context, AsyncSnapshot snapshot) { - User postCreator = snapshot.data; - - if (!postCreator.hasProfileAvatar()) return const SizedBox(); + User postCreator = snapshot.data!; return OBAvatar( size: OBAvatarSize.medium, @@ -70,7 +68,7 @@ class OBUserPostHeader extends StatelessWidget { context: context, post: _post, onPostDeleted: onPostDeleted, - displayContext: displayContext, + displayContext: displayContext!, onPostReported: onPostReported); }) : null, @@ -78,7 +76,7 @@ class OBUserPostHeader extends StatelessWidget { children: [ Flexible( child: OBText( - _post.creator.getProfileName(), + _post.creator!.getProfileName()!, style: TextStyle(fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis, ), @@ -96,11 +94,11 @@ class OBUserPostHeader extends StatelessWidget { } Widget _buildBadge() { - User postCommenter = _post.creator; + User postCommenter = _post.creator!; if (postCommenter.hasProfileBadges()) return OBUserBadge( - badge: _post.creator.getDisplayedProfileBadge(), + badge: _post.creator!.getDisplayedProfileBadge(), size: OBUserBadgeSize.small); return const SizedBox(); diff --git a/lib/widgets/post/widgets/post_reactions.dart b/lib/widgets/post/widgets/post_reactions.dart index 441dc3c5f..a1757e6de 100644 --- a/lib/widgets/post/widgets/post_reactions.dart +++ b/lib/widgets/post/widgets/post_reactions.dart @@ -23,12 +23,12 @@ class OBPostReactions extends StatefulWidget { } class OBPostReactionsState extends State { - UserService _userService; - ToastService _toastService; - NavigationService _navigationService; + late UserService _userService; + late ToastService _toastService; + late NavigationService _navigationService; - CancelableOperation _requestOperation; - bool _requestInProgress; + CancelableOperation? _requestOperation; + late bool _requestInProgress; @override void initState() { @@ -39,7 +39,7 @@ class OBPostReactionsState extends State { @override void dispose() { super.dispose(); - if (_requestOperation != null) _requestOperation.cancel(); + if (_requestOperation != null) _requestOperation!.cancel(); } @override @@ -55,8 +55,8 @@ class OBPostReactionsState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var post = snapshot.data; - List emojiCounts = - post.reactionsEmojiCounts?.counts; + List? emojiCounts = + post!.reactionsEmojiCounts?.counts; if (emojiCounts == null || emojiCounts.length == 0) return const SizedBox(); @@ -76,11 +76,11 @@ class OBPostReactionsState extends State { itemCount: emojiCounts.length, scrollDirection: Axis.horizontal, itemBuilder: (BuildContext context, int index) { - ReactionsEmojiCount emojiCount = emojiCounts[index]; + ReactionsEmojiCount emojiCount = emojiCounts[index]!; return OBEmojiReactionButton( emojiCount, - reacted: widget.post.isReactionEmoji(emojiCount.emoji), + reacted: widget.post.isReactionEmoji(emojiCount.emoji!), onLongPressed: (pressedEmojiCount) { _navigationService.navigateToPostReactions( post: widget.post, @@ -99,7 +99,7 @@ class OBPostReactionsState extends State { void _onEmojiReactionCountPressed( ReactionsEmojiCount pressedEmojiCount) async { - bool reacted = widget.post.isReactionEmoji(pressedEmojiCount.emoji); + bool reacted = widget.post.isReactionEmoji(pressedEmojiCount.emoji!); if (reacted) { await _deleteReaction(); @@ -107,18 +107,18 @@ class OBPostReactionsState extends State { } else { // React PostReaction newPostReaction = - await _reactToPost(pressedEmojiCount.emoji); + await _reactToPost(pressedEmojiCount.emoji!); widget.post.setReaction(newPostReaction); } } Future _reactToPost(Emoji emoji) async { _setRequestInProgress(true); - PostReaction postReaction; + late PostReaction postReaction; try { _requestOperation = CancelableOperation.fromFuture( _userService.reactToPost(post: widget.post, emoji: emoji)); - postReaction = await _requestOperation.value; + postReaction = await _requestOperation!.value; } catch (error) { _onError(error); } finally { @@ -133,8 +133,8 @@ class OBPostReactionsState extends State { try { _requestOperation = CancelableOperation.fromFuture( _userService.deletePostReaction( - postReaction: widget.post.reaction, post: widget.post)); - await _requestOperation.value; + postReaction: widget.post.reaction!, post: widget.post)); + await _requestOperation!.value; } catch (error) { _onError(error); } finally { @@ -147,8 +147,8 @@ class OBPostReactionsState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; diff --git a/lib/widgets/posts_count.dart b/lib/widgets/posts_count.dart index 4e070f5d1..f9c988c9b 100644 --- a/lib/widgets/posts_count.dart +++ b/lib/widgets/posts_count.dart @@ -6,10 +6,10 @@ import 'package:Okuna/services/localization.dart'; import 'package:flutter/material.dart'; class OBPostsCount extends StatelessWidget { - final int postsCount; + final int? postsCount; final bool showZero; - final Color color; - final double fontSize; + final Color? color; + final double? fontSize; OBPostsCount(this.postsCount, {this.showZero = false, this.color, this.fontSize}); @@ -23,7 +23,7 @@ class OBPostsCount extends StatelessWidget { var themeValueParserService = openbookProvider.themeValueParserService; LocalizationService _localizationService = openbookProvider.localizationService; - String count = getPrettyCount(postsCount, _localizationService); + String count = getPrettyCount(postsCount!, _localizationService); return StreamBuilder( stream: themeService.themeChange, @@ -44,7 +44,7 @@ class OBPostsCount extends StatelessWidget { fontSize: fontSize, fontWeight: FontWeight.bold, color: color ?? themeValueParserService - .parseColor(theme.primaryTextColor))), + .parseColor(theme!.primaryTextColor))), TextSpan( text: postsCount == 1 ? _localizationService.post__profile_counts_post @@ -52,7 +52,7 @@ class OBPostsCount extends StatelessWidget { style: TextStyle( fontSize: fontSize, color: color ?? themeValueParserService - .parseColor(theme.secondaryTextColor))) + .parseColor(theme!.secondaryTextColor))) ])), ), const SizedBox( diff --git a/lib/widgets/posts_stream/posts_stream.dart b/lib/widgets/posts_stream/posts_stream.dart index f9611ba17..36f52f9f8 100644 --- a/lib/widgets/posts_stream/posts_stream.dart +++ b/lib/widgets/posts_stream/posts_stream.dart @@ -20,33 +20,33 @@ import 'package:inview_notifier_list/inview_notifier_list.dart'; var rng = new Random(); class OBPostsStream extends StatefulWidget { - final List prependedItems; + final List? prependedItems; final OBPostsStreamRefresher refresher; final OBPostsStreamOnScrollLoader onScrollLoader; - final ScrollController scrollController; - final OBPostsStreamController controller; - final List initialPosts; + final ScrollController? scrollController; + final OBPostsStreamController? controller; + final List? initialPosts; final String streamIdentifier; - final ValueChanged> onPostsRefreshed; + final ValueChanged>? onPostsRefreshed; final bool refreshOnCreate; - final OBPostsStreamSecondaryRefresher secondaryRefresher; - final OBPostsStreamStatusIndicatorBuilder statusIndicatorBuilder; + final OBPostsStreamSecondaryRefresher? secondaryRefresher; + final OBPostsStreamStatusIndicatorBuilder? statusIndicatorBuilder; final OBPostDisplayContext displayContext; - final OBPostsStreamPostBuilder postBuilder; - final Function(ScrollPosition) onScrollCallback; + final OBPostsStreamPostBuilder? postBuilder; + final Function(ScrollPosition)? onScrollCallback; final double refreshIndicatorDisplacement; - final int onScrollLoadMoreLimit; - final String onScrollLoadMoreLimitLoadMoreText; + final int? onScrollLoadMoreLimit; + final String? onScrollLoadMoreLimitLoadMoreText; const OBPostsStream({ - Key key, + Key? key, this.prependedItems, - @required this.refresher, - @required this.onScrollLoader, + required this.refresher, + required this.onScrollLoader, this.onScrollCallback, this.controller, this.initialPosts, - @required this.streamIdentifier, + required this.streamIdentifier, this.onPostsRefreshed, this.refreshOnCreate = true, this.refreshIndicatorDisplacement = 40.0, @@ -67,35 +67,35 @@ class OBPostsStream extends StatefulWidget { class OBPostsStreamState extends State with SingleTickerProviderStateMixin { - List _posts; - bool _needsBootstrap; - ToastService _toastService; - LocalizationService _localizationService; - ThemeService _themeService; - ThemeValueParserService _themeValueParserService; - ScrollController _streamScrollController; + late List _posts; + late bool _needsBootstrap; + late ToastService _toastService; + late LocalizationService _localizationService; + late ThemeService _themeService; + late ThemeValueParserService _themeValueParserService; + late ScrollController _streamScrollController; - GlobalKey _refreshIndicatorKey; + late GlobalKey _refreshIndicatorKey; - OBPostsStreamStatus _status; + late OBPostsStreamStatus _status; - CancelableOperation _refreshOperation; - CancelableOperation _secondaryRefresherOperation; - CancelableOperation _loadMoreOperation; - CancelableOperation _cachePostsInStorage; + CancelableOperation? _refreshOperation; + CancelableOperation? _secondaryRefresherOperation; + CancelableOperation? _loadMoreOperation; + CancelableOperation? _cachePostsInStorage; - AnimationController _hideOverlayAnimationController; - Animation _animation; + late AnimationController _hideOverlayAnimationController; + late Animation _animation; bool _shouldHideStackedLoadingScreen = true; - bool _onScrollLoadMoreLimitRemoved; + late bool _onScrollLoadMoreLimitRemoved; - String _streamUniqueIdentifier; + late String _streamUniqueIdentifier; @override void initState() { super.initState(); - if (widget.controller != null) widget.controller.attach(this); - _posts = widget.initialPosts != null ? widget.initialPosts.toList() : []; + if (widget.controller != null) widget.controller!.attach(this); + _posts = widget.initialPosts != null ? widget.initialPosts!.toList() : []; if (_posts.isNotEmpty) _shouldHideStackedLoadingScreen = false; _needsBootstrap = true; _refreshIndicatorKey = GlobalKey(); @@ -162,8 +162,8 @@ class OBPostsStreamState extends State Widget _buildStream() { List streamItems = []; bool hasPrependedItems = - widget.prependedItems != null && widget.prependedItems.isNotEmpty; - if (hasPrependedItems) streamItems.addAll(widget.prependedItems); + widget.prependedItems != null && widget.prependedItems!.isNotEmpty; + if (hasPrependedItems) streamItems.addAll(widget.prependedItems!); if (_posts.isEmpty) { OBPostsStreamStatusIndicatorBuilder statusIndicatorBuilder = @@ -173,12 +173,16 @@ class OBPostsStreamState extends State context: context, streamStatus: _status, streamRefresher: _refresh, - streamPrependedItems: widget.prependedItems, + streamPrependedItems: widget.prependedItems ?? [], )); } else { streamItems.addAll(_buildStreamPosts()); - if (_status != OBPostsStreamStatus.idle) - streamItems.add(_buildStatusTile()); + if (_status != OBPostsStreamStatus.idle) { + Widget? statusTile = _buildStatusTile(); + if (statusTile != null) { + streamItems.add(statusTile); + } + } } return Stack( @@ -246,18 +250,18 @@ class OBPostsStreamState extends State } Widget _defaultStreamPostBuilder({ - BuildContext context, - Post post, - OBPostDisplayContext displayContext, - String postIdentifier, - ValueChanged onPostDeleted, + BuildContext? context, + Post? post, + OBPostDisplayContext? displayContext, + String? postIdentifier, + ValueChanged? onPostDeleted, }) { return OBPost( - post, - key: Key(postIdentifier), - onPostDeleted: onPostDeleted, + post!, + key: Key(postIdentifier!), + onPostDeleted: onPostDeleted!, inViewId: postIdentifier, - displayContext: displayContext, + displayContext: displayContext!, ); } @@ -266,8 +270,8 @@ class OBPostsStreamState extends State () => _hideOverlayAnimationController.forward()); } - Widget _buildStatusTile() { - Widget statusTile; + Widget? _buildStatusTile() { + Widget? statusTile; Key statusKey = Key('${_streamUniqueIdentifier}_status_tile'); switch (_status) { @@ -277,13 +281,11 @@ class OBPostsStreamState extends State padding: const EdgeInsets.all(20), child: const OBLoadingIndicatorTile(), ); - break; case OBPostsStreamStatus.loadingMoreFailed: return OBRetryTile( key: statusKey, onWantsToRetry: _loadMorePosts, ); - break; case OBPostsStreamStatus.noMoreToLoad: return ListTile( key: statusKey, @@ -335,7 +337,7 @@ class OBPostsStreamState extends State void _scrollToTop({bool skipRefresh = false}) { if (_streamScrollController.hasClients) { if (_streamScrollController.offset == 0 && !skipRefresh) { - _refreshIndicatorKey.currentState.show(); + _refreshIndicatorKey.currentState?.show(); } _streamScrollController.animateTo( @@ -363,7 +365,7 @@ class OBPostsStreamState extends State if (widget.onScrollCallback != null && _shouldHideStackedLoadingScreen) { // trigger this callback only after loading overlay is hidden // so that its not registered as a manual scroll - widget.onScrollCallback(_streamScrollController.position); + widget.onScrollCallback!(_streamScrollController.position); } if (_status == OBPostsStreamStatus.loadingMore || @@ -377,20 +379,20 @@ class OBPostsStreamState extends State void _ensureNoRefreshPostsInProgress() { if (_refreshOperation != null) { - _refreshOperation.cancel(); + _refreshOperation!.cancel(); _refreshOperation = null; } } void _ensureNoLoadMoreInProgress() { if (_loadMoreOperation != null) { - _loadMoreOperation.cancel(); + _loadMoreOperation!.cancel(); _loadMoreOperation = null; } } - Future _refresh() { - return _refreshIndicatorKey?.currentState?.show(); + Future? _refresh() { + return _refreshIndicatorKey.currentState?.show(); } Future _refreshPosts() async { @@ -401,12 +403,12 @@ class OBPostsStreamState extends State try { _refreshOperation = CancelableOperation.fromFuture(widget.refresher()); - List refreshFutures = [_refreshOperation.value]; + List refreshFutures = [_refreshOperation!.value]; if (widget.secondaryRefresher != null) { _secondaryRefresherOperation = - CancelableOperation.fromFuture(widget.secondaryRefresher()); - refreshFutures.add(_secondaryRefresherOperation.value); + CancelableOperation.fromFuture(widget.secondaryRefresher!()); + refreshFutures.add(_secondaryRefresherOperation!.value); } List results = await Future.wait(refreshFutures); @@ -414,9 +416,9 @@ class OBPostsStreamState extends State if (!_onScrollLoadMoreLimitRemoved && widget.onScrollLoadMoreLimit != null && - posts.length > widget.onScrollLoadMoreLimit) { + posts.length > widget.onScrollLoadMoreLimit!) { // Slice the posts to be within the limit - posts = posts.sublist(0, widget.onScrollLoadMoreLimit - 1); + posts = posts.sublist(0, widget.onScrollLoadMoreLimit! - 1); _setStatus(OBPostsStreamStatus.onScrollLoadMoreLimitReached); } else if (posts.length == 0) { _setStatus(OBPostsStreamStatus.empty); @@ -424,7 +426,7 @@ class OBPostsStreamState extends State _setStatus(OBPostsStreamStatus.idle); } _setPosts(posts); - if (widget.onPostsRefreshed != null) widget.onPostsRefreshed(posts); + if (widget.onPostsRefreshed != null) widget.onPostsRefreshed!(posts); } catch (error) { _setStatus(OBPostsStreamStatus.loadingMoreFailed); _onError(error); @@ -449,7 +451,7 @@ class OBPostsStreamState extends State if (!_onScrollLoadMoreLimitRemoved && (widget.onScrollLoadMoreLimit != null && - _posts.length >= widget.onScrollLoadMoreLimit)) { + _posts.length >= widget.onScrollLoadMoreLimit!)) { debugLog('Load more limit reached'); _setStatus(OBPostsStreamStatus.onScrollLoadMoreLimitReached); return; @@ -463,15 +465,15 @@ class OBPostsStreamState extends State _loadMoreOperation = CancelableOperation.fromFuture(widget.onScrollLoader(_posts)); - List morePosts = await _loadMoreOperation.value; + List morePosts = await _loadMoreOperation!.value; if (!_onScrollLoadMoreLimitRemoved && widget.onScrollLoadMoreLimit != null && - _posts.length + morePosts.length > widget.onScrollLoadMoreLimit) { + _posts.length + morePosts.length > widget.onScrollLoadMoreLimit!) { // Slice the posts to be within the limit if (morePosts.length == 0) return; morePosts = - morePosts.sublist(0, widget.onScrollLoadMoreLimit - _posts.length); + morePosts.sublist(0, widget.onScrollLoadMoreLimit! - _posts.length); _setStatus(OBPostsStreamStatus.onScrollLoadMoreLimitReached); } else if (morePosts.length == 0) { _setStatus(OBPostsStreamStatus.noMoreToLoad); @@ -492,7 +494,7 @@ class OBPostsStreamState extends State _posts.remove(deletedPost); if (_posts.isEmpty) _setStatus(OBPostsStreamStatus.empty); if (deletedPost.isCommunityPost()) - deletedPost.community.decrementPostsCount(); + deletedPost.community!.decrementPostsCount(); }); } @@ -501,8 +503,8 @@ class OBPostsStreamState extends State _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); @@ -538,28 +540,28 @@ class OBPostsStreamState extends State } class OBPostsStreamController { - OBPostsStreamState _state; + OBPostsStreamState? _state; /// Register the OBHomePostsState to the controller - void attach(OBPostsStreamState state) { + void attach(OBPostsStreamState? state) { assert(state != null, 'Cannot attach to empty state'); _state = state; } void scrollToTop({bool skipRefresh = false}) { - _state._scrollToTop(skipRefresh: skipRefresh); + _state?._scrollToTop(skipRefresh: skipRefresh); } void addPostToTop(Post post) { - _state._addPostToTop(post); + _state?._addPostToTop(post); } - Future refreshPosts() { - return _state._refreshPosts(); + Future? refreshPosts() { + return _state?._refreshPosts(); } - Future refresh() { - return _state._refresh(); + Future? refresh() { + return _state?._refresh(); } bool isAttached() { @@ -578,14 +580,18 @@ enum OBPostsStreamStatus { } Widget defaultStatusIndicatorBuilder( - {BuildContext context, - OBPostsStreamStatus streamStatus, - List streamPrependedItems, - Function streamRefresher}) { + {BuildContext? context, + OBPostsStreamStatus? streamStatus, + List? streamPrependedItems, + Function? streamRefresher}) { return OBPostsStreamDrHoo( streamStatus: streamStatus, streamPrependedItems: streamPrependedItems, - streamRefresher: streamRefresher, + streamRefresher: () { + if (streamRefresher != null) { + streamRefresher(); + } + }, ); } @@ -594,10 +600,10 @@ typedef Future> OBPostsStreamOnScrollLoader(List posts); typedef Future OBPostsStreamSecondaryRefresher(); typedef OBPostsStreamStatusIndicatorBuilder = Widget Function( - {@required BuildContext context, - @required OBPostsStreamStatus streamStatus, - @required List streamPrependedItems, - @required Function streamRefresher}); + {required BuildContext context, + required OBPostsStreamStatus streamStatus, + required List streamPrependedItems, + required Function streamRefresher}); typedef Widget OBPostsStreamPostBuilder( {BuildContext context, diff --git a/lib/widgets/posts_stream/widgets/dr_hoo.dart b/lib/widgets/posts_stream/widgets/dr_hoo.dart index e5d884bb9..20ba5f1dc 100644 --- a/lib/widgets/posts_stream/widgets/dr_hoo.dart +++ b/lib/widgets/posts_stream/widgets/dr_hoo.dart @@ -8,15 +8,15 @@ import 'package:Okuna/widgets/theming/text.dart'; import 'package:flutter/cupertino.dart'; class OBPostsStreamDrHoo extends StatelessWidget { - final VoidCallback streamRefresher; - final OBPostsStreamStatus streamStatus; - final List streamPrependedItems; + final VoidCallback? streamRefresher; + final OBPostsStreamStatus? streamStatus; + final List? streamPrependedItems; const OBPostsStreamDrHoo({ - Key key, - @required this.streamRefresher, - @required this.streamStatus, - @required this.streamPrependedItems, + Key? key, + required this.streamRefresher, + required this.streamStatus, + required this.streamPrependedItems, }) : super(key: key); @override @@ -109,7 +109,7 @@ class OBPostsStreamDrHoo extends StatelessWidget { padding: EdgeInsets.symmetric( horizontal: 20, vertical: - streamPrependedItems != null && streamPrependedItems.isNotEmpty || + streamPrependedItems != null && streamPrependedItems!.isNotEmpty || streamStatus == OBPostsStreamStatus.empty || streamStatus == OBPostsStreamStatus.refreshing || streamStatus == OBPostsStreamStatus.loadingMoreFailed diff --git a/lib/widgets/progress_indicator.dart b/lib/widgets/progress_indicator.dart index 5aad0fe7b..a943a9888 100644 --- a/lib/widgets/progress_indicator.dart +++ b/lib/widgets/progress_indicator.dart @@ -2,10 +2,10 @@ import 'package:flutter/material.dart'; class OBProgressIndicator extends StatelessWidget { - final Color color; + final Color? color; final double size; - const OBProgressIndicator({Key key, this.color, this.size = 20.0}) : super(key: key); + const OBProgressIndicator({Key? key, this.color, this.size = 20.0}) : super(key: key); @override Widget build(BuildContext context) { @@ -16,7 +16,7 @@ class OBProgressIndicator extends StatelessWidget { ), child: CircularProgressIndicator( strokeWidth: 2.0, - valueColor: AlwaysStoppedAnimation(color), + valueColor: AlwaysStoppedAnimation(color), ), ); } diff --git a/lib/widgets/reaction_emoji_count.dart b/lib/widgets/reaction_emoji_count.dart index b9dcb4fdc..97eaa896d 100644 --- a/lib/widgets/reaction_emoji_count.dart +++ b/lib/widgets/reaction_emoji_count.dart @@ -9,9 +9,9 @@ import 'buttons/button.dart'; class OBEmojiReactionButton extends StatelessWidget { final ReactionsEmojiCount postReactionsEmojiCount; - final bool reacted; - final ValueChanged onPressed; - final ValueChanged onLongPressed; + final bool? reacted; + final ValueChanged? onPressed; + final ValueChanged? onLongPressed; final OBEmojiReactionButtonSize size; const OBEmojiReactionButton(this.postReactionsEmojiCount, @@ -22,12 +22,12 @@ class OBEmojiReactionButton extends StatelessWidget { @override Widget build(BuildContext context) { - var emoji = postReactionsEmojiCount.emoji; + var emoji = postReactionsEmojiCount.emoji!; List buttonRowItems = [ Image( height: size == OBEmojiReactionButtonSize.medium ? 18 : 14, - image: AdvancedNetworkImage(emoji.image, useDiskCache: true), + image: AdvancedNetworkImage(emoji.image!, useDiskCache: true), ), const SizedBox( width: 10.0, @@ -35,7 +35,7 @@ class OBEmojiReactionButton extends StatelessWidget { OBText( postReactionsEmojiCount.getPrettyCount(), style: TextStyle( - fontWeight: reacted ? FontWeight.bold : FontWeight.normal, + fontWeight: (reacted == true) ? FontWeight.bold : FontWeight.normal, fontSize: size == OBEmojiReactionButtonSize.medium ? null : 12), ) ]; @@ -47,10 +47,10 @@ class OBEmojiReactionButton extends StatelessWidget { minWidth: 50, child: buttonChild, onLongPressed: () { - if (onLongPressed != null) onLongPressed(postReactionsEmojiCount); + if (onLongPressed != null) onLongPressed!(postReactionsEmojiCount); }, onPressed: () { - if (onPressed != null) onPressed(postReactionsEmojiCount); + if (onPressed != null) onPressed!(postReactionsEmojiCount); }, type: OBButtonType.highlight, ); diff --git a/lib/widgets/routes/slide_right_route.dart b/lib/widgets/routes/slide_right_route.dart index a49a13677..b1c89f94b 100644 --- a/lib/widgets/routes/slide_right_route.dart +++ b/lib/widgets/routes/slide_right_route.dart @@ -6,9 +6,9 @@ class OBSlideRightRoute extends PageRoute { Key slidableKey; OBSlideRightRoute({ - @required this.slidableKey, - @required this.builder, - RouteSettings settings, + required this.slidableKey, + required this.builder, + RouteSettings? settings, this.maintainState = true, bool fullscreenDialog = false, }) : assert(builder != null), @@ -32,7 +32,7 @@ class OBSlideRightRoute extends PageRoute { Color get barrierColor => Color.fromARGB(0, 0, 0, 1); @override - String get barrierLabel => null; + String? get barrierLabel => null; @override bool canTransitionFrom(TransitionRoute previousRoute) { diff --git a/lib/widgets/search_bar.dart b/lib/widgets/search_bar.dart index 272465a78..8edf81b8c 100644 --- a/lib/widgets/search_bar.dart +++ b/lib/widgets/search_bar.dart @@ -8,10 +8,10 @@ import 'package:flutter/material.dart'; class OBSearchBar extends StatefulWidget { final OBSearchBarOnSearch onSearch; - final VoidCallback onCancel; - final String hintText; + final VoidCallback? onCancel; + final String? hintText; - OBSearchBar({Key key, @required this.onSearch, this.hintText, this.onCancel}) + OBSearchBar({Key? key, required this.onSearch, this.hintText, this.onCancel}) : super(key: key); @override @@ -21,8 +21,8 @@ class OBSearchBar extends StatefulWidget { } class OBSearchBarState extends State { - TextEditingController _textController; - FocusNode _textFocusNode; + late TextEditingController _textController; + late FocusNode _textFocusNode; @override void initState() { @@ -52,7 +52,7 @@ class OBSearchBarState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var theme = snapshot.data; Color primaryColor = - themeValueParserService.parseColor(theme.primaryColor); + themeValueParserService.parseColor(theme!.primaryColor); final bool isDarkPrimaryColor = primaryColor.computeLuminance() < 0.179; @@ -138,7 +138,7 @@ class OBSearchBarState extends State { // Unfocus text FocusScope.of(context).requestFocus(new FocusNode()); _textController.clear(); - if (widget.onCancel != null) widget.onCancel(); + if (widget.onCancel != null) widget.onCancel!(); } } diff --git a/lib/widgets/tabs/image_tab.dart b/lib/widgets/tabs/image_tab.dart index 57f29c6a2..f2d53e14f 100644 --- a/lib/widgets/tabs/image_tab.dart +++ b/lib/widgets/tabs/image_tab.dart @@ -5,17 +5,17 @@ class OBImageTab extends StatelessWidget { static const double width = 130; static const double height = 80; - final Color color; + final Color? color; final Color textColor; final String text; final ImageProvider imageProvider; const OBImageTab( - {Key key, + {Key? key, this.color, - @required this.textColor, - @required this.text, - this.imageProvider}) + required this.textColor, + required this.text, + required this.imageProvider}) : super(key: key); @override diff --git a/lib/widgets/theming/actionable_smart_text.dart b/lib/widgets/theming/actionable_smart_text.dart index 5dca8e4c4..f14e008db 100644 --- a/lib/widgets/theming/actionable_smart_text.dart +++ b/lib/widgets/theming/actionable_smart_text.dart @@ -15,17 +15,17 @@ export 'package:Okuna/widgets/theming/smart_text.dart'; import 'package:flutter/material.dart'; class OBActionableSmartText extends StatefulWidget { - final String text; - final int maxlength; + final String? text; + final int? maxlength; final OBTextSize size; final TextOverflow overflow; final TextOverflow lengthOverflow; - final SmartTextElement trailingSmartTextElement; - final Map hashtagsMap; - final List links; + final SmartTextElement? trailingSmartTextElement; + final Map? hashtagsMap; + final List? links; const OBActionableSmartText( - {Key key, + {Key? key, this.text, this.maxlength, this.size = OBTextSize.medium, @@ -43,13 +43,13 @@ class OBActionableSmartText extends StatefulWidget { } class OBActionableTextState extends State { - NavigationService _navigationService; - UserService _userService; - UrlLauncherService _urlLauncherService; - ToastService _toastService; + late NavigationService _navigationService; + late UserService _userService; + late UrlLauncherService _urlLauncherService; + late ToastService _toastService; - bool _needsBootstrap; - StreamSubscription _requestSubscription; + late bool _needsBootstrap; + StreamSubscription? _requestSubscription; @override void initState() { @@ -115,16 +115,16 @@ class OBActionableTextState extends State { } void _onHashtagNameHashtagRetrieved( - {Hashtag hashtag, String rawHashtagName}) { + {Hashtag? hashtag, String? rawHashtagName}) { if (hashtag != null) { - _onHashtagRetrieved(hashtag: hashtag, rawHashtagName: rawHashtagName); + _onHashtagRetrieved(hashtag: hashtag, rawHashtagName: rawHashtagName!); return; } _clearRequestSubscription(); StreamSubscription requestSubscription = _userService - .getHashtagWithName(rawHashtagName) + .getHashtagWithName(rawHashtagName!) .asStream() .listen( (Hashtag hashtag) => _onHashtagRetrieved( @@ -134,7 +134,7 @@ class OBActionableTextState extends State { _setRequestSubscription(requestSubscription); } - void _onHashtagRetrieved({Hashtag hashtag, String rawHashtagName}) { + void _onHashtagRetrieved({required Hashtag hashtag, String? rawHashtagName}) { _navigationService.navigateToHashtag( rawHashtagName: rawHashtagName, hashtag: hashtag, context: context); } @@ -162,8 +162,8 @@ class OBActionableTextState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? 'Unknown error', context: context); } else { _toastService.error(message: 'Unknown error', context: context); throw error; @@ -172,12 +172,12 @@ class OBActionableTextState extends State { void _clearRequestSubscription() { if (_requestSubscription != null) { - _requestSubscription.cancel(); + _requestSubscription!.cancel(); _setRequestSubscription(null); } } - void _setRequestSubscription(StreamSubscription requestSubscription) { + void _setRequestSubscription(StreamSubscription? requestSubscription) { _requestSubscription = requestSubscription; } } diff --git a/lib/widgets/theming/collapsible_smart_text.dart b/lib/widgets/theming/collapsible_smart_text.dart index db67bbcae..0cd791e22 100644 --- a/lib/widgets/theming/collapsible_smart_text.dart +++ b/lib/widgets/theming/collapsible_smart_text.dart @@ -12,18 +12,18 @@ import '../../provider.dart'; import 'actionable_smart_text.dart'; class OBCollapsibleSmartText extends StatefulWidget { - final String text; - final int maxlength; + final String? text; + final int? maxlength; final OBTextSize size; final TextOverflow overflow; final TextOverflow lengthOverflow; - final SmartTextElement trailingSmartTextElement; - final Function getChild; - final Map hashtagsMap; - final List links; + final SmartTextElement? trailingSmartTextElement; + final Function? getChild; + final Map? hashtagsMap; + final List? links; const OBCollapsibleSmartText( - {Key key, + {Key? key, this.text, this.maxlength, this.size = OBTextSize.medium, @@ -42,7 +42,7 @@ class OBCollapsibleSmartText extends StatefulWidget { } class OBCollapsibleSmartTextState extends State { - ExpandableController _expandableController; + late ExpandableController _expandableController; @override void initState() { @@ -52,7 +52,7 @@ class OBCollapsibleSmartTextState extends State { @override Widget build(BuildContext context) { - bool shouldBeCollapsed = widget.text.length > widget.maxlength; + bool shouldBeCollapsed = widget.text != null && widget.maxlength != null && widget.text!.length > widget.maxlength!; LocalizationService _localizationService = OpenbookProvider.of(context).localizationService; @@ -75,7 +75,7 @@ class OBCollapsibleSmartTextState extends State { Builder(builder: (BuildContext context) { var exp = ExpandableController.of(context); - if (exp.expanded) return const SizedBox(); + if (exp?.expanded == true) return const SizedBox(); return GestureDetector( onTap: _toggleExpandable, @@ -84,7 +84,7 @@ class OBCollapsibleSmartTextState extends State { child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - widget.getChild(), + widget.getChild!(), Row( children: [ OBSecondaryText( @@ -114,7 +114,7 @@ class OBCollapsibleSmartTextState extends State { _expandableController.toggle(); } - Widget _buildActionableSmartText({int maxLength}) { + Widget _buildActionableSmartText({int? maxLength}) { Widget translateButton; if (maxLength != null) { @@ -122,7 +122,7 @@ class OBCollapsibleSmartTextState extends State { } else { translateButton = Padding( padding: EdgeInsets.only(top: 10.0), - child: widget.getChild(), + child: widget.getChild!(), ); } diff --git a/lib/widgets/theming/divider.dart b/lib/widgets/theming/divider.dart index 86d949d04..7ac024e3d 100644 --- a/lib/widgets/theming/divider.dart +++ b/lib/widgets/theming/divider.dart @@ -29,7 +29,7 @@ class OBDivider extends StatelessWidget { border: Border( bottom: BorderSide( color: themeValueParserService - .parseColor(theme.secondaryTextColor), + .parseColor(theme!.secondaryTextColor), width: 0.5, )), ), diff --git a/lib/widgets/theming/fading_highlighted_box.dart b/lib/widgets/theming/fading_highlighted_box.dart index e46ebdf19..d9c04bd49 100644 --- a/lib/widgets/theming/fading_highlighted_box.dart +++ b/lib/widgets/theming/fading_highlighted_box.dart @@ -4,12 +4,12 @@ import 'package:Okuna/widgets/theming/text.dart'; import 'package:flutter/material.dart'; class OBFadingHighlightedBox extends StatefulWidget { - final Widget child; - final EdgeInsets padding; - final BorderRadius borderRadius; + final Widget? child; + final EdgeInsets? padding; + final BorderRadius? borderRadius; const OBFadingHighlightedBox( - {Key key, this.child, this.padding, this.borderRadius}) + {Key? key, this.child, this.padding, this.borderRadius}) : super(key: key); @override @@ -20,7 +20,7 @@ class OBFadingHighlightedBox extends StatefulWidget { class OBFadingHighlightedBoxState extends State with SingleTickerProviderStateMixin { - AnimationController _controller; + late AnimationController _controller; @override void initState() { @@ -51,7 +51,7 @@ class OBFadingHighlightedBoxState extends State var theme = snapshot.data; var primaryColor = - themeValueParserService.parseColor(theme.primaryColor); + themeValueParserService.parseColor(theme!.primaryColor); final bool isDarkPrimaryColor = primaryColor.computeLuminance() < 0.179; @@ -59,7 +59,7 @@ class OBFadingHighlightedBoxState extends State ? Color.fromARGB(30, 255, 255, 255) : Color.fromARGB(10, 0, 0, 0); - Animatable background = TweenSequence( + Animatable background = TweenSequence( [ TweenSequenceItem( weight: 1.0, @@ -74,7 +74,7 @@ class OBFadingHighlightedBoxState extends State return AnimatedBuilder( animation: _controller, builder: (context, child) { - Color color = background + Color? color = background .evaluate(AlwaysStoppedAnimation(_controller.value)); return Container( diff --git a/lib/widgets/theming/highlighted_box.dart b/lib/widgets/theming/highlighted_box.dart index 3b94b8e21..7600ac368 100644 --- a/lib/widgets/theming/highlighted_box.dart +++ b/lib/widgets/theming/highlighted_box.dart @@ -3,12 +3,12 @@ import 'package:Okuna/provider.dart'; import 'package:flutter/material.dart'; class OBHighlightedBox extends StatelessWidget { - final Widget child; - final EdgeInsets padding; - final BorderRadius borderRadius; + final Widget? child; + final EdgeInsets? padding; + final BorderRadius? borderRadius; const OBHighlightedBox( - {Key key, + {Key? key, this.child, this.padding, this.borderRadius}) @@ -27,7 +27,7 @@ class OBHighlightedBox extends StatelessWidget { var theme = snapshot.data; var primaryColor = - themeValueParserService.parseColor(theme.primaryColor); + themeValueParserService.parseColor(theme!.primaryColor); final bool isDarkPrimaryColor = primaryColor.computeLuminance() < 0.179; diff --git a/lib/widgets/theming/highlighted_color_container.dart b/lib/widgets/theming/highlighted_color_container.dart index 0f52157ea..14388c8dc 100644 --- a/lib/widgets/theming/highlighted_color_container.dart +++ b/lib/widgets/theming/highlighted_color_container.dart @@ -3,12 +3,12 @@ import 'package:Okuna/provider.dart'; import 'package:flutter/material.dart'; class OBHighlightedColorContainer extends StatelessWidget { - final Widget child; - final BoxDecoration decoration; - final MainAxisSize mainAxisSize; + final Widget? child; + final BoxDecoration? decoration; + final MainAxisSize? mainAxisSize; const OBHighlightedColorContainer( - {Key key, + {Key? key, this.child, this.decoration, this.mainAxisSize = MainAxisSize.max}) @@ -27,7 +27,7 @@ class OBHighlightedColorContainer extends StatelessWidget { var theme = snapshot.data; var primaryColor = - themeValueParserService.parseColor(theme.primaryColor); + themeValueParserService.parseColor(theme!.primaryColor); final bool isDarkPrimaryColor = primaryColor.computeLuminance() < 0.179; @@ -52,7 +52,7 @@ class OBHighlightedColorContainer extends StatelessWidget { } return Column( - mainAxisSize: mainAxisSize, + mainAxisSize: mainAxisSize ?? MainAxisSize.max, children: [Expanded(child: container)], ); }); diff --git a/lib/widgets/theming/post_divider.dart b/lib/widgets/theming/post_divider.dart index ea601b797..d7081ba5e 100644 --- a/lib/widgets/theming/post_divider.dart +++ b/lib/widgets/theming/post_divider.dart @@ -18,7 +18,7 @@ class OBPostDivider extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { var theme = snapshot.data; - Color color = themeValueParserService.parseColor(theme.primaryColor); + Color color = themeValueParserService.parseColor(theme!.primaryColor); TinyColor modifiedColor = themeValueParserService.isDarkColor(color) ? TinyColor(color).lighten(30) diff --git a/lib/widgets/theming/primary_accent_text.dart b/lib/widgets/theming/primary_accent_text.dart index 239ed8bce..c6d87b0f0 100644 --- a/lib/widgets/theming/primary_accent_text.dart +++ b/lib/widgets/theming/primary_accent_text.dart @@ -5,10 +5,10 @@ import 'package:flutter/material.dart'; class OBPrimaryAccentText extends StatelessWidget { final String text; - final TextStyle style; - final OBTextSize size; + final TextStyle? style; + final OBTextSize? size; final TextOverflow overflow; - final int maxLines; + final int? maxLines; OBPrimaryAccentText(this.text, {this.style, @@ -28,11 +28,11 @@ class OBPrimaryAccentText extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { var theme = snapshot.data; - TextStyle finalStyle = style; + TextStyle? finalStyle = style; TextStyle themedTextStyle = TextStyle( foreground: Paint() ..shader = themeValueParserService - .parseGradient(theme.primaryAccentColor).createShader(Rect.fromLTWH(0.0, 0.0, 200.0, 70.0))); + .parseGradient(theme!.primaryAccentColor).createShader(Rect.fromLTWH(0.0, 0.0, 200.0, 70.0))); if (finalStyle != null) { finalStyle = finalStyle.merge(themedTextStyle); @@ -43,7 +43,7 @@ class OBPrimaryAccentText extends StatelessWidget { return OBText( text, style: finalStyle, - size: size, + size: size ?? OBTextSize.medium, overflow: overflow, maxLines: maxLines, ); diff --git a/lib/widgets/theming/primary_color_container.dart b/lib/widgets/theming/primary_color_container.dart index 42ee8561a..a511c59a6 100644 --- a/lib/widgets/theming/primary_color_container.dart +++ b/lib/widgets/theming/primary_color_container.dart @@ -3,12 +3,12 @@ import 'package:Okuna/provider.dart'; import 'package:flutter/material.dart'; class OBPrimaryColorContainer extends StatelessWidget { - final Widget child; - final BoxDecoration decoration; + final Widget? child; + final BoxDecoration? decoration; final MainAxisSize mainAxisSize; const OBPrimaryColorContainer( - {Key key, + {Key? key, this.child, this.decoration, this.mainAxisSize = MainAxisSize.max}) @@ -28,7 +28,7 @@ class OBPrimaryColorContainer extends StatelessWidget { Widget container = DecoratedBox( decoration: BoxDecoration( - color: themeValueParserService.parseColor(theme.primaryColor), + color: themeValueParserService.parseColor(theme!.primaryColor), borderRadius: decoration?.borderRadius), child: child, ); diff --git a/lib/widgets/theming/secondary_text.dart b/lib/widgets/theming/secondary_text.dart index c0fc581e4..78295b186 100644 --- a/lib/widgets/theming/secondary_text.dart +++ b/lib/widgets/theming/secondary_text.dart @@ -5,11 +5,11 @@ import 'package:flutter/material.dart'; class OBSecondaryText extends StatelessWidget { final String text; - final TextStyle style; - final OBTextSize size; - final TextOverflow overflow; - final TextAlign textAlign; - final int maxLines; + final TextStyle? style; + final OBTextSize? size; + final TextOverflow? overflow; + final TextAlign? textAlign; + final int? maxLines; const OBSecondaryText(this.text, {this.style, this.size, this.overflow, this.textAlign, this.maxLines}); @@ -26,10 +26,10 @@ class OBSecondaryText extends StatelessWidget { builder: (BuildContext context, AsyncSnapshot snapshot) { var theme = snapshot.data; - TextStyle finalStyle = style; + TextStyle? finalStyle = style; TextStyle themedTextStyle = TextStyle( color: - themeValueParserService.parseColor(theme.secondaryTextColor)); + themeValueParserService.parseColor(theme!.secondaryTextColor)); if (finalStyle != null) { finalStyle = finalStyle.merge(themedTextStyle); @@ -40,7 +40,7 @@ class OBSecondaryText extends StatelessWidget { return OBText( text, style: finalStyle, - size: size, + size: size ?? OBTextSize.medium, overflow: overflow, maxLines: maxLines, textAlign: textAlign, diff --git a/lib/widgets/theming/smart_text.dart b/lib/widgets/theming/smart_text.dart index e1df3db77..293fdc19b 100644 --- a/lib/widgets/theming/smart_text.dart +++ b/lib/widgets/theming/smart_text.dart @@ -131,17 +131,17 @@ List _smartify(String text) { List matches = []; matches.addAll(_usernameRegex.allMatches(text).map((m) { return SmartMatch( - UsernameElement(m.group(1)), m.start + m.group(0).indexOf("@"), m.end); + UsernameElement(m.group(1)!), m.start + m.group(0)!.indexOf("@"), m.end); })); matches.addAll(_communityNameRegex.allMatches(text).map((m) { - return SmartMatch(CommunityNameElement(m.group(0)), m.start, m.end); + return SmartMatch(CommunityNameElement(m.group(0)!), m.start, m.end); })); matches.addAll(linkRegex.allMatches(text).map((m) { - return SmartMatch(LinkElement(m.group(0)), m.start, m.end); + return SmartMatch(LinkElement(m.group(0)!), m.start, m.end); })); matches.addAll(_tagRegex.allMatches(text).map((m) { - return SmartMatch(HashtagElement(m.group(0)), m.start, m.end); + return SmartMatch(HashtagElement(m.group(0)!), m.start, m.end); })); // matches.addAll(_tagRegex.allMatches(text).map((m) { return SmartMatch(HashTagElement(m.group(0)), m.start, m.end); })); matches.sort((a, b) { @@ -155,7 +155,7 @@ List _smartify(String text) { List span = []; int currentTextIndex = 0; int matchIndex = 0; - var currentMatch = matches[matchIndex]; + SmartMatch? currentMatch = matches[matchIndex]; while (currentTextIndex < text.length) { if (currentMatch == null) { // no more match found, add entire remaining text @@ -196,34 +196,34 @@ typedef StringCallback(String url); /// Turns URLs into links class OBSmartText extends StatelessWidget { /// Text to be linkified - final String text; + final String? text; /// Maximum text length - final int maxlength; + final int? maxlength; /// Style for non-link text - final TextStyle style; + final TextStyle? style; /// Style of link text - final TextStyle linkStyle; + final TextStyle? linkStyle; /// Style of HashTag text - final TextStyle tagStyle; + final TextStyle? tagStyle; /// Callback for tapping a link - final StringCallback onLinkTapped; + final StringCallback? onLinkTapped; /// Callback for tapping a link - final OnHashtagTapped onHashtagTapped; + final OnHashtagTapped? onHashtagTapped; /// Callback for tapping a link - final StringCallback onUsernameTapped; + final StringCallback? onUsernameTapped; /// Callback for tapping a link - final StringCallback onCommunityNameTapped; + final StringCallback? onCommunityNameTapped; /// SmartTextElement element to add at the end of smart text - final SmartTextElement trailingSmartTextElement; + final SmartTextElement? trailingSmartTextElement; final OBTextSize size; @@ -231,10 +231,10 @@ class OBSmartText extends StatelessWidget { final TextOverflow lengthOverflow; - final Map hashtagsMap; + final Map? hashtagsMap; const OBSmartText({ - Key key, + Key? key, this.text, this.maxlength, this.overflow = TextOverflow.clip, @@ -253,17 +253,17 @@ class OBSmartText extends StatelessWidget { /// Raw TextSpan builder for more control on the RichText TextSpan _buildSpan({ - String text, - TextStyle style, - TextStyle secondaryTextStyle, - TextStyle linkStyle, - TextStyle tagStyle, - TextStyle usernameStyle, - TextStyle communityNameStyle, - StringCallback onLinkTapped, - StringCallback onTagTapped, - StringCallback onUsernameTapped, - StringCallback onCommunityNameTapped, + String? text, + TextStyle? style, + TextStyle? secondaryTextStyle, + TextStyle? linkStyle, + TextStyle? tagStyle, + TextStyle? usernameStyle, + TextStyle? communityNameStyle, + StringCallback? onLinkTapped, + StringCallback? onTagTapped, + StringCallback? onUsernameTapped, + StringCallback? onCommunityNameTapped, }) { void _onOpen(String url) { if (onLinkTapped != null) { @@ -298,19 +298,19 @@ class OBSmartText extends StatelessWidget { } } - List elements = _smartify(text); + List elements = _smartify(text!); - if (this.maxlength != null && text.length > maxlength) { - _enforceMaxLength(elements, maxlength); + if (this.maxlength != null && text.length > maxlength!) { + _enforceMaxLength(elements, maxlength!); } if (this.trailingSmartTextElement != null) { - elements.add(this.trailingSmartTextElement); + elements.add(this.trailingSmartTextElement!); } return TextSpan( children: elements.map((element) { - InlineSpan textSpan; + late InlineSpan textSpan; if (element is TextElement) { textSpan = TextSpan( text: element.text, @@ -332,8 +332,8 @@ class OBSmartText extends StatelessWidget { element.text.substring(1, element.text.length); String hashtagName = rawHashtagName.toLowerCase(); if (this.hashtagsMap != null && - this.hashtagsMap.containsKey(hashtagName)) { - Hashtag hashtag = this.hashtagsMap[hashtagName]; + this.hashtagsMap!.containsKey(hashtagName)) { + Hashtag hashtag = this.hashtagsMap![hashtagName]!; textSpan = WidgetSpan( baseline: TextBaseline.alphabetic, alignment: ui.PlaceholderAlignment.baseline, @@ -342,7 +342,7 @@ class OBSmartText extends StatelessWidget { hashtag: hashtag, rawHashtagName: rawHashtagName, onPressed: (Hashtag hashtag) { - if (onHashtagTapped != null) onHashtagTapped( + if (onHashtagTapped != null) onHashtagTapped!( hashtag: hashtag, rawHashtagName: rawHashtagName); }, textStyle: linkStyle, @@ -351,7 +351,7 @@ class OBSmartText extends StatelessWidget { textSpan = LinkTextSpan( text: element.text, style: linkStyle, - onPressed: () => onHashtagTapped(rawHashtagName: rawHashtagName), + onPressed: () => onHashtagTapped!(rawHashtagName: rawHashtagName), ); } } else if (element is UsernameElement) { @@ -372,7 +372,7 @@ class OBSmartText extends StatelessWidget { }).toList()); } - String runeSubstring({String input, int start, int end}) { + String runeSubstring({required String input, required int start, required int end}) { return String.fromCharCodes(input.runes.toList().sublist(start, end)); } @@ -418,7 +418,7 @@ class OBSmartText extends StatelessWidget { initialData: themeService.getActiveTheme(), stream: themeService.themeChange, builder: (BuildContext context, AsyncSnapshot snapshot) { - OBTheme theme = snapshot.data; + OBTheme theme = snapshot.data!; Color primaryTextColor = themeValueParserService.parseColor(theme.primaryTextColor); @@ -428,7 +428,7 @@ class OBSmartText extends StatelessWidget { fontSize: fontSize, fontFamilyFallback: ['NunitoSans']); - TextStyle secondaryTextStyle; + TextStyle? secondaryTextStyle; if (trailingSmartTextElement != null) { // This is ugly af, why do we even need this. @@ -474,7 +474,7 @@ class OBSmartText extends StatelessWidget { } class LinkTextSpan extends TextSpan { - LinkTextSpan({TextStyle style, VoidCallback onPressed, String text}) + LinkTextSpan({TextStyle? style, VoidCallback? onPressed, String? text}) : super( style: style, text: text, diff --git a/lib/widgets/theming/text.dart b/lib/widgets/theming/text.dart index d2a3a6cc4..85cca95c1 100644 --- a/lib/widgets/theming/text.dart +++ b/lib/widgets/theming/text.dart @@ -30,10 +30,10 @@ class OBText extends StatelessWidget { } final String text; - final TextStyle style; - final TextAlign textAlign; - final TextOverflow overflow; - final int maxLines; + final TextStyle? style; + final TextAlign? textAlign; + final TextOverflow? overflow; + final int? maxLines; final OBTextSize size; const OBText(this.text, @@ -58,10 +58,10 @@ class OBText extends StatelessWidget { var theme = snapshot.data; TextStyle themedTextStyle = TextStyle( - color: themeValueParserService.parseColor(theme.primaryTextColor), + color: themeValueParserService.parseColor(theme!.primaryTextColor), fontFamilyFallback: ['NunitoSans'], - fontSize: (style != null && style.fontSize != null) - ? style.fontSize + fontSize: (style != null && style!.fontSize != null) + ? style!.fontSize : fontSize); if (style != null) { diff --git a/lib/widgets/tile_group_title.dart b/lib/widgets/tile_group_title.dart index 45ddff1ce..c28d30e31 100644 --- a/lib/widgets/tile_group_title.dart +++ b/lib/widgets/tile_group_title.dart @@ -2,10 +2,10 @@ import 'package:Okuna/widgets/theming/text.dart'; import 'package:flutter/material.dart'; class OBTileGroupTitle extends StatelessWidget { - final String title; - final TextStyle style; + final String? title; + final TextStyle? style; - const OBTileGroupTitle({Key key, this.title, this.style}) : super(key: key); + const OBTileGroupTitle({Key? key, this.title, this.style}) : super(key: key); @override Widget build(BuildContext context) { @@ -15,7 +15,7 @@ class OBTileGroupTitle extends StatelessWidget { return Padding( padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5), child: OBText( - title, + title ?? '', size: OBTextSize.large, style: finalStyle, ), diff --git a/lib/widgets/tiles/actions/block_user_tile.dart b/lib/widgets/tiles/actions/block_user_tile.dart index da8f96a38..9e2bce3bb 100644 --- a/lib/widgets/tiles/actions/block_user_tile.dart +++ b/lib/widgets/tiles/actions/block_user_tile.dart @@ -12,12 +12,12 @@ import 'package:flutter/material.dart'; class OBBlockUserTile extends StatelessWidget { final User user; - final VoidCallback onBlockedUser; - final VoidCallback onUnblockedUser; + final VoidCallback? onBlockedUser; + final VoidCallback? onUnblockedUser; const OBBlockUserTile({ - Key key, - @required this.user, + Key? key, + required this.user, this.onBlockedUser, this.onUnblockedUser, }) : super(key: key); @@ -34,7 +34,7 @@ class OBBlockUserTile extends StatelessWidget { stream: user.updateSubject, initialData: user, builder: (BuildContext context, AsyncSnapshot snapshot) { - var user = snapshot.data; + var user = snapshot.data!; bool isBlocked = user.isBlocked ?? false; @@ -53,7 +53,7 @@ class OBBlockUserTile extends StatelessWidget { toastService.success( message: localizationService.user__profile_action_user_unblocked, context: context); - if (onUnblockedUser != null) onUnblockedUser(); + if (onUnblockedUser != null) onUnblockedUser!(); }); } : () { @@ -65,7 +65,7 @@ class OBBlockUserTile extends StatelessWidget { toastService.success( message: localizationService.user__profile_action_user_blocked, context: context); - if (onBlockedUser != null) onBlockedUser(); + if (onBlockedUser != null) onBlockedUser!(); }); }, ); diff --git a/lib/widgets/tiles/actions/clear_application_cache_tile.dart b/lib/widgets/tiles/actions/clear_application_cache_tile.dart index 289644420..ab2b8b3c5 100644 --- a/lib/widgets/tiles/actions/clear_application_cache_tile.dart +++ b/lib/widgets/tiles/actions/clear_application_cache_tile.dart @@ -15,7 +15,7 @@ class OBClearApplicationCacheTile extends StatefulWidget { class OBClearApplicationCacheTileState extends State { - bool _inProgress; + late bool _inProgress; @override initState() { diff --git a/lib/widgets/tiles/actions/clear_application_preferences_tile.dart b/lib/widgets/tiles/actions/clear_application_preferences_tile.dart index 95a8d9a73..b065e368b 100644 --- a/lib/widgets/tiles/actions/clear_application_preferences_tile.dart +++ b/lib/widgets/tiles/actions/clear_application_preferences_tile.dart @@ -15,7 +15,7 @@ class OBClearApplicationPreferencesTile extends StatefulWidget { class OBClearApplicationPreferencesTileState extends State { - bool _inProgress; + late bool _inProgress; @override initState() { diff --git a/lib/widgets/tiles/actions/close_post_tile.dart b/lib/widgets/tiles/actions/close_post_tile.dart index 9a377021d..502053989 100644 --- a/lib/widgets/tiles/actions/close_post_tile.dart +++ b/lib/widgets/tiles/actions/close_post_tile.dart @@ -11,12 +11,12 @@ import 'package:flutter/material.dart'; class OBClosePostTile extends StatefulWidget { final Post post; - final VoidCallback onClosePost; - final VoidCallback onOpenPost; + final VoidCallback? onClosePost; + final VoidCallback? onOpenPost; const OBClosePostTile({ - Key key, - @required this.post, + Key? key, + required this.post, this.onClosePost, this.onOpenPost, }) : super(key: key); @@ -28,10 +28,10 @@ class OBClosePostTile extends StatefulWidget { } class OBClosePostTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -50,9 +50,9 @@ class OBClosePostTileState extends State { stream: widget.post.updateSubject, initialData: widget.post, builder: (BuildContext context, AsyncSnapshot snapshot) { - var post = snapshot.data; + var post = snapshot.data!; - bool isPostClosed = post.isClosed; + bool isPostClosed = post.isClosed ?? false; return OBLoadingTile( isLoading: _requestInProgress, @@ -70,7 +70,7 @@ class OBClosePostTileState extends State { _setRequestInProgress(true); try { await _userService.openPost(widget.post); - if (widget.onClosePost != null) widget.onClosePost(); + if (widget.onClosePost != null) widget.onClosePost!(); _toastService.success(message: _localizationService.post__post_opened, context: context); } catch (e) { _onError(e); @@ -83,7 +83,7 @@ class OBClosePostTileState extends State { _setRequestInProgress(true); try { await _userService.closePost(widget.post); - if (widget.onOpenPost != null) widget.onOpenPost(); + if (widget.onOpenPost != null) widget.onOpenPost!(); _toastService.success(message: _localizationService.post__post_closed, context: context); } catch (e) { _onError(e); @@ -97,8 +97,8 @@ class OBClosePostTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/widgets/tiles/actions/disable_comments_post_tile.dart b/lib/widgets/tiles/actions/disable_comments_post_tile.dart index ca6f55f36..f6c5ab515 100644 --- a/lib/widgets/tiles/actions/disable_comments_post_tile.dart +++ b/lib/widgets/tiles/actions/disable_comments_post_tile.dart @@ -10,12 +10,12 @@ import 'package:flutter/material.dart'; class OBDisableCommentsPostTile extends StatefulWidget { final Post post; - final VoidCallback onDisableComments; - final VoidCallback onEnableComments; + final VoidCallback? onDisableComments; + final VoidCallback? onEnableComments; const OBDisableCommentsPostTile({ - Key key, - @required this.post, + Key? key, + required this.post, this.onDisableComments, this.onEnableComments, }) : super(key: key); @@ -27,10 +27,10 @@ class OBDisableCommentsPostTile extends StatefulWidget { } class OBDisableCommentsPostTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -49,9 +49,9 @@ class OBDisableCommentsPostTileState extends State { stream: widget.post.updateSubject, initialData: widget.post, builder: (BuildContext context, AsyncSnapshot snapshot) { - var post = snapshot.data; + var post = snapshot.data!; - bool areCommentsEnabled = post.areCommentsEnabled; + bool areCommentsEnabled = post.areCommentsEnabled ?? false; return ListTile( enabled: !_requestInProgress, @@ -69,7 +69,7 @@ class OBDisableCommentsPostTileState extends State { _setRequestInProgress(true); try { await _userService.enableCommentsForPost(widget.post); - if (widget.onDisableComments != null) widget.onDisableComments(); + if (widget.onDisableComments != null) widget.onDisableComments!(); _toastService.success(message: _localizationService.post__comments_enabled_message, context: context); } catch (e) { _onError(e); @@ -82,7 +82,7 @@ class OBDisableCommentsPostTileState extends State { _setRequestInProgress(true); try { await _userService.disableCommentsForPost(widget.post); - if (widget.onEnableComments != null) widget.onEnableComments(); + if (widget.onEnableComments != null) widget.onEnableComments!(); _toastService.success(message: _localizationService.post__comments_disabled_message, context: context); } catch (e) { _onError(e); @@ -96,8 +96,8 @@ class OBDisableCommentsPostTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/widgets/tiles/actions/display_profile_community_posts_toggle_tile.dart b/lib/widgets/tiles/actions/display_profile_community_posts_toggle_tile.dart index b4259ece7..fc17e7f8f 100644 --- a/lib/widgets/tiles/actions/display_profile_community_posts_toggle_tile.dart +++ b/lib/widgets/tiles/actions/display_profile_community_posts_toggle_tile.dart @@ -12,11 +12,11 @@ import 'package:flutter/material.dart'; class OBDisplayProfileCommunityPostsToggleTile extends StatefulWidget { final User user; - final ValueChanged onChanged; + final ValueChanged? onChanged; final bool hasDivider; const OBDisplayProfileCommunityPostsToggleTile( - {Key key, this.onChanged, @required this.user, this.hasDivider = false}) + {Key? key, this.onChanged, required this.user, this.hasDivider = false}) : super(key: key); @override @@ -31,13 +31,13 @@ class OBDisplayProfileCommunityPostsToggleTileState static EdgeInsetsGeometry inputContentPadding = EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0); - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; - bool _requestInProgress; + late bool _requestInProgress; - bool _communityPostsVisible; + late bool _communityPostsVisible; @override void initState() { @@ -78,7 +78,7 @@ class OBDisplayProfileCommunityPostsToggleTileState await _userService.updateUser( communityPostsVisible: _communityPostsVisible, ); - if (widget.onChanged != null) widget.onChanged(_communityPostsVisible); + if (widget.onChanged != null) widget.onChanged!(_communityPostsVisible); } catch (error) { _onError(error); } finally { @@ -91,8 +91,8 @@ class OBDisplayProfileCommunityPostsToggleTileState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/widgets/tiles/actions/display_profile_followers_count_toggle_tile.dart b/lib/widgets/tiles/actions/display_profile_followers_count_toggle_tile.dart index 859225ee8..a7b1b4477 100644 --- a/lib/widgets/tiles/actions/display_profile_followers_count_toggle_tile.dart +++ b/lib/widgets/tiles/actions/display_profile_followers_count_toggle_tile.dart @@ -12,11 +12,11 @@ import 'package:flutter/material.dart'; class OBDisplayProfileFollowersCountToggleTile extends StatefulWidget { final User user; - final ValueChanged onChanged; + final ValueChanged? onChanged; final bool hasDivider; const OBDisplayProfileFollowersCountToggleTile( - {Key key, this.onChanged, @required this.user, this.hasDivider = false}) + {Key? key, this.onChanged, required this.user, this.hasDivider = false}) : super(key: key); @override @@ -31,13 +31,13 @@ class OBDisplayProfileFollowersCountToggleTileState static EdgeInsetsGeometry inputContentPadding = EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0); - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; - bool _requestInProgress; + late bool _requestInProgress; - bool _followersCountVisible; + late bool _followersCountVisible; @override void initState() { @@ -78,7 +78,7 @@ class OBDisplayProfileFollowersCountToggleTileState await _userService.updateUser( followersCountVisible: _followersCountVisible, ); - if (widget.onChanged != null) widget.onChanged(_followersCountVisible); + if (widget.onChanged != null) widget.onChanged!(_followersCountVisible); } catch (error) { _onError(error); } finally { @@ -91,8 +91,8 @@ class OBDisplayProfileFollowersCountToggleTileState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/widgets/tiles/actions/exclude_community_from_profile_posts_tile.dart b/lib/widgets/tiles/actions/exclude_community_from_profile_posts_tile.dart index fb8ba917b..adbb5e3ac 100644 --- a/lib/widgets/tiles/actions/exclude_community_from_profile_posts_tile.dart +++ b/lib/widgets/tiles/actions/exclude_community_from_profile_posts_tile.dart @@ -14,9 +14,9 @@ class OBExcludeCommunityFromProfilePostsTile extends StatefulWidget { final ValueChanged onPostCommunityExcludedFromProfilePosts; const OBExcludeCommunityFromProfilePostsTile({ - Key key, - @required this.post, - @required this.onPostCommunityExcludedFromProfilePosts, + Key? key, + required this.post, + required this.onPostCommunityExcludedFromProfilePosts, }) : super(key: key); @override @@ -27,10 +27,10 @@ class OBExcludeCommunityFromProfilePostsTile extends StatefulWidget { class OBExcludeCommunityFromProfilePostsTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - BottomSheetService _bottomSheetService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late BottomSheetService _bottomSheetService; @override Widget build(BuildContext context) { @@ -56,7 +56,7 @@ class OBExcludeCommunityFromProfilePostsTileState actionCompleter: (BuildContext context) async { await _excludePostCommunity(); - widget.onPostCommunityExcludedFromProfilePosts(widget.post.community); + widget.onPostCommunityExcludedFromProfilePosts(widget.post.community!); _toastService.success( message: _localizationService.post__exclude_community_from_profile_posts_success, context: context); @@ -64,6 +64,6 @@ class OBExcludeCommunityFromProfilePostsTileState } Future _excludePostCommunity() async { - return _userService.excludeCommunityFromProfilePosts(widget.post.community); + return _userService.excludeCommunityFromProfilePosts(widget.post.community!); } } diff --git a/lib/widgets/tiles/actions/exclude_community_from_top_posts_tile.dart b/lib/widgets/tiles/actions/exclude_community_from_top_posts_tile.dart index fd0fb7c73..a4a7ce4a5 100644 --- a/lib/widgets/tiles/actions/exclude_community_from_top_posts_tile.dart +++ b/lib/widgets/tiles/actions/exclude_community_from_top_posts_tile.dart @@ -12,12 +12,12 @@ import 'package:async/async.dart'; class OBExcludeCommunityFromTopPostsTile extends StatefulWidget { final Post post; - final VoidCallback onExcludedPostCommunity; - final VoidCallback onUndoExcludedPostCommunity; + final VoidCallback? onExcludedPostCommunity; + final VoidCallback? onUndoExcludedPostCommunity; const OBExcludeCommunityFromTopPostsTile({ - Key key, - @required this.post, + Key? key, + required this.post, this.onExcludedPostCommunity, this.onUndoExcludedPostCommunity, }) : super(key: key); @@ -30,13 +30,13 @@ class OBExcludeCommunityFromTopPostsTile extends StatefulWidget { class OBExcludeCommunityFromTopPostsTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - CancelableOperation _excludeCommunityOperation; - CancelableOperation _undoExcludeCommunityOperation; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + CancelableOperation? _excludeCommunityOperation; + CancelableOperation? _undoExcludeCommunityOperation; - bool _requestInProgress; + late bool _requestInProgress; @override void initState() { @@ -55,7 +55,7 @@ class OBExcludeCommunityFromTopPostsTileState stream: widget.post.updateSubject, initialData: widget.post, builder: (BuildContext context, AsyncSnapshot snapshot) { - var post = snapshot.data; + var post = snapshot.data!; bool isExcluded = post.isExcludedFromTopPosts; @@ -76,9 +76,9 @@ class OBExcludeCommunityFromTopPostsTileState @override void dispose() { super.dispose(); - if (_excludeCommunityOperation != null) _excludeCommunityOperation.cancel(); + if (_excludeCommunityOperation != null) _excludeCommunityOperation!.cancel(); if (_undoExcludeCommunityOperation != null) - _undoExcludeCommunityOperation.cancel(); + _undoExcludeCommunityOperation!.cancel(); } void _excludePostCommunity() async { @@ -86,10 +86,10 @@ class OBExcludeCommunityFromTopPostsTileState _setRequestInProgress(true); try { _excludeCommunityOperation = CancelableOperation.fromFuture( - _userService.excludeCommunityFromTopPosts(widget.post.community)); - String message = await _excludeCommunityOperation.value; + _userService.excludeCommunityFromTopPosts(widget.post.community!)); + String message = await _excludeCommunityOperation!.value; if (widget.onExcludedPostCommunity != null) - widget.onExcludedPostCommunity(); + widget.onExcludedPostCommunity!(); widget.post.updateIsExcludedFromTopPosts(true); _toastService.success(message: message, context: context); } catch (e) { @@ -105,10 +105,10 @@ class OBExcludeCommunityFromTopPostsTileState _setRequestInProgress(true); try { _undoExcludeCommunityOperation = CancelableOperation.fromFuture( - _userService.undoExcludeCommunityFromTopPosts(widget.post.community)); - await _undoExcludeCommunityOperation.value; + _userService.undoExcludeCommunityFromTopPosts(widget.post.community!)); + await _undoExcludeCommunityOperation!.value; if (widget.onUndoExcludedPostCommunity != null) - widget.onUndoExcludedPostCommunity(); + widget.onUndoExcludedPostCommunity!(); _toastService.success(message: _localizationService.post__exclude_community_from_profile_posts_success, context: context); widget.post.updateIsExcludedFromTopPosts(false); } catch (e) { @@ -124,8 +124,8 @@ class OBExcludeCommunityFromTopPostsTileState _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/widgets/tiles/actions/exclude_joined_communities_from_top_posts_tile.dart b/lib/widgets/tiles/actions/exclude_joined_communities_from_top_posts_tile.dart index d06d74fe2..b83edf440 100644 --- a/lib/widgets/tiles/actions/exclude_joined_communities_from_top_posts_tile.dart +++ b/lib/widgets/tiles/actions/exclude_joined_communities_from_top_posts_tile.dart @@ -25,7 +25,7 @@ class OBExcludeJoinedCommunitiesTile extends StatelessWidget { initialData: snapshot.data, builder: (BuildContext context, AsyncSnapshot snapshot) { - bool currentExcludeJoinedCommunitiesSetting = snapshot.data; + bool currentExcludeJoinedCommunitiesSetting = snapshot.data!; return OBToggleField( key: Key('toggleExcludeJoinedCommunities'), @@ -43,4 +43,4 @@ class OBExcludeJoinedCommunitiesTile extends StatelessWidget { }, ); } -} \ No newline at end of file +} diff --git a/lib/widgets/tiles/actions/favorite_community_tile.dart b/lib/widgets/tiles/actions/favorite_community_tile.dart index bc5beafef..0dae6b9c0 100644 --- a/lib/widgets/tiles/actions/favorite_community_tile.dart +++ b/lib/widgets/tiles/actions/favorite_community_tile.dart @@ -10,14 +10,14 @@ import 'package:flutter/material.dart'; class OBFavoriteCommunityTile extends StatefulWidget { final Community community; - final VoidCallback onFavoritedCommunity; - final VoidCallback onUnfavoritedCommunity; - final Widget favoriteSubtitle; - final Widget unfavoriteSubtitle; + final VoidCallback? onFavoritedCommunity; + final VoidCallback? onUnfavoritedCommunity; + final Widget? favoriteSubtitle; + final Widget? unfavoriteSubtitle; const OBFavoriteCommunityTile( - {Key key, - @required this.community, + {Key? key, + required this.community, this.onFavoritedCommunity, this.onUnfavoritedCommunity, this.favoriteSubtitle, @@ -31,10 +31,10 @@ class OBFavoriteCommunityTile extends StatefulWidget { } class OBFavoriteCommunityTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -55,7 +55,7 @@ class OBFavoriteCommunityTileState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - bool isFavorite = community.isFavorite; + bool isFavorite = community?.isFavorite ?? false; return ListTile( enabled: !_requestInProgress, @@ -76,7 +76,7 @@ class OBFavoriteCommunityTileState extends State { _setRequestInProgress(true); try { await _userService.favoriteCommunity(widget.community); - if (widget.onFavoritedCommunity != null) widget.onFavoritedCommunity(); + if (widget.onFavoritedCommunity != null) widget.onFavoritedCommunity!(); } catch (e) { _onError(e); } finally { @@ -89,7 +89,7 @@ class OBFavoriteCommunityTileState extends State { try { await _userService.unfavoriteCommunity(widget.community); if (widget.onUnfavoritedCommunity != null) - widget.onUnfavoritedCommunity(); + widget.onUnfavoritedCommunity!(); } catch (e) { _onError(e); } finally { @@ -102,8 +102,8 @@ class OBFavoriteCommunityTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/widgets/tiles/actions/hashtags_display_setting_tile.dart b/lib/widgets/tiles/actions/hashtags_display_setting_tile.dart index ba9bded91..3612ba178 100644 --- a/lib/widgets/tiles/actions/hashtags_display_setting_tile.dart +++ b/lib/widgets/tiles/actions/hashtags_display_setting_tile.dart @@ -24,7 +24,7 @@ class OBHashtagsDisplaySettingTile extends StatelessWidget { return FutureBuilder( future: userPreferencesService.getHashtagsDisplaySetting(), builder: - (BuildContext context, AsyncSnapshot snapshot) { + (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data == null) return const SizedBox(); return StreamBuilder( @@ -32,7 +32,7 @@ class OBHashtagsDisplaySettingTile extends StatelessWidget { initialData: snapshot.data, builder: (BuildContext context, AsyncSnapshot snapshot) { - HashtagsDisplaySetting currentHashtagsDisplaySetting = snapshot.data; + HashtagsDisplaySetting currentHashtagsDisplaySetting = snapshot.data!; return MergeSemantics( child: ListTile( @@ -47,7 +47,7 @@ class OBHashtagsDisplaySettingTile extends StatelessWidget { children: [ OBPrimaryAccentText( hashtagsDisplaySettingsLocalizationMap[ - currentHashtagsDisplaySetting], + currentHashtagsDisplaySetting]!, style: TextStyle(fontSize: 16), ), ], diff --git a/lib/widgets/tiles/actions/link_previews_setting_tile.dart b/lib/widgets/tiles/actions/link_previews_setting_tile.dart index cbb912c6d..145d70c1a 100644 --- a/lib/widgets/tiles/actions/link_previews_setting_tile.dart +++ b/lib/widgets/tiles/actions/link_previews_setting_tile.dart @@ -24,7 +24,7 @@ class OBLinkPreviewsSettingTile extends StatelessWidget { return FutureBuilder( future: userPreferencesService.getLinkPreviewsSetting(), builder: - (BuildContext context, AsyncSnapshot snapshot) { + (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data == null) return const SizedBox(); return StreamBuilder( @@ -32,7 +32,7 @@ class OBLinkPreviewsSettingTile extends StatelessWidget { initialData: snapshot.data, builder: (BuildContext context, AsyncSnapshot snapshot) { - LinkPreviewsSetting currentLinkPreviewsSetting = snapshot.data; + LinkPreviewsSetting currentLinkPreviewsSetting = snapshot.data!; return MergeSemantics( child: ListTile( @@ -50,7 +50,7 @@ class OBLinkPreviewsSettingTile extends StatelessWidget { children: [ OBPrimaryAccentText( linkPreviewsSettingsLocalizationMap[ - currentLinkPreviewsSetting], + currentLinkPreviewsSetting]!, style: TextStyle(fontSize: 16), ), ], diff --git a/lib/widgets/tiles/actions/mute_post_comment_tile.dart b/lib/widgets/tiles/actions/mute_post_comment_tile.dart index 372fff890..29cdc45f6 100644 --- a/lib/widgets/tiles/actions/mute_post_comment_tile.dart +++ b/lib/widgets/tiles/actions/mute_post_comment_tile.dart @@ -13,15 +13,15 @@ import 'package:flutter/material.dart'; class OBMutePostCommentTile extends StatefulWidget { final Post post; final PostComment postComment; - final VoidCallback onMutedPostComment; - final VoidCallback onUnmutedPostComment; + final VoidCallback? onMutedPostComment; + final VoidCallback? onUnmutedPostComment; const OBMutePostCommentTile({ - Key key, - @required this.postComment, + Key? key, + required this.postComment, this.onMutedPostComment, this.onUnmutedPostComment, - @required this.post, + required this.post, }) : super(key: key); @override @@ -31,10 +31,10 @@ class OBMutePostCommentTile extends StatefulWidget { } class OBMutePostCommentTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -55,7 +55,7 @@ class OBMutePostCommentTileState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var postComment = snapshot.data; - bool isMuted = postComment.isMuted; + bool isMuted = postComment?.isMuted ?? false; return OBLoadingTile( isLoading: _requestInProgress, @@ -76,7 +76,7 @@ class OBMutePostCommentTileState extends State { await _userService.mutePostComment( post: widget.post, postComment: widget.postComment); widget.postComment.setIsMuted(true); - if (widget.onMutedPostComment != null) widget.onMutedPostComment(); + if (widget.onMutedPostComment != null) widget.onMutedPostComment!(); } catch (e) { _onError(e); } finally { @@ -90,7 +90,7 @@ class OBMutePostCommentTileState extends State { await _userService.unmutePostComment( post: widget.post, postComment: widget.postComment); widget.postComment.setIsMuted(false); - if (widget.onUnmutedPostComment != null) widget.onUnmutedPostComment(); + if (widget.onUnmutedPostComment != null) widget.onUnmutedPostComment!(); } catch (e) { _onError(e); } finally { @@ -103,8 +103,8 @@ class OBMutePostCommentTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/widgets/tiles/actions/mute_post_tile.dart b/lib/widgets/tiles/actions/mute_post_tile.dart index 0f4a7a372..6932e719f 100644 --- a/lib/widgets/tiles/actions/mute_post_tile.dart +++ b/lib/widgets/tiles/actions/mute_post_tile.dart @@ -11,12 +11,12 @@ import 'package:flutter/material.dart'; class OBMutePostTile extends StatefulWidget { final Post post; - final VoidCallback onMutedPost; - final VoidCallback onUnmutedPost; + final VoidCallback? onMutedPost; + final VoidCallback? onUnmutedPost; const OBMutePostTile({ - Key key, - @required this.post, + Key? key, + required this.post, this.onMutedPost, this.onUnmutedPost, }) : super(key: key); @@ -28,11 +28,11 @@ class OBMutePostTile extends StatefulWidget { } class OBMutePostTileState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; - bool _requestInProgress; + late bool _requestInProgress; @override void initState() { @@ -53,7 +53,7 @@ class OBMutePostTileState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var post = snapshot.data; - bool isMuted = post.isMuted; + bool isMuted = post?.isMuted ?? false; return OBLoadingTile( isLoading: _requestInProgress, @@ -71,7 +71,7 @@ class OBMutePostTileState extends State { _setRequestInProgress(true); try { await _userService.mutePost(widget.post); - if (widget.onMutedPost != null) widget.onMutedPost(); + if (widget.onMutedPost != null) widget.onMutedPost!(); } catch (e) { _onError(e); } finally { @@ -83,7 +83,7 @@ class OBMutePostTileState extends State { _setRequestInProgress(true); try { await _userService.unmutePost(widget.post); - if (widget.onUnmutedPost != null) widget.onUnmutedPost(); + if (widget.onUnmutedPost != null) widget.onUnmutedPost!(); } catch (e) { _onError(e); } finally { @@ -96,8 +96,8 @@ class OBMutePostTileState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error(message: _localizationService.error__unknown_error, context: context); throw error; diff --git a/lib/widgets/tiles/actions/new_post_notifications_for_community_tile.dart b/lib/widgets/tiles/actions/new_post_notifications_for_community_tile.dart index a174ccde8..383a9e0c2 100644 --- a/lib/widgets/tiles/actions/new_post_notifications_for_community_tile.dart +++ b/lib/widgets/tiles/actions/new_post_notifications_for_community_tile.dart @@ -9,14 +9,14 @@ import 'package:flutter/material.dart'; class OBNewPostNotificationsForCommunityTile extends StatefulWidget { final Community community; - final VoidCallback onSubscribed; - final VoidCallback onUnsubscribed; - final Widget title; - final Widget subtitle; + final VoidCallback? onSubscribed; + final VoidCallback? onUnsubscribed; + final Widget? title; + final Widget? subtitle; const OBNewPostNotificationsForCommunityTile({ - Key key, - @required this.community, + Key? key, + required this.community, this.onSubscribed, this.onUnsubscribed, this.title, @@ -30,10 +30,10 @@ class OBNewPostNotificationsForCommunityTile extends StatefulWidget { } class OBNewPostNotificationsForCommunityTileState extends State { - bool _requestInProgress; - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; + late bool _requestInProgress; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; @override void initState() { @@ -54,7 +54,7 @@ class OBNewPostNotificationsForCommunityTileState extends State snapshot) { var community = snapshot.data; - bool areNotificationsEnabled = community.areNewPostNotificationsEnabled ?? false; + bool areNotificationsEnabled = community?.areNewPostNotificationsEnabled ?? false; return ListTile( enabled: !_requestInProgress, @@ -78,7 +78,7 @@ class OBNewPostNotificationsForCommunityTileState extends State onCommunityReported; - final VoidCallback onWantsToReportCommunity; + final ValueChanged? onCommunityReported; + final VoidCallback? onWantsToReportCommunity; const OBReportCommunityTile({ - Key key, + Key? key, this.onCommunityReported, - @required this.community, + required this.community, this.onWantsToReportCommunity, }) : super(key: key); @@ -26,8 +26,8 @@ class OBReportCommunityTile extends StatefulWidget { } class OBReportCommunityTileState extends State { - NavigationService _navigationService; - bool _requestInProgress; + late NavigationService _navigationService; + late bool _requestInProgress; @override void initState() { @@ -47,7 +47,7 @@ class OBReportCommunityTileState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var community = snapshot.data; - bool isReported = community.isReported ?? false; + bool isReported = community?.isReported ?? false; return OBLoadingTile( isLoading: _requestInProgress || isReported, @@ -63,7 +63,7 @@ class OBReportCommunityTileState extends State { void _reportCommunity() { if (widget.onWantsToReportCommunity != null) - widget.onWantsToReportCommunity(); + widget.onWantsToReportCommunity!(); _navigationService.navigateToReportObject( context: context, object: widget.community, diff --git a/lib/widgets/tiles/actions/report_hashtag_tile.dart b/lib/widgets/tiles/actions/report_hashtag_tile.dart index e95b00220..d79563eee 100644 --- a/lib/widgets/tiles/actions/report_hashtag_tile.dart +++ b/lib/widgets/tiles/actions/report_hashtag_tile.dart @@ -9,13 +9,13 @@ import 'package:flutter/material.dart'; class OBReportHashtagTile extends StatefulWidget { final Hashtag hashtag; - final ValueChanged onHashtagReported; - final VoidCallback onWantsToReportHashtag; + final ValueChanged? onHashtagReported; + final VoidCallback? onWantsToReportHashtag; const OBReportHashtagTile({ - Key key, + Key? key, this.onHashtagReported, - @required this.hashtag, + required this.hashtag, this.onWantsToReportHashtag, }) : super(key: key); @@ -26,9 +26,9 @@ class OBReportHashtagTile extends StatefulWidget { } class OBReportHashtagTileState extends State { - NavigationService _navigationService; - LocalizationService _localizationService; - bool _requestInProgress; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -63,13 +63,13 @@ class OBReportHashtagTileState extends State { } void _reportHashtag() { - if (widget.onWantsToReportHashtag != null) widget.onWantsToReportHashtag(); + if (widget.onWantsToReportHashtag != null) widget.onWantsToReportHashtag!(); _navigationService.navigateToReportObject( context: context, object: widget.hashtag, onObjectReported: (dynamic reportedObject) { if (reportedObject != null && widget.onHashtagReported != null) - widget.onHashtagReported(reportedObject as Hashtag); + widget.onHashtagReported!(reportedObject as Hashtag); }); } } diff --git a/lib/widgets/tiles/actions/report_post_comment_tile.dart b/lib/widgets/tiles/actions/report_post_comment_tile.dart index 3bc6fd744..e7d86a21e 100644 --- a/lib/widgets/tiles/actions/report_post_comment_tile.dart +++ b/lib/widgets/tiles/actions/report_post_comment_tile.dart @@ -9,13 +9,13 @@ import 'package:flutter/material.dart'; class OBReportPostCommentTile extends StatefulWidget { final PostComment postComment; - final ValueChanged onPostCommentReported; - final VoidCallback onWantsToReportPostComment; + final ValueChanged? onPostCommentReported; + final VoidCallback? onWantsToReportPostComment; const OBReportPostCommentTile({ - Key key, + Key? key, this.onPostCommentReported, - @required this.postComment, + required this.postComment, this.onWantsToReportPostComment, }) : super(key: key); @@ -26,8 +26,8 @@ class OBReportPostCommentTile extends StatefulWidget { } class OBReportPostCommentTileState extends State { - NavigationService _navigationService; - bool _requestInProgress; + late NavigationService _navigationService; + late bool _requestInProgress; @override void initState() { @@ -47,7 +47,7 @@ class OBReportPostCommentTileState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var postComment = snapshot.data; - bool isReported = postComment.isReported ?? false; + bool isReported = postComment?.isReported ?? false; return OBLoadingTile( isLoading: _requestInProgress || isReported, @@ -62,7 +62,7 @@ class OBReportPostCommentTileState extends State { void _reportPostComment() { if (widget.onWantsToReportPostComment != null) - widget.onWantsToReportPostComment(); + widget.onWantsToReportPostComment!(); _navigationService.navigateToReportObject( context: context, object: widget.postComment, diff --git a/lib/widgets/tiles/actions/report_post_tile.dart b/lib/widgets/tiles/actions/report_post_tile.dart index 3ad19e7d6..b9a87bc93 100644 --- a/lib/widgets/tiles/actions/report_post_tile.dart +++ b/lib/widgets/tiles/actions/report_post_tile.dart @@ -9,13 +9,13 @@ import 'package:flutter/material.dart'; class OBReportPostTile extends StatefulWidget { final Post post; - final ValueChanged onPostReported; - final VoidCallback onWantsToReportPost; + final ValueChanged? onPostReported; + final VoidCallback? onWantsToReportPost; const OBReportPostTile({ - Key key, + Key? key, this.onPostReported, - @required this.post, + required this.post, this.onWantsToReportPost, }) : super(key: key); @@ -26,9 +26,9 @@ class OBReportPostTile extends StatefulWidget { } class OBReportPostTileState extends State { - NavigationService _navigationService; - LocalizationService _localizationService; - bool _requestInProgress; + late NavigationService _navigationService; + late LocalizationService _localizationService; + late bool _requestInProgress; @override void initState() { @@ -48,7 +48,7 @@ class OBReportPostTileState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var post = snapshot.data; - bool isReported = post.isReported ?? false; + bool isReported = post?.isReported ?? false; return OBLoadingTile( isLoading: _requestInProgress || isReported, @@ -62,13 +62,13 @@ class OBReportPostTileState extends State { } void _reportPost() { - if (widget.onWantsToReportPost != null) widget.onWantsToReportPost(); + if (widget.onWantsToReportPost != null) widget.onWantsToReportPost!(); _navigationService.navigateToReportObject( context: context, object: widget.post, onObjectReported: (dynamic reportedObject) { if (reportedObject != null && widget.onPostReported != null) - widget.onPostReported(reportedObject as Post); + widget.onPostReported!(reportedObject as Post); }); } } diff --git a/lib/widgets/tiles/actions/report_user_tile.dart b/lib/widgets/tiles/actions/report_user_tile.dart index 6f1e5a705..6f249bcdb 100644 --- a/lib/widgets/tiles/actions/report_user_tile.dart +++ b/lib/widgets/tiles/actions/report_user_tile.dart @@ -9,13 +9,13 @@ import 'package:flutter/material.dart'; class OBReportUserTile extends StatefulWidget { final User user; - final ValueChanged onUserReported; - final VoidCallback onWantsToReportUser; + final ValueChanged? onUserReported; + final VoidCallback? onWantsToReportUser; const OBReportUserTile({ - Key key, + Key? key, this.onUserReported, - @required this.user, + required this.user, this.onWantsToReportUser, }) : super(key: key); @@ -26,8 +26,8 @@ class OBReportUserTile extends StatefulWidget { } class OBReportUserTileState extends State { - NavigationService _navigationService; - bool _requestInProgress; + late NavigationService _navigationService; + late bool _requestInProgress; @override void initState() { @@ -47,7 +47,7 @@ class OBReportUserTileState extends State { builder: (BuildContext context, AsyncSnapshot snapshot) { var user = snapshot.data; - bool isReported = user.isReported ?? false; + bool isReported = user?.isReported ?? false; return OBLoadingTile( isLoading: _requestInProgress || isReported, @@ -61,7 +61,7 @@ class OBReportUserTileState extends State { } void _reportUser() { - if (widget.onWantsToReportUser != null) widget.onWantsToReportUser(); + if (widget.onWantsToReportUser != null) widget.onWantsToReportUser!(); _navigationService.navigateToReportObject( context: context, object: widget.user, diff --git a/lib/widgets/tiles/actions/user_visibility_tile.dart b/lib/widgets/tiles/actions/user_visibility_tile.dart index 4bba541b9..2015a98f9 100644 --- a/lib/widgets/tiles/actions/user_visibility_tile.dart +++ b/lib/widgets/tiles/actions/user_visibility_tile.dart @@ -23,23 +23,23 @@ class OBUserVisibilityTile extends StatelessWidget { userService.getUserVisibilityLocalizationMap(); return StreamBuilder( - stream: userService.getLoggedInUser().updateSubject, + stream: userService.getLoggedInUser()!.updateSubject, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data == null) return const SizedBox(); - UserVisibility currentUserVisibility = snapshot.data.visibility; + UserVisibility currentUserVisibility = snapshot.data!.visibility!; - var visibilityLocalizationsMap = userVisibilitiesLocalizationMap[currentUserVisibility]; + var visibilityLocalizationsMap = userVisibilitiesLocalizationMap[currentUserVisibility]!; return ListTile( leading: OBUserVisibilityIcon(visibility: currentUserVisibility), - title: OBText(visibilityLocalizationsMap['title']), + title: OBText(visibilityLocalizationsMap['title']!), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ OBText( - visibilityLocalizationsMap['description'], + visibilityLocalizationsMap['description']!, size: OBTextSize.mediumSecondary, ), OBText( diff --git a/lib/widgets/tiles/actions/videos_autoplay_setting_tile.dart b/lib/widgets/tiles/actions/videos_autoplay_setting_tile.dart index 2957b44fa..96f1e2126 100644 --- a/lib/widgets/tiles/actions/videos_autoplay_setting_tile.dart +++ b/lib/widgets/tiles/actions/videos_autoplay_setting_tile.dart @@ -24,7 +24,7 @@ class OBVideosAutoPlaySettingTile extends StatelessWidget { return FutureBuilder( future: userPreferencesService.getVideosAutoPlaySetting(), builder: - (BuildContext context, AsyncSnapshot snapshot) { + (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data == null) return const SizedBox(); return StreamBuilder( @@ -32,7 +32,7 @@ class OBVideosAutoPlaySettingTile extends StatelessWidget { initialData: snapshot.data, builder: (BuildContext context, AsyncSnapshot snapshot) { - VideosAutoPlaySetting currentVideosAutoPlaySetting = snapshot.data; + VideosAutoPlaySetting currentVideosAutoPlaySetting = snapshot.data!; return MergeSemantics( child: ListTile( @@ -47,7 +47,7 @@ class OBVideosAutoPlaySettingTile extends StatelessWidget { children: [ OBPrimaryAccentText( videosAutoPlaySettingsLocalizationMap[ - currentVideosAutoPlaySetting], + currentVideosAutoPlaySetting]!, style: TextStyle(fontSize: 16), ), ], diff --git a/lib/widgets/tiles/actions/videos_sound_setting_tile.dart b/lib/widgets/tiles/actions/videos_sound_setting_tile.dart index 9c97f5fb1..aacaa2ac1 100644 --- a/lib/widgets/tiles/actions/videos_sound_setting_tile.dart +++ b/lib/widgets/tiles/actions/videos_sound_setting_tile.dart @@ -24,7 +24,7 @@ class OBVideosSoundSettingTile extends StatelessWidget { return FutureBuilder( future: userPreferencesService.getVideosSoundSetting(), builder: - (BuildContext context, AsyncSnapshot snapshot) { + (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.data == null) return const SizedBox(); return StreamBuilder( @@ -32,7 +32,7 @@ class OBVideosSoundSettingTile extends StatelessWidget { initialData: snapshot.data, builder: (BuildContext context, AsyncSnapshot snapshot) { - VideosSoundSetting currentVideosSoundSetting = snapshot.data; + VideosSoundSetting currentVideosSoundSetting = snapshot.data!; return MergeSemantics( child: ListTile( @@ -47,7 +47,7 @@ class OBVideosSoundSettingTile extends StatelessWidget { children: [ OBPrimaryAccentText( videosSoundSettingsLocalizationMap[ - currentVideosSoundSetting], + currentVideosSoundSetting]!, style: TextStyle(fontSize: 16), ), ], diff --git a/lib/widgets/tiles/circle_selectable_tile.dart b/lib/widgets/tiles/circle_selectable_tile.dart index 144652e7f..a5e861a48 100644 --- a/lib/widgets/tiles/circle_selectable_tile.dart +++ b/lib/widgets/tiles/circle_selectable_tile.dart @@ -9,27 +9,32 @@ import '../../provider.dart'; class OBCircleSelectableTile extends StatelessWidget { final Circle circle; - final OnCirclePressed onCirclePressed; - final bool isSelected; + final OnCirclePressed? onCirclePressed; + final bool? isSelected; final bool isDisabled; const OBCircleSelectableTile(this.circle, - {Key key, this.onCirclePressed, this.isSelected, this.isDisabled = false}) + {Key? key, this.onCirclePressed, this.isSelected, this.isDisabled = false}) : super(key: key); @override Widget build(BuildContext context) { - int usersCount = circle.usersCount; + int? usersCount = circle.usersCount; LocalizationService localizationService = OpenbookProvider.of(context).localizationService; - String prettyCount = getPrettyCount(usersCount, localizationService); + String? prettyCount = usersCount != null + ? getPrettyCount(usersCount, localizationService) + : null; + return OBCheckboxField( isDisabled: isDisabled, - value: isSelected, - title: circle.name, + value: isSelected ?? false, + title: circle.name!, subtitle: - usersCount != null ? localizationService.user__circle_peoples_count(prettyCount) : null, + usersCount != null ? localizationService.user__circle_peoples_count(prettyCount!) : null, onTap: () { - onCirclePressed(circle); + if (onCirclePressed != null) { + onCirclePressed!(circle); + } }, leading: SizedBox( height: 40, diff --git a/lib/widgets/tiles/community_selectable_tile.dart b/lib/widgets/tiles/community_selectable_tile.dart index eae66d08d..cc4ed6ee7 100644 --- a/lib/widgets/tiles/community_selectable_tile.dart +++ b/lib/widgets/tiles/community_selectable_tile.dart @@ -9,10 +9,10 @@ class OBCommunitySelectableTile extends StatelessWidget { final bool isSelected; const OBCommunitySelectableTile( - {Key key, - @required this.community, - @required this.onCommunityPressed, - @required this.isSelected}) + {Key? key, + required this.community, + required this.onCommunityPressed, + required this.isSelected}) : super(key: key); @override diff --git a/lib/widgets/tiles/community_tile.dart b/lib/widgets/tiles/community_tile.dart index 16317940b..f2dd3f3ea 100644 --- a/lib/widgets/tiles/community_tile.dart +++ b/lib/widgets/tiles/community_tile.dart @@ -19,22 +19,22 @@ class OBCommunityTile extends StatelessWidget { static const double normalSizeHeight = 80; final Community community; - final ValueChanged onCommunityTilePressed; - final ValueChanged onCommunityTileDeleted; + final ValueChanged? onCommunityTilePressed; + final ValueChanged? onCommunityTileDeleted; final OBCommunityTileSize size; - final Widget trailing; + final Widget? trailing; const OBCommunityTile(this.community, {this.onCommunityTilePressed, this.onCommunityTileDeleted, - Key key, + Key? key, this.size = OBCommunityTileSize.normal, this.trailing}) : super(key: key); @override Widget build(BuildContext context) { - String communityHexColor = community.color; + String communityHexColor = community.color!; LocalizationService localizationService = OpenbookProvider.of(context).localizationService; ThemeService themeService = OpenbookProvider.of(context).themeService; @@ -59,7 +59,7 @@ class OBCommunityTile extends StatelessWidget { fit: BoxFit.cover, colorFilter: new ColorFilter.mode( Colors.black.withOpacity(0.60), BlendMode.darken), - image: AdvancedNetworkImage(community.cover, + image: AdvancedNetworkImage(community.cover!, useDiskCache: true, fallbackAssetImage: COVER_PLACEHOLDER, retryLimit: 0))); @@ -90,7 +90,7 @@ class OBCommunityTile extends StatelessWidget { ? TinyColor(communityColor).lighten(5).color : communityColor); communityAvatar = OBLetterAvatar( - letter: community.name[0], + letter: community.name![0], color: avatarColor, labelColor: textColor, size: isNormalSize ? OBAvatarSize.medium : OBAvatarSize.small, @@ -101,8 +101,8 @@ class OBCommunityTile extends StatelessWidget { localizationService.community__member_capitalized; String usersAdjective = community.usersAdjective ?? localizationService.community__members_capitalized; - String membersPrettyCount = community.membersCount != null - ? getPrettyCount(community.membersCount, localizationService) + String? membersPrettyCount = community.membersCount != null + ? getPrettyCount(community.membersCount!, localizationService) : null; String finalAdjective = community.membersCount == 1 ? userAdjective : usersAdjective; @@ -122,14 +122,14 @@ class OBCommunityTile extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ - Text('c/' + community.name, + Text('c/' + community.name!, style: TextStyle( color: textColor, fontSize: 16, ), overflow: TextOverflow.ellipsis), Text( - community.title, + community.title!, style: TextStyle( color: textColor, fontSize: 18, @@ -164,7 +164,7 @@ class OBCommunityTile extends StatelessWidget { actionExtentRatio: 0.25, child: GestureDetector( onTap: () { - onCommunityTilePressed(community); + onCommunityTilePressed!(community); }, child: communityTile, ), @@ -176,14 +176,14 @@ class OBCommunityTile extends StatelessWidget { color: Colors.transparent, icon: Icons.delete, onTap: () { - onCommunityTileDeleted(community); + onCommunityTileDeleted!(community); }), ], ); } else if (onCommunityTilePressed != null) { communityTile = GestureDetector( onTap: () { - onCommunityTilePressed(community); + onCommunityTilePressed!(community); }, child: communityTile, ); diff --git a/lib/widgets/tiles/follows_list_selectable_tile.dart b/lib/widgets/tiles/follows_list_selectable_tile.dart index 33ac719d3..a7a61c0b1 100644 --- a/lib/widgets/tiles/follows_list_selectable_tile.dart +++ b/lib/widgets/tiles/follows_list_selectable_tile.dart @@ -9,12 +9,12 @@ import '../../provider.dart'; class OBFollowsListSelectableTile extends StatelessWidget { final FollowsList followsList; - final OnFollowsListPressed onFollowsListPressed; - final bool isSelected; + final OnFollowsListPressed? onFollowsListPressed; + final bool? isSelected; final bool isDisabled; const OBFollowsListSelectableTile(this.followsList, - {Key key, + {Key? key, this.onFollowsListPressed, this.isSelected, this.isDisabled = false}) @@ -22,25 +22,29 @@ class OBFollowsListSelectableTile extends StatelessWidget { @override Widget build(BuildContext context) { - int usersCount = followsList.followsCount; + int? usersCount = followsList.followsCount; LocalizationService localizationService = OpenbookProvider.of(context).localizationService; - String prettyCount = getPrettyCount(usersCount, localizationService); + String? prettyCount = usersCount != null + ? getPrettyCount(usersCount, localizationService) + : null; return OBCheckboxField( isDisabled: isDisabled, - value: isSelected, - title: followsList.name, + value: isSelected ?? false, + title: followsList.name!, subtitle: - usersCount != null ? localizationService.user__follows_list_accounts_count(prettyCount) : null, + usersCount != null ? localizationService.user__follows_list_accounts_count(prettyCount!) : null, onTap: () { - onFollowsListPressed(followsList); + if (onFollowsListPressed != null) { + onFollowsListPressed!(followsList); + } }, leading: SizedBox( height: 40, width: 40, child: Center( child: OBEmojiPreview( - followsList.emoji, + followsList.emoji!, size: OBEmojiPreviewSize.medium, ), ), diff --git a/lib/widgets/tiles/hashtag_tile.dart b/lib/widgets/tiles/hashtag_tile.dart index a10ee687a..4752695b2 100644 --- a/lib/widgets/tiles/hashtag_tile.dart +++ b/lib/widgets/tiles/hashtag_tile.dart @@ -8,11 +8,11 @@ import 'package:flutter/material.dart'; class OBHashtagTile extends StatelessWidget { final Hashtag hashtag; - final ValueChanged onHashtagTilePressed; - final ValueChanged onHashtagTileDeleted; + final ValueChanged? onHashtagTilePressed; + final ValueChanged? onHashtagTileDeleted; const OBHashtagTile(this.hashtag, - {Key key, + {Key? key, this.onHashtagTilePressed, this.onHashtagTileDeleted}) : super(key: key); @@ -21,7 +21,7 @@ class OBHashtagTile extends StatelessWidget { Widget build(BuildContext context) { Widget tile = ListTile( onTap: () { - if (onHashtagTilePressed != null) onHashtagTilePressed(hashtag); + if (onHashtagTilePressed != null) onHashtagTilePressed!(hashtag); }, leading: OBHashtagAvatar( key: Key('Avatar-${hashtag.name}'), @@ -53,4 +53,3 @@ class OBHashtagTile extends StatelessWidget { } } - diff --git a/lib/widgets/tiles/loading_tile.dart b/lib/widgets/tiles/loading_tile.dart index 53a497bc8..c010e87a7 100644 --- a/lib/widgets/tiles/loading_tile.dart +++ b/lib/widgets/tiles/loading_tile.dart @@ -5,14 +5,14 @@ import 'package:flutter/material.dart'; class OBLoadingTile extends StatelessWidget { final bool isLoading; - final Widget title; - final Widget subtitle; - final Widget leading; - final Widget trailing; - final VoidCallback onTap; + final Widget? title; + final Widget? subtitle; + final Widget? leading; + final Widget? trailing; + final VoidCallback? onTap; const OBLoadingTile( - {Key key, + {Key? key, this.isLoading = false, this.title, this.subtitle, diff --git a/lib/widgets/tiles/moderated_object_status_tile.dart b/lib/widgets/tiles/moderated_object_status_tile.dart index 6a5baf267..0a185dfee 100644 --- a/lib/widgets/tiles/moderated_object_status_tile.dart +++ b/lib/widgets/tiles/moderated_object_status_tile.dart @@ -9,14 +9,14 @@ import '../moderated_object_status_circle.dart'; class OBModeratedObjectStatusTile extends StatelessWidget { final ModeratedObject moderatedObject; - final ValueChanged onPressed; - final Widget trailing; + final ValueChanged? onPressed; + final Widget? trailing; static double statusCircleSize = 10; static String pendingColor = '#f48c42'; const OBModeratedObjectStatusTile( - {Key key, @required this.moderatedObject, this.onPressed, this.trailing}) + {Key? key, required this.moderatedObject, this.onPressed, this.trailing}) : super(key: key); @override @@ -25,24 +25,24 @@ class OBModeratedObjectStatusTile extends StatelessWidget { stream: moderatedObject.updateSubject, initialData: moderatedObject, builder: (BuildContext context, AsyncSnapshot snapshot) { - ModeratedObject currentModeratedObject = snapshot.data; + ModeratedObject currentModeratedObject = snapshot.data!; return ListTile( title: Row( children: [ OBModeratedObjectStatusCircle( - status: moderatedObject.status, + status: moderatedObject.status!, ), const SizedBox( width: 10, ), OBText(ModeratedObject.factory.convertStatusToHumanReadableString( currentModeratedObject.status, - capitalize: true)) + capitalize: true) ?? '') ], ), onTap: () async { - if (onPressed != null) onPressed(moderatedObject); + if (onPressed != null) onPressed!(moderatedObject); }, trailing: trailing, ); diff --git a/lib/widgets/tiles/moderation_category_tile.dart b/lib/widgets/tiles/moderation_category_tile.dart index a1e2aad01..1798e9293 100644 --- a/lib/widgets/tiles/moderation_category_tile.dart +++ b/lib/widgets/tiles/moderation_category_tile.dart @@ -6,14 +6,14 @@ import 'package:flutter/material.dart'; class OBModerationCategoryTile extends StatelessWidget { final ModerationCategory category; - final Widget trailing; - final ValueChanged onPressed; - final EdgeInsets contentPadding; + final Widget? trailing; + final ValueChanged? onPressed; + final EdgeInsets? contentPadding; const OBModerationCategoryTile( - {Key key, + {Key? key, this.trailing, - @required this.category, + required this.category, this.onPressed, this.contentPadding}) : super(key: key); @@ -23,14 +23,14 @@ class OBModerationCategoryTile extends StatelessWidget { return GestureDetector( key: Key(category.id.toString()), onTap: () { - if (onPressed != null) onPressed(category); + if (onPressed != null) onPressed!(category); }, child: ListTile( contentPadding: contentPadding, title: OBText( - category.title, + category.title!, ), - subtitle: OBSecondaryText(category.description), + subtitle: OBSecondaryText(category.description ?? ''), trailing: trailing, //trailing: OBIcon(OBIcons.chevronRight), ), diff --git a/lib/widgets/tiles/notification_tile/notification_tile.dart b/lib/widgets/tiles/notification_tile/notification_tile.dart index c4bee2981..c585c257e 100644 --- a/lib/widgets/tiles/notification_tile/notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/notification_tile.dart @@ -33,12 +33,12 @@ import 'package:flutter_slidable/flutter_slidable.dart'; class OBNotificationTile extends StatelessWidget { final OBNotification notification; - final ValueChanged onNotificationTileDeleted; - final ValueChanged onPressed; + final ValueChanged? onNotificationTileDeleted; + final ValueChanged? onPressed; const OBNotificationTile( - {Key key, - @required this.notification, + {Key? key, + required this.notification, this.onNotificationTileDeleted, this.onPressed}) : super(key: key); @@ -64,7 +64,7 @@ class OBNotificationTile extends StatelessWidget { Widget _buildNotificationBackground( BuildContext context, AsyncSnapshot snapshot) { - return snapshot.data.read ? const SizedBox() : OBHighlightedBox(); + return snapshot.data?.read == true ? const SizedBox() : OBHighlightedBox(); } Widget _buildNotification(OBNotification notification) { @@ -72,9 +72,9 @@ class OBNotificationTile extends StatelessWidget { dynamic notificationContentObject = this.notification.contentObject; - Function finalOnPressed = onPressed != null + VoidCallback? finalOnPressed = onPressed != null ? () { - onPressed(notification); + onPressed!(notification); } : null; @@ -197,7 +197,9 @@ class OBNotificationTile extends StatelessWidget { color: Colors.red, icon: Icons.delete, onTap: () { - onNotificationTileDeleted(notification); + if (onNotificationTileDeleted != null) { + onNotificationTileDeleted!(notification); + } }, ), ], diff --git a/lib/widgets/tiles/notification_tile/notification_tile_post_media_preview.dart b/lib/widgets/tiles/notification_tile/notification_tile_post_media_preview.dart index 2396b5489..332e0877f 100644 --- a/lib/widgets/tiles/notification_tile/notification_tile_post_media_preview.dart +++ b/lib/widgets/tiles/notification_tile/notification_tile_post_media_preview.dart @@ -7,7 +7,7 @@ class OBNotificationTilePostMediaPreview extends StatelessWidget { static final double postMediaPreviewSize = 40; final Post post; - const OBNotificationTilePostMediaPreview({Key key, @required this.post}) : super(key: key); + const OBNotificationTilePostMediaPreview({Key? key, required this.post}) : super(key: key); @override Widget build(BuildContext context) { @@ -20,7 +20,7 @@ class OBNotificationTilePostMediaPreview extends StatelessWidget { loadingWidget: const SizedBox(), fit: BoxFit.cover, alignment: Alignment.center, - image: AdvancedNetworkImage(post.mediaThumbnail, + image: AdvancedNetworkImage(post.mediaThumbnail ?? '', useDiskCache: true, fallbackAssetImage: 'assets/images/fallbacks/post-fallback.png', retryLimit: 3, diff --git a/lib/widgets/tiles/notification_tile/widgets/community_invite_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/community_invite_notification_tile.dart index f7b5cde13..2f21deffc 100644 --- a/lib/widgets/tiles/notification_tile/widgets/community_invite_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/community_invite_notification_tile.dart @@ -16,29 +16,29 @@ import 'notification_tile_title.dart'; class OBCommunityInviteNotificationTile extends StatelessWidget { final OBNotification notification; final CommunityInviteNotification communityInviteNotification; - final VoidCallback onPressed; + final VoidCallback? onPressed; static final double postImagePreviewSize = 40; const OBCommunityInviteNotificationTile( - {Key key, - @required this.notification, - @required this.communityInviteNotification, + {Key? key, + required this.notification, + required this.communityInviteNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { CommunityInvite communityInvite = - communityInviteNotification.communityInvite; - User inviteCreator = communityInvite.creator; - Community community = communityInvite.community; + communityInviteNotification.communityInvite!; + User inviteCreator = communityInvite.creator!; + Community community = communityInvite.community!; - String communityName = community.name; + String communityName = community.name!; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); var utilsService = openbookProvider.utilsService; - Function navigateToInviteCreatorProfile = () { + VoidCallback navigateToInviteCreatorProfile = () { openbookProvider.navigationService .navigateToUserProfile(user: inviteCreator, context: context); }; @@ -46,7 +46,7 @@ class OBCommunityInviteNotificationTile extends StatelessWidget { return OBNotificationTileSkeleton( onTap: () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService @@ -67,7 +67,7 @@ class OBCommunityInviteNotificationTile extends StatelessWidget { community: community, size: OBAvatarSize.medium, ), - subtitle: OBSecondaryText(utilsService.timeAgo(notification.created, _localizationService)), + subtitle: OBSecondaryText(utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/notification_tile/widgets/community_new_post_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/community_new_post_notification_tile.dart index 47341b319..d74347dac 100644 --- a/lib/widgets/tiles/notification_tile/widgets/community_new_post_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/community_new_post_notification_tile.dart @@ -16,20 +16,20 @@ class OBCommunityNewPostNotificationTile extends StatelessWidget { final OBNotification notification; final CommunityNewPostNotification communityNewPostNotification; static final double postImagePreviewSize = 40; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBCommunityNewPostNotificationTile( - {Key key, - @required this.notification, - @required this.communityNewPostNotification, + {Key? key, + required this.notification, + required this.communityNewPostNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { - Post post = communityNewPostNotification.post; + Post post = communityNewPostNotification.post!; - Widget postImagePreview; + Widget? postImagePreview; if (post.hasMediaThumbnail()) { postImagePreview = Padding( padding: const EdgeInsets.only(left: 10), @@ -42,14 +42,14 @@ class OBCommunityNewPostNotificationTile extends StatelessWidget { LocalizationService _localizationService = openbookProvider.localizationService; - Function navigateToCommunity = () { + VoidCallback navigateToCommunity = () { openbookProvider.navigationService - .navigateToCommunity(community: post.community, context: context); + .navigateToCommunity(community: post.community!, context: context); }; return OBNotificationTileSkeleton( onTap: () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService .navigateToPost(post: post, context: context); @@ -57,14 +57,14 @@ class OBCommunityNewPostNotificationTile extends StatelessWidget { leading: OBCommunityAvatar( onPressed: navigateToCommunity, size: OBAvatarSize.medium, - community: post.community, + community: post.community!, ), title: OBNotificationTileTitle( text: TextSpan( - text: _localizationService.notifications__community_new_post_tile(post.community.name)), + text: _localizationService.notifications__community_new_post_tile(post.community!.name!)), ), subtitle: OBSecondaryText( - utilsService.timeAgo(notification.created, _localizationService)), + utilsService.timeAgo(notification.created!, _localizationService)), trailing: postImagePreview, ); } diff --git a/lib/widgets/tiles/notification_tile/widgets/connection_confirmed_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/connection_confirmed_notification_tile.dart index 7bc6129e2..4b105f8fd 100644 --- a/lib/widgets/tiles/notification_tile/widgets/connection_confirmed_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/connection_confirmed_notification_tile.dart @@ -13,12 +13,12 @@ import 'notification_tile_title.dart'; class OBConnectionConfirmedNotificationTile extends StatelessWidget { final OBNotification notification; final ConnectionConfirmedNotification connectionConfirmedNotification; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBConnectionConfirmedNotificationTile( - {Key key, - @required this.notification, - @required this.connectionConfirmedNotification, + {Key? key, + required this.notification, + required this.connectionConfirmedNotification, this.onPressed}) : super(key: key); @@ -28,10 +28,10 @@ class OBConnectionConfirmedNotificationTile extends StatelessWidget { var utilsService = openbookProvider.utilsService; var navigateToConfirmatorProfile = () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService.navigateToUserProfile( - user: connectionConfirmedNotification.connectionConfirmator, + user: connectionConfirmedNotification.connectionConfirmator!, context: context); }; LocalizationService _localizationService = OpenbookProvider.of(context).localizationService; @@ -40,7 +40,7 @@ class OBConnectionConfirmedNotificationTile extends StatelessWidget { onTap: navigateToConfirmatorProfile, leading: OBAvatar( size: OBAvatarSize.medium, - avatarUrl: connectionConfirmedNotification.connectionConfirmator + avatarUrl: connectionConfirmedNotification.connectionConfirmator! .getProfileAvatar(), ), title: OBNotificationTileTitle( @@ -48,7 +48,7 @@ class OBConnectionConfirmedNotificationTile extends StatelessWidget { user: connectionConfirmedNotification.connectionConfirmator, text: TextSpan(text: _localizationService.notifications__accepted_connection_request_tile), ), - subtitle: OBSecondaryText(utilsService.timeAgo(notification.created, _localizationService)), + subtitle: OBSecondaryText(utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/notification_tile/widgets/connection_request_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/connection_request_notification_tile.dart index 12798fdb2..e42c22444 100644 --- a/lib/widgets/tiles/notification_tile/widgets/connection_request_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/connection_request_notification_tile.dart @@ -12,12 +12,12 @@ import 'notification_tile_title.dart'; class OBConnectionRequestNotificationTile extends StatelessWidget { final OBNotification notification; final ConnectionRequestNotification connectionRequestNotification; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBConnectionRequestNotificationTile( - {Key key, - @required this.notification, - @required this.connectionRequestNotification, + {Key? key, + required this.notification, + required this.connectionRequestNotification, this.onPressed}) : super(key: key); @@ -28,11 +28,11 @@ class OBConnectionRequestNotificationTile extends StatelessWidget { LocalizationService _localizationService = openbookProvider.localizationService; var navigateToRequesterProfile = () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService.navigateToUserProfile( - user: connectionRequestNotification.connectionRequester, + user: connectionRequestNotification.connectionRequester!, context: context); }; @@ -40,7 +40,7 @@ class OBConnectionRequestNotificationTile extends StatelessWidget { onTap: navigateToRequesterProfile, leading: OBAvatar( size: OBAvatarSize.medium, - avatarUrl: connectionRequestNotification.connectionRequester + avatarUrl: connectionRequestNotification.connectionRequester! .getProfileAvatar(), ), title: OBNotificationTileTitle( @@ -49,7 +49,7 @@ class OBConnectionRequestNotificationTile extends StatelessWidget { text: TextSpan( text: _localizationService.notifications__connection_request_tile, )), - subtitle: OBSecondaryText(utilsService.timeAgo(notification.created, _localizationService)), + subtitle: OBSecondaryText(utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/notification_tile/widgets/follow_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/follow_notification_tile.dart index bf409e34c..922eab5d3 100644 --- a/lib/widgets/tiles/notification_tile/widgets/follow_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/follow_notification_tile.dart @@ -12,12 +12,12 @@ import 'notification_tile_title.dart'; class OBFollowNotificationTile extends StatelessWidget { final OBNotification notification; final FollowNotification followNotification; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBFollowNotificationTile( - {Key key, - @required this.notification, - @required this.followNotification, + {Key? key, + required this.notification, + required this.followNotification, this.onPressed}) : super(key: key); @@ -27,9 +27,9 @@ class OBFollowNotificationTile extends StatelessWidget { var utilsService = openbookProvider.utilsService; var navigateToFollowerProfile = () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); openbookProvider.navigationService.navigateToUserProfile( - user: followNotification.follower, context: context); + user: followNotification.follower!, context: context); }; LocalizationService _localizationService = OpenbookProvider.of(context).localizationService; @@ -37,14 +37,14 @@ class OBFollowNotificationTile extends StatelessWidget { onTap: navigateToFollowerProfile, leading: OBAvatar( size: OBAvatarSize.medium, - avatarUrl: followNotification.follower.getProfileAvatar(), + avatarUrl: followNotification.follower!.getProfileAvatar(), ), title: OBNotificationTileTitle( onUsernamePressed: navigateToFollowerProfile, user: followNotification.follower, text: TextSpan(text: _localizationService.notifications__following_you_tile), ), - subtitle: OBSecondaryText(utilsService.timeAgo(notification.created, _localizationService)), + subtitle: OBSecondaryText(utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/notification_tile/widgets/follow_request_approved_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/follow_request_approved_notification_tile.dart index aa89a1156..838e67224 100644 --- a/lib/widgets/tiles/notification_tile/widgets/follow_request_approved_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/follow_request_approved_notification_tile.dart @@ -12,12 +12,12 @@ import 'notification_tile_title.dart'; class OBFollowRequestApprovedNotificationTile extends StatelessWidget { final OBNotification notification; final FollowRequestApprovedNotification followRequestApprovedNotification; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBFollowRequestApprovedNotificationTile( - {Key key, - @required this.notification, - @required this.followRequestApprovedNotification, + {Key? key, + required this.notification, + required this.followRequestApprovedNotification, this.onPressed}) : super(key: key); @@ -27,10 +27,10 @@ class OBFollowRequestApprovedNotificationTile extends StatelessWidget { var utilsService = openbookProvider.utilsService; var navigateToConfirmatorProfile = () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService.navigateToUserProfile( - user: followRequestApprovedNotification.follow.followedUser, + user: followRequestApprovedNotification.follow!.followedUser!, context: context); }; LocalizationService _localizationService = OpenbookProvider.of(context).localizationService; @@ -39,15 +39,15 @@ class OBFollowRequestApprovedNotificationTile extends StatelessWidget { onTap: navigateToConfirmatorProfile, leading: OBAvatar( size: OBAvatarSize.medium, - avatarUrl: followRequestApprovedNotification.follow.followedUser + avatarUrl: followRequestApprovedNotification.follow!.followedUser! .getProfileAvatar(), ), title: OBNotificationTileTitle( onUsernamePressed: navigateToConfirmatorProfile, - user: followRequestApprovedNotification.follow.followedUser, + user: followRequestApprovedNotification.follow!.followedUser, text: TextSpan(text: _localizationService.notifications__approved_follow_request_tile), ), - subtitle: OBSecondaryText(utilsService.timeAgo(notification.created, _localizationService)), + subtitle: OBSecondaryText(utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/notification_tile/widgets/follow_request_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/follow_request_notification_tile.dart index 2be3416d0..05d99ea72 100644 --- a/lib/widgets/tiles/notification_tile/widgets/follow_request_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/follow_request_notification_tile.dart @@ -12,12 +12,12 @@ import 'notification_tile_title.dart'; class OBFollowRequestNotificationTile extends StatelessWidget { final OBNotification notification; final FollowRequestNotification followRequestNotification; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBFollowRequestNotificationTile( - {Key key, - @required this.notification, - @required this.followRequestNotification, + {Key? key, + required this.notification, + required this.followRequestNotification, this.onPressed}) : super(key: key); @@ -28,11 +28,11 @@ class OBFollowRequestNotificationTile extends StatelessWidget { LocalizationService _localizationService = openbookProvider.localizationService; var navigateToRequesterProfile = () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService.navigateToUserProfile( - user: followRequestNotification.followRequest.creator, + user: followRequestNotification.followRequest!.creator!, context: context); }; @@ -40,16 +40,16 @@ class OBFollowRequestNotificationTile extends StatelessWidget { onTap: navigateToRequesterProfile, leading: OBAvatar( size: OBAvatarSize.medium, - avatarUrl: followRequestNotification.followRequest.creator + avatarUrl: followRequestNotification.followRequest!.creator! .getProfileAvatar(), ), title: OBNotificationTileTitle( onUsernamePressed: navigateToRequesterProfile, - user: followRequestNotification.followRequest.creator, + user: followRequestNotification.followRequest!.creator, text: TextSpan( text: _localizationService.notifications__follow_request_tile, )), - subtitle: OBSecondaryText(utilsService.timeAgo(notification.created, _localizationService)), + subtitle: OBSecondaryText(utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/notification_tile/widgets/notification_tile_skeleton.dart b/lib/widgets/tiles/notification_tile/widgets/notification_tile_skeleton.dart index 14ab9e5d0..a0d8b18a3 100644 --- a/lib/widgets/tiles/notification_tile/widgets/notification_tile_skeleton.dart +++ b/lib/widgets/tiles/notification_tile/widgets/notification_tile_skeleton.dart @@ -2,18 +2,18 @@ import 'package:flutter/material.dart'; class OBNotificationTileSkeleton extends StatelessWidget { final Widget leading; - final Widget trailing; + final Widget? trailing; final Widget title; final Widget subtitle; - final VoidCallback onTap; + final VoidCallback? onTap; const OBNotificationTileSkeleton( - {Key key, - @required this.leading, + {Key? key, + required this.leading, this.trailing, - @required this.title, + required this.title, this.onTap, - @required this.subtitle}) + required this.subtitle}) : super(key: key); @override diff --git a/lib/widgets/tiles/notification_tile/widgets/notification_tile_title.dart b/lib/widgets/tiles/notification_tile/widgets/notification_tile_title.dart index d323b0014..4b50058db 100644 --- a/lib/widgets/tiles/notification_tile/widgets/notification_tile_title.dart +++ b/lib/widgets/tiles/notification_tile/widgets/notification_tile_title.dart @@ -5,17 +5,17 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; class OBNotificationTileTitle extends StatelessWidget { - final User user; - final VoidCallback onUsernamePressed; + final User? user; + final VoidCallback? onUsernamePressed; final TextSpan text; static int postCommentMaxVisibleLength = 500; OBNotificationTileTitle( - {Key key, + {Key? key, this.onUsernamePressed, this.user, - @required this.text}) + required this.text}) : super(key: key); @override @@ -28,20 +28,20 @@ class OBNotificationTileTitle extends StatelessWidget { stream: themeService.themeChange, initialData: themeService.getActiveTheme(), builder: (BuildContext context, AsyncSnapshot snapshot) { - OBTheme theme = snapshot.data; + OBTheme theme = snapshot.data!; Color primaryTextColor = themeValueParserService.parseColor(theme.primaryTextColor); Color secondaryTextColor = themeValueParserService.parseColor(theme.secondaryTextColor); - String commenterUsername = user?.username; - String commenterName = user?.getProfileName(); + String? commenterUsername = user?.username; + String? commenterName = user?.getProfileName(); GestureRecognizer usernameTapGestureRecognizer = TapGestureRecognizer()..onTap = onUsernamePressed; - List plainTextItems = text.text.split(' '); + List plainTextItems = text.text!.split(' '); List textItems = []; plainTextItems.asMap().forEach((index, item) { diff --git a/lib/widgets/tiles/notification_tile/widgets/post_comment_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/post_comment_notification_tile.dart index 0782d2b75..38037c523 100644 --- a/lib/widgets/tiles/notification_tile/widgets/post_comment_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/post_comment_notification_tile.dart @@ -16,28 +16,28 @@ class OBPostCommentNotificationTile extends StatelessWidget { final OBNotification notification; final PostCommentNotification postCommentNotification; static final double postImagePreviewSize = 40; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBPostCommentNotificationTile( - {Key key, - @required this.notification, - @required this.postCommentNotification, + {Key? key, + required this.notification, + required this.postCommentNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { - PostComment postComment = postCommentNotification.postComment; - Post post = postComment.post; - String postCommentText = postComment.text; + PostComment postComment = postCommentNotification.postComment!; + Post post = postComment.post!; + String postCommentText = postComment.text!; - int postCreatorId = postCommentNotification.getPostCreatorId(); + int postCreatorId = postCommentNotification.getPostCreatorId()!; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); bool isOwnPostNotification = - openbookProvider.userService.getLoggedInUser().id == postCreatorId; + openbookProvider.userService.getLoggedInUser()?.id == postCreatorId; LocalizationService _localizationService = OpenbookProvider.of(context).localizationService; - Widget postImagePreview; + Widget? postImagePreview; if (post.hasMediaThumbnail()) { postImagePreview = OBNotificationTilePostMediaPreview( post: post, @@ -46,14 +46,14 @@ class OBPostCommentNotificationTile extends StatelessWidget { var utilsService = openbookProvider.utilsService; - Function navigateToCommenterProfile = () { + VoidCallback navigateToCommenterProfile = () { openbookProvider.navigationService - .navigateToUserProfile(user: postComment.commenter, context: context); + .navigateToUserProfile(user: postComment.commenter!, context: context); }; return OBNotificationTileSkeleton( onTap: () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService.navigateToPostCommentsLinked( @@ -62,7 +62,7 @@ class OBPostCommentNotificationTile extends StatelessWidget { leading: OBAvatar( onPressed: navigateToCommenterProfile, size: OBAvatarSize.medium, - avatarUrl: postComment.commenter.getProfileAvatar(), + avatarUrl: postComment.commenter!.getProfileAvatar(), ), title: OBNotificationTileTitle( onUsernamePressed: navigateToCommenterProfile, @@ -73,7 +73,7 @@ class OBPostCommentNotificationTile extends StatelessWidget { : _localizationService.notifications__comment_comment_notification_tile_user_also_commented(postCommentText)), ), trailing: postImagePreview, - subtitle: OBSecondaryText(utilsService.timeAgo(notification.created, _localizationService)), + subtitle: OBSecondaryText(utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/notification_tile/widgets/post_comment_reaction_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/post_comment_reaction_notification_tile.dart index e13b9417f..bb5c2327d 100644 --- a/lib/widgets/tiles/notification_tile/widgets/post_comment_reaction_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/post_comment_reaction_notification_tile.dart @@ -19,23 +19,23 @@ class OBPostCommentReactionNotificationTile extends StatelessWidget { final OBNotification notification; final PostCommentReactionNotification postCommentReactionNotification; static final double postCommentImagePreviewSize = 40; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBPostCommentReactionNotificationTile( - {Key key, - @required this.notification, - @required this.postCommentReactionNotification, + {Key? key, + required this.notification, + required this.postCommentReactionNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { PostCommentReaction postCommentReaction = - postCommentReactionNotification.postCommentReaction; - PostComment postComment = postCommentReaction.postComment; - Post post = postComment.post; + postCommentReactionNotification.postCommentReaction!; + PostComment postComment = postCommentReaction.postComment!; + Post post = postComment.post!; - Widget postCommentImagePreview; + Widget? postCommentImagePreview; if (post.hasMediaThumbnail()) { postCommentImagePreview = OBNotificationTilePostMediaPreview( post: post, @@ -44,19 +44,19 @@ class OBPostCommentReactionNotificationTile extends StatelessWidget { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); var utilsService = openbookProvider.utilsService; - Function navigateToReactorProfile = () { + VoidCallback navigateToReactorProfile = () { openbookProvider.navigationService.navigateToUserProfile( - user: postCommentReaction.reactor, context: context); + user: postCommentReaction.reactor!, context: context); }; LocalizationService _localizationService = openbookProvider.localizationService; return OBNotificationTileSkeleton( onTap: () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - PostComment parentComment = postComment.parentComment; - if(parentComment!=null){ + PostComment? parentComment = postComment.parentComment; + if(parentComment != null){ openbookProvider.navigationService.navigateToPostCommentRepliesLinked( postComment: postComment, context: context, @@ -69,7 +69,7 @@ class OBPostCommentReactionNotificationTile extends StatelessWidget { leading: OBAvatar( onPressed: navigateToReactorProfile, size: OBAvatarSize.medium, - avatarUrl: postCommentReaction.reactor.getProfileAvatar(), + avatarUrl: postCommentReaction.reactor!.getProfileAvatar(), ), title: OBNotificationTileTitle( text: TextSpan(text: _localizationService.notifications__reacted_to_post_comment_tile), @@ -77,13 +77,13 @@ class OBPostCommentReactionNotificationTile extends StatelessWidget { user: postCommentReaction.reactor, ), subtitle: OBSecondaryText( - utilsService.timeAgo(notification.created, _localizationService), + utilsService.timeAgo(notification.created!, _localizationService), size: OBTextSize.small, ), trailing: Row( children: [ OBEmoji( - postCommentReaction.emoji, + postCommentReaction.emoji!, ), postCommentImagePreview ?? const SizedBox() ], diff --git a/lib/widgets/tiles/notification_tile/widgets/post_comment_reply_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/post_comment_reply_notification_tile.dart index 590d0842a..f0d124774 100644 --- a/lib/widgets/tiles/notification_tile/widgets/post_comment_reply_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/post_comment_reply_notification_tile.dart @@ -16,30 +16,30 @@ class OBPostCommentReplyNotificationTile extends StatelessWidget { final OBNotification notification; final PostCommentReplyNotification postCommentNotification; static final double postImagePreviewSize = 40; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBPostCommentReplyNotificationTile( - {Key key, - @required this.notification, - @required this.postCommentNotification, + {Key? key, + required this.notification, + required this.postCommentNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { - PostComment postComment = postCommentNotification.postComment; - PostComment parentComment = postComment.parentComment; - Post post = postComment.post; - String postCommentText = postComment.text; + PostComment postComment = postCommentNotification.postComment!; + PostComment parentComment = postComment.parentComment!; + Post post = postComment.post!; + String postCommentText = postComment.text!; - int postCreatorId = postCommentNotification.getPostCreatorId(); + int postCreatorId = postCommentNotification.getPostCreatorId()!; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); LocalizationService localizationService = openbookProvider.localizationService; bool isOwnPostNotification = - openbookProvider.userService.getLoggedInUser().id == postCreatorId; + openbookProvider.userService.getLoggedInUser()?.id == postCreatorId; - Widget postImagePreview; + Widget? postImagePreview; if (post.hasMediaThumbnail()) { postImagePreview = OBNotificationTilePostMediaPreview( post: post, @@ -48,14 +48,14 @@ class OBPostCommentReplyNotificationTile extends StatelessWidget { var utilsService = openbookProvider.utilsService; - Function navigateToCommenterProfile = () { + VoidCallback navigateToCommenterProfile = () { openbookProvider.navigationService - .navigateToUserProfile(user: postComment.commenter, context: context); + .navigateToUserProfile(user: postComment.commenter!, context: context); }; return OBNotificationTileSkeleton( onTap: () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService.navigateToPostCommentRepliesLinked( @@ -66,7 +66,7 @@ class OBPostCommentReplyNotificationTile extends StatelessWidget { leading: OBAvatar( onPressed: navigateToCommenterProfile, size: OBAvatarSize.medium, - avatarUrl: postComment.commenter.getProfileAvatar(), + avatarUrl: postComment.commenter!.getProfileAvatar(), ), title: OBNotificationTileTitle( text: TextSpan( @@ -77,7 +77,7 @@ class OBPostCommentReplyNotificationTile extends StatelessWidget { user: postComment.commenter, ), subtitle: OBSecondaryText( - utilsService.timeAgo(notification.created, localizationService), + utilsService.timeAgo(notification.created!, localizationService), size: OBTextSize.small, ), trailing: postImagePreview ?? const SizedBox(), diff --git a/lib/widgets/tiles/notification_tile/widgets/post_comment_user_mention_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/post_comment_user_mention_notification_tile.dart index 6e5b43d7d..7450c6f91 100644 --- a/lib/widgets/tiles/notification_tile/widgets/post_comment_user_mention_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/post_comment_user_mention_notification_tile.dart @@ -16,38 +16,38 @@ class OBPostCommentUserMentionNotificationTile extends StatelessWidget { final OBNotification notification; final PostCommentUserMentionNotification postCommentUserMentionNotification; static final double postCommentImagePreviewSize = 40; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBPostCommentUserMentionNotificationTile( - {Key key, - @required this.notification, - @required this.postCommentUserMentionNotification, + {Key? key, + required this.notification, + required this.postCommentUserMentionNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { PostCommentUserMention postCommentUserMention = - postCommentUserMentionNotification.postCommentUserMention; - PostComment postComment = postCommentUserMention.postComment; + postCommentUserMentionNotification.postCommentUserMention!; + PostComment postComment = postCommentUserMention.postComment!; OpenbookProviderState openbookProvider = OpenbookProvider.of(context); var utilsService = openbookProvider.utilsService; - Function navigateToMentionerProfile = () { + VoidCallback navigateToMentionerProfile = () { openbookProvider.navigationService.navigateToUserProfile( - user: postCommentUserMention.postComment.commenter, context: context); + user: postCommentUserMention.postComment!.commenter!, context: context); }; LocalizationService _localizationService = openbookProvider.localizationService; - String postCommentText = postComment.text; + String postCommentText = postComment.text!; return OBNotificationTileSkeleton( onTap: () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); - PostComment parentComment = postComment.parentComment; - if(parentComment!=null){ + PostComment? parentComment = postComment.parentComment; + if(parentComment != null){ openbookProvider.navigationService.navigateToPostCommentRepliesLinked( postComment: postComment, context: context, @@ -60,15 +60,15 @@ class OBPostCommentUserMentionNotificationTile extends StatelessWidget { leading: OBAvatar( onPressed: navigateToMentionerProfile, size: OBAvatarSize.medium, - avatarUrl: postCommentUserMention.postComment.commenter.getProfileAvatar(), + avatarUrl: postCommentUserMention.postComment!.commenter!.getProfileAvatar(), ), title: OBNotificationTileTitle( text: TextSpan(text: _localizationService.notifications__mentioned_in_post_comment_tile(postCommentText)), onUsernamePressed: navigateToMentionerProfile, - user: postCommentUserMention.postComment.commenter, + user: postCommentUserMention.postComment!.commenter, ), subtitle: OBSecondaryText( - utilsService.timeAgo(notification.created, _localizationService), + utilsService.timeAgo(notification.created!, _localizationService), size: OBTextSize.small, ), ); diff --git a/lib/widgets/tiles/notification_tile/widgets/post_reaction_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/post_reaction_notification_tile.dart index 8a1d3c472..b90f84ec1 100644 --- a/lib/widgets/tiles/notification_tile/widgets/post_reaction_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/post_reaction_notification_tile.dart @@ -17,21 +17,21 @@ class OBPostReactionNotificationTile extends StatelessWidget { final OBNotification notification; final PostReactionNotification postReactionNotification; static final double postImagePreviewSize = 40; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBPostReactionNotificationTile( - {Key key, - @required this.notification, - @required this.postReactionNotification, + {Key? key, + required this.notification, + required this.postReactionNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { - PostReaction postReaction = postReactionNotification.postReaction; - Post post = postReaction.post; + PostReaction postReaction = postReactionNotification.postReaction!; + Post post = postReaction.post!; - Widget postImagePreview; + Widget? postImagePreview; if (post.hasMediaThumbnail()) { postImagePreview = Padding( padding: const EdgeInsets.only(left: 10), @@ -44,22 +44,22 @@ class OBPostReactionNotificationTile extends StatelessWidget { LocalizationService _localizationService = openbookProvider.localizationService; - Function navigateToReactorProfile = () { + VoidCallback navigateToReactorProfile = () { openbookProvider.navigationService - .navigateToUserProfile(user: postReaction.reactor, context: context); + .navigateToUserProfile(user: postReaction.reactor!, context: context); }; return OBNotificationTileSkeleton( onTap: () { - if (onPressed != null) onPressed(); + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService - .navigateToPost(post: postReaction.post, context: context); + .navigateToPost(post: postReaction.post!, context: context); }, leading: OBAvatar( onPressed: navigateToReactorProfile, size: OBAvatarSize.medium, - avatarUrl: postReaction.reactor.getProfileAvatar(), + avatarUrl: postReaction.reactor!.getProfileAvatar(), ), title: OBNotificationTileTitle( text: TextSpan( @@ -68,11 +68,11 @@ class OBPostReactionNotificationTile extends StatelessWidget { user: postReaction.reactor, ), subtitle: OBSecondaryText( - utilsService.timeAgo(notification.created, _localizationService)), + utilsService.timeAgo(notification.created!, _localizationService)), trailing: Row( children: [ OBEmoji( - postReaction.emoji, + postReaction.emoji!, ), postImagePreview ?? const SizedBox() ], diff --git a/lib/widgets/tiles/notification_tile/widgets/post_user_mention_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/post_user_mention_notification_tile.dart index 501e9312d..45a0f9a65 100644 --- a/lib/widgets/tiles/notification_tile/widgets/post_user_mention_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/post_user_mention_notification_tile.dart @@ -16,22 +16,22 @@ class OBPostUserMentionNotificationTile extends StatelessWidget { final OBNotification notification; final PostUserMentionNotification postUserMentionNotification; static final double postImagePreviewSize = 40; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBPostUserMentionNotificationTile( - {Key key, - @required this.notification, - @required this.postUserMentionNotification, + {Key? key, + required this.notification, + required this.postUserMentionNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { PostUserMention postUserMention = - postUserMentionNotification.postUserMention; - Post post = postUserMention.post; + postUserMentionNotification.postUserMention!; + Post post = postUserMention.post!; - Widget postImagePreview; + Widget? postImagePreview; if (post.hasMediaThumbnail()) { postImagePreview = OBNotificationTilePostMediaPreview( post: post, @@ -40,35 +40,35 @@ class OBPostUserMentionNotificationTile extends StatelessWidget { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); var utilsService = openbookProvider.utilsService; - Function navigateToMentionerProfile = () { + VoidCallback navigateToMentionerProfile = () { openbookProvider.navigationService.navigateToUserProfile( - user: postUserMention.post.creator, context: context); + user: postUserMention.post!.creator!, context: context); }; LocalizationService _localizationService = openbookProvider.localizationService; - Function onTileTapped = () { - if (onPressed != null) onPressed(); + VoidCallback onTileTapped = () { + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService - .navigateToPost(post: postUserMention.post, context: context); + .navigateToPost(post: postUserMention.post!, context: context); }; return OBNotificationTileSkeleton( onTap: onTileTapped, leading: OBAvatar( onPressed: navigateToMentionerProfile, size: OBAvatarSize.medium, - avatarUrl: postUserMention.post.creator.getProfileAvatar(), + avatarUrl: postUserMention.post!.creator!.getProfileAvatar(), ), title: OBNotificationTileTitle( onUsernamePressed: navigateToMentionerProfile, - user: postUserMention.post.creator, + user: postUserMention.post!.creator, text: TextSpan( text: _localizationService.notifications__mentioned_in_post_tile), ), trailing: postImagePreview, subtitle: OBSecondaryText( - utilsService.timeAgo(notification.created, _localizationService)), + utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/notification_tile/widgets/user_new_post_notification_tile.dart b/lib/widgets/tiles/notification_tile/widgets/user_new_post_notification_tile.dart index 57f35602a..db0244265 100644 --- a/lib/widgets/tiles/notification_tile/widgets/user_new_post_notification_tile.dart +++ b/lib/widgets/tiles/notification_tile/widgets/user_new_post_notification_tile.dart @@ -15,20 +15,20 @@ class OBUserNewPostNotificationTile extends StatelessWidget { final OBNotification notification; final UserNewPostNotification userNewPostNotification; static final double postImagePreviewSize = 40; - final VoidCallback onPressed; + final VoidCallback? onPressed; const OBUserNewPostNotificationTile( - {Key key, - @required this.notification, - @required this.userNewPostNotification, + {Key? key, + required this.notification, + required this.userNewPostNotification, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { - Post post = userNewPostNotification.post; + Post post = userNewPostNotification.post!; - Widget postImagePreview; + Widget? postImagePreview; if (post.hasMediaThumbnail()) { postImagePreview = OBNotificationTilePostMediaPreview( post: post, @@ -37,34 +37,34 @@ class OBUserNewPostNotificationTile extends StatelessWidget { OpenbookProviderState openbookProvider = OpenbookProvider.of(context); var utilsService = openbookProvider.utilsService; - Function navigateToCreatorProfile = () { + VoidCallback navigateToCreatorProfile = () { openbookProvider.navigationService.navigateToUserProfile( - user: userNewPostNotification.post.creator, context: context); + user: userNewPostNotification.post!.creator!, context: context); }; LocalizationService _localizationService = openbookProvider.localizationService; - Function onTileTapped = () { - if (onPressed != null) onPressed(); + VoidCallback onTileTapped = () { + if (onPressed != null) onPressed!(); OpenbookProviderState openbookProvider = OpenbookProvider.of(context); openbookProvider.navigationService - .navigateToPost(post: userNewPostNotification.post, context: context); + .navigateToPost(post: userNewPostNotification.post!, context: context); }; return OBNotificationTileSkeleton( onTap: onTileTapped, leading: OBAvatar( onPressed: navigateToCreatorProfile, size: OBAvatarSize.medium, - avatarUrl: userNewPostNotification.post.creator.getProfileAvatar(), + avatarUrl: userNewPostNotification.post!.creator!.getProfileAvatar(), ), title: OBNotificationTileTitle( onUsernamePressed: navigateToCreatorProfile, - user: userNewPostNotification.post.creator, + user: userNewPostNotification.post!.creator, text: TextSpan(text: _localizationService.notifications__user_new_post_tile), ), trailing: postImagePreview, subtitle: OBSecondaryText( - utilsService.timeAgo(notification.created, _localizationService)), + utilsService.timeAgo(notification.created!, _localizationService)), ); } } diff --git a/lib/widgets/tiles/post_comment_reaction_tile.dart b/lib/widgets/tiles/post_comment_reaction_tile.dart index 2856ffcd0..f9cb01aae 100644 --- a/lib/widgets/tiles/post_comment_reaction_tile.dart +++ b/lib/widgets/tiles/post_comment_reaction_tile.dart @@ -5,29 +5,29 @@ import 'package:flutter/material.dart'; class OBPostCommentReactionTile extends StatelessWidget { final PostCommentReaction postCommentReaction; - final ValueChanged onPostCommentReactionTilePressed; + final ValueChanged? onPostCommentReactionTilePressed; const OBPostCommentReactionTile( - {Key key, - @required this.postCommentReaction, - @required this.onPostCommentReactionTilePressed}) + {Key? key, + required this.postCommentReaction, + required this.onPostCommentReactionTilePressed}) : super(key: key); @override Widget build(BuildContext context) { - var reactor = postCommentReaction.reactor; + var reactor = postCommentReaction.reactor!; return ListTile( onTap: () { if (onPostCommentReactionTilePressed != null) - onPostCommentReactionTilePressed(postCommentReaction); + onPostCommentReactionTilePressed!(postCommentReaction); }, leading: OBAvatar( size: OBAvatarSize.medium, avatarUrl: reactor.getProfileAvatar(), ), title: OBText( - reactor.username, + reactor.username!, style: TextStyle(fontWeight: FontWeight.bold), ), ); diff --git a/lib/widgets/tiles/post_reaction_tile.dart b/lib/widgets/tiles/post_reaction_tile.dart index 3217a5d8f..4f89c0829 100644 --- a/lib/widgets/tiles/post_reaction_tile.dart +++ b/lib/widgets/tiles/post_reaction_tile.dart @@ -4,28 +4,28 @@ import 'package:Okuna/widgets/theming/text.dart'; import 'package:flutter/material.dart'; class OBPostReactionTile extends StatelessWidget { - final PostReaction postReaction; - final ValueChanged onPostReactionTilePressed; + final PostReaction? postReaction; + final ValueChanged? onPostReactionTilePressed; const OBPostReactionTile( - {Key key, this.postReaction, this.onPostReactionTilePressed}) + {Key? key, this.postReaction, this.onPostReactionTilePressed}) : super(key: key); @override Widget build(BuildContext context) { - var reactor = postReaction.reactor; + var reactor = postReaction?.reactor; return ListTile( onTap: () { if (onPostReactionTilePressed != null) - onPostReactionTilePressed(postReaction); + onPostReactionTilePressed!(postReaction); }, leading: OBAvatar( size: OBAvatarSize.medium, - avatarUrl: reactor.getProfileAvatar(), + avatarUrl: reactor?.getProfileAvatar(), ), title: OBText( - reactor.username, + reactor?.username ?? '', style: TextStyle(fontWeight: FontWeight.bold), ), ); diff --git a/lib/widgets/tiles/received_follow_request_tile.dart b/lib/widgets/tiles/received_follow_request_tile.dart index 052b5e360..1d3ab171e 100644 --- a/lib/widgets/tiles/received_follow_request_tile.dart +++ b/lib/widgets/tiles/received_follow_request_tile.dart @@ -10,11 +10,11 @@ import '../../provider.dart'; class OBReceivedFollowRequestTile extends StatelessWidget { final FollowRequest followRequest; - final ValueChanged onFollowRequestApproved; - final ValueChanged onFollowRequestRejected; + final ValueChanged? onFollowRequestApproved; + final ValueChanged? onFollowRequestRejected; const OBReceivedFollowRequestTile(this.followRequest, - {Key key, this.onFollowRequestApproved, this.onFollowRequestRejected}) + {Key? key, this.onFollowRequestApproved, this.onFollowRequestRejected}) : super(key: key); @override @@ -23,7 +23,7 @@ class OBReceivedFollowRequestTile extends StatelessWidget { var navigationService = openbookProvider.navigationService; return OBUserTile( - followRequest.creator, + followRequest.creator!, onUserTilePressed: (User user) { navigationService.navigateToUserProfile(user: user, context: context); }, @@ -31,9 +31,9 @@ class OBReceivedFollowRequestTile extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ OBRejectFollowRequestButton( - followRequest.creator, + followRequest.creator!, onFollowRequestRejected: () { - if(onFollowRequestRejected != null) onFollowRequestRejected(followRequest); + if(onFollowRequestRejected != null) onFollowRequestRejected!(followRequest); }, size: OBButtonSize.small, ), @@ -41,9 +41,9 @@ class OBReceivedFollowRequestTile extends StatelessWidget { width: 10, ), OBApproveFollowRequestButton( - followRequest.creator, + followRequest.creator!, onFollowRequestApproved: () { - if(onFollowRequestApproved != null) onFollowRequestApproved(followRequest); + if(onFollowRequestApproved != null) onFollowRequestApproved!(followRequest); }, size: OBButtonSize.small, ), diff --git a/lib/widgets/tiles/retry_tile.dart b/lib/widgets/tiles/retry_tile.dart index 235351080..fb5c45522 100644 --- a/lib/widgets/tiles/retry_tile.dart +++ b/lib/widgets/tiles/retry_tile.dart @@ -9,10 +9,10 @@ class OBRetryTile extends StatelessWidget { final bool isLoading; const OBRetryTile( - {Key key, + {Key? key, this.text = 'Tap to retry.', - @required this.onWantsToRetry, - this.isLoading}) + required this.onWantsToRetry, + this.isLoading = false}) : super(key: key); @override diff --git a/lib/widgets/tiles/user_tile.dart b/lib/widgets/tiles/user_tile.dart index 9a98d8a0a..c0cdecbc8 100644 --- a/lib/widgets/tiles/user_tile.dart +++ b/lib/widgets/tiles/user_tile.dart @@ -12,13 +12,13 @@ import '../../provider.dart'; class OBUserTile extends StatelessWidget { final User user; - final OnUserTilePressed onUserTilePressed; - final OnUserTileDeleted onUserTileDeleted; + final OnUserTilePressed? onUserTilePressed; + final OnUserTileDeleted? onUserTileDeleted; final bool showFollowing; - final Widget trailing; + final Widget? trailing; const OBUserTile(this.user, - {Key key, + {Key? key, this.onUserTilePressed, this.onUserTileDeleted, this.showFollowing = false, @@ -32,7 +32,7 @@ class OBUserTile extends StatelessWidget { openbookProvider.localizationService; Widget tile = ListTile( onTap: () { - if (onUserTilePressed != null) onUserTilePressed(user); + if (onUserTilePressed != null) onUserTilePressed!(user); }, leading: OBAvatar( size: OBAvatarSize.medium, @@ -41,15 +41,15 @@ class OBUserTile extends StatelessWidget { trailing: trailing, title: Row(children: [ OBText( - user.username, - style: TextStyle(fontWeight: FontWeight.bold), + user.username!, + style: TextStyle(fontWeight: FontWeight.bold) ), _getUserBadge(user) ]), subtitle: Row( children: [ - OBSecondaryText(user.getProfileName()), - showFollowing && user.isFollowing != null && user.isFollowing + Expanded(child: OBSecondaryText(user.getProfileName()!)), + showFollowing && user.isFollowing != null && user.isFollowing! ? OBSecondaryText( _localizationService.trans('user__tile_following')) : const SizedBox() @@ -68,7 +68,7 @@ class OBUserTile extends StatelessWidget { color: Colors.red, icon: Icons.delete, onTap: () { - onUserTileDeleted(user); + onUserTileDeleted!(user); }, ), ], @@ -79,7 +79,7 @@ class OBUserTile extends StatelessWidget { Widget _getUserBadge(User creator) { if (creator.hasProfileBadges()) { - Badge badge = creator.getProfileBadges()[0]; + Badge badge = creator.getProfileBadges()![0]; return OBUserBadge(badge: badge, size: OBUserBadgeSize.small); } return const SizedBox(); diff --git a/lib/widgets/toast.dart b/lib/widgets/toast.dart index 93dc26e18..ab67954d1 100644 --- a/lib/widgets/toast.dart +++ b/lib/widgets/toast.dart @@ -3,7 +3,7 @@ import 'package:flutter/material.dart'; // TODO Queue toasts. class OBToast extends StatefulWidget { - final Widget child; + final Widget? child; OBToast({this.child}); @@ -14,19 +14,19 @@ class OBToast extends StatefulWidget { static OBToastState of(BuildContext context) { final OBToastState toastState = - context.findRootAncestorStateOfType(); + context.findRootAncestorStateOfType()!; toastState._setCurrentContext(context); return toastState; } } class OBToastState extends State with SingleTickerProviderStateMixin { - OverlayEntry _overlayEntry; - BuildContext _currentContext; - AnimationController controller; - Animation offset; - bool _toastInProgress; - bool _dismissInProgress; + OverlayEntry? _overlayEntry; + BuildContext? _currentContext; + late AnimationController controller; + late Animation offset; + late bool _toastInProgress; + late bool _dismissInProgress; static const double TOAST_CONTAINER_HEIGHT = 75.0; @@ -45,23 +45,23 @@ class OBToastState extends State with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { return _OpenbookToast( - child: widget.child, + child: widget.child!, ); } Future showToast( - {@required Color color, - String message, - Widget child, - Duration duration, - VoidCallback onDismissed}) async { + {required Color color, + String? message, + Widget? child, + Duration? duration, + VoidCallback? onDismissed}) async { if (_toastInProgress) return; _toastInProgress = true; this._overlayEntry = this._createOverlayEntryFromTop( color: color, message: message, onDismissed: onDismissed, child: child); - final overlay = Overlay.of(_currentContext); + final overlay = Overlay.of(_currentContext!); WidgetsBinding.instance - .addPostFrameCallback((_) => overlay.insert(_overlayEntry)); + ?.addPostFrameCallback((_) => overlay?.insert(_overlayEntry!)); controller.forward(); duration = duration ?? const Duration(seconds: 3); @@ -77,17 +77,17 @@ class OBToastState extends State with SingleTickerProviderStateMixin { Future _dismissToast() async { await controller.reverse(); - if (this._overlayEntry != null) this._overlayEntry.remove(); + if (this._overlayEntry != null) this._overlayEntry!.remove(); this._overlayEntry = null; _dismissInProgress = false; _toastInProgress = false; } OverlayEntry _createOverlayEntryFromTop( - {@required Color color, - String message, - Widget child, - VoidCallback onDismissed}) { + {required Color color, + String? message, + Widget? child, + VoidCallback? onDismissed}) { return OverlayEntry(builder: (context) { final MediaQueryData existingMediaQuery = MediaQuery.of(context); // 44 is header height @@ -107,7 +107,7 @@ class OBToastState extends State with SingleTickerProviderStateMixin { child: _buildToast( paddingTop: paddingTop, color: color, - message: message, + message: message!, child: child), )) ]); @@ -115,10 +115,10 @@ class OBToastState extends State with SingleTickerProviderStateMixin { } Widget _buildToast( - {@required double paddingTop, - @required Color color, - @required String message, - Widget child}) { + {required double paddingTop, + required Color color, + required String message, + Widget? child}) { return Material( color: Colors.transparent, child: Column( @@ -186,7 +186,7 @@ class OBToastState extends State with SingleTickerProviderStateMixin { } class _OpenbookToast extends InheritedWidget { - _OpenbookToast({Key key, Widget child}) : super(key: key, child: child); + _OpenbookToast({Key? key, required Widget child}) : super(key: key, child: child); @override bool updateShouldNotify(_OpenbookToast old) { diff --git a/lib/widgets/user_badge.dart b/lib/widgets/user_badge.dart index 72024cc4d..2dcadbf5c 100644 --- a/lib/widgets/user_badge.dart +++ b/lib/widgets/user_badge.dart @@ -7,7 +7,7 @@ import 'package:flutter/material.dart'; import 'package:shimmer/shimmer.dart'; class OBUserBadge extends StatelessWidget { - final Badge badge; + final Badge? badge; final OBUserBadgeSize size; static double badgeSizeLarge = 45; static double badgeSizeMedium = 25; @@ -20,7 +20,7 @@ class OBUserBadge extends StatelessWidget { static double iconSizeExtraSmall = 8; - const OBUserBadge({Key key, this.badge, this.size = OBUserBadgeSize.medium}) : super(key: key); + const OBUserBadge({Key? key, this.badge, this.size = OBUserBadgeSize.medium}) : super(key: key); @override Widget build(BuildContext context) { @@ -34,19 +34,19 @@ class OBUserBadge extends StatelessWidget { initialData: themeService.getActiveTheme(), builder: (BuildContext context, AsyncSnapshot snapshot) { - switch(badge.getKeyword()) { + switch(badge!.getKeyword()) { case BadgeKeyword.verified: - return _getVerifiedBadge(badge); break; + return _getVerifiedBadge(badge!); break; case BadgeKeyword.founder: - return _getFounderBadge(badge); break; + return _getFounderBadge(badge!); break; case BadgeKeyword.golden_founder: - return _getGoldenFounderBadge(badge); break; + return _getGoldenFounderBadge(badge!); break; case BadgeKeyword.diamond_founder: - return _getDiamondFounderBadge(badge); break; + return _getDiamondFounderBadge(badge!); break; case BadgeKeyword.super_founder: - return _getSuperFounderBadge(badge); break; + return _getSuperFounderBadge(badge!); break; case BadgeKeyword.angel: - return _getAngelBadge(badge); break; + return _getAngelBadge(badge!); break; default: return const SizedBox(); break; } @@ -66,9 +66,9 @@ class OBUserBadge extends StatelessWidget { end: Alignment.bottomRight, stops: [0.2, 0.6, 0.8], colors: [ - Colors.blue[300], - Colors.blueAccent[200], - Colors.blue[800], + Colors.blue[300]!, + Colors.blueAccent[200]!, + Colors.blue[800]!, ], ), borderRadius: BorderRadius.circular(50) @@ -87,7 +87,7 @@ class OBUserBadge extends StatelessWidget { children: [ Shimmer.fromColors( baseColor: Colors.pink, - highlightColor: Colors.pinkAccent[100], + highlightColor: Colors.pinkAccent[100]!, child: Container( margin: EdgeInsets.only(left: 4.0, right: 4.0), width: badgeSize, @@ -124,11 +124,11 @@ class OBUserBadge extends StatelessWidget { end: Alignment.bottomRight, stops: [0.1, 0.2, 0.5, 0.8, 0.9], colors: [ - Colors.green[300], - Colors.lightGreenAccent[700], - Colors.yellow[400], - Colors.yellow[700], - Colors.orange[400], + Colors.green[300]!, + Colors.lightGreenAccent[700]!, + Colors.yellow[400]!, + Colors.yellow[700]!, + Colors.orange[400]!, ] ), borderRadius: BorderRadius.circular(50) @@ -152,9 +152,9 @@ class OBUserBadge extends StatelessWidget { end: Alignment.bottomRight, stops: [0.1, 0.3, 0.8], colors: [ - Colors.yellowAccent[400], - Colors.yellow[700], - Colors.yellow[800], + Colors.yellowAccent[400]!, + Colors.yellow[700]!, + Colors.yellow[800]!, ], ), borderRadius: BorderRadius.circular(50) @@ -178,9 +178,9 @@ class OBUserBadge extends StatelessWidget { end: Alignment.bottomRight, stops: [0.2, 0.6, 0.8], colors: [ - Colors.red[100], - Colors.redAccent[100], - Colors.red[300], + Colors.red[100]!, + Colors.redAccent[100]!, + Colors.red[300]!, ], ), borderRadius: BorderRadius.circular(50) @@ -204,9 +204,9 @@ class OBUserBadge extends StatelessWidget { end: Alignment.bottomRight, stops: [0.1, 0.5, 0.8], colors: [ - Colors.deepPurple[200], - Colors.deepPurple[100], - Colors.blue[200], + Colors.deepPurple[200]!, + Colors.deepPurple[100]!, + Colors.blue[200]!, ], ), borderRadius: BorderRadius.circular(50) diff --git a/lib/widgets/user_posts_count.dart b/lib/widgets/user_posts_count.dart index 103b74ee1..71e4ef738 100644 --- a/lib/widgets/user_posts_count.dart +++ b/lib/widgets/user_posts_count.dart @@ -19,12 +19,12 @@ class OBUserPostsCount extends StatefulWidget { } class OBUserPostsCountState extends State { - UserService _userService; - ToastService _toastService; - LocalizationService _localizationService; - bool _requestInProgress; - bool _hasError; - bool _needsBootstrap; + late UserService _userService; + late ToastService _toastService; + late LocalizationService _localizationService; + late bool _requestInProgress; + late bool _hasError; + late bool _needsBootstrap; @override void initState() { @@ -55,7 +55,7 @@ class OBUserPostsCountState extends State { ? _buildErrorIcon() : _requestInProgress ? _buildLoadingIcon() - : _buildPostsCount(user); + : _buildPostsCount(user!); }, ); } @@ -96,8 +96,8 @@ class OBUserPostsCountState extends State { _toastService.error( message: error.toHumanReadableMessage(), context: context); } else if (error is HttpieRequestError) { - String errorMessage = await error.toHumanReadableMessage(); - _toastService.error(message: errorMessage, context: context); + String? errorMessage = await error.toHumanReadableMessage(); + _toastService.error(message: errorMessage ?? _localizationService.error__unknown_error, context: context); } else { _toastService.error( message: _localizationService.error__unknown_error, context: context); diff --git a/lib/widgets/user_visibility_icon.dart b/lib/widgets/user_visibility_icon.dart index 0c1746658..b3663d668 100644 --- a/lib/widgets/user_visibility_icon.dart +++ b/lib/widgets/user_visibility_icon.dart @@ -7,18 +7,18 @@ enum OBIconSize { small, medium, large, extraLarge } class OBUserVisibilityIcon extends StatelessWidget { final UserVisibility visibility; - final OBIconSize size; - final double customSize; - final Color color; - final String semanticLabel; + final OBIconSize? size; + final double? customSize; + final Color? color; + final String? semanticLabel; const OBUserVisibilityIcon( - {Key key, + {Key? key, this.size, this.customSize, this.color, this.semanticLabel, - @required this.visibility}) + required this.visibility}) : super(key: key); @override diff --git a/lib/widgets/video_player/video_player.dart b/lib/widgets/video_player/video_player.dart index 237b84ef3..e45ea289f 100644 --- a/lib/widgets/video_player/video_player.dart +++ b/lib/widgets/video_player/video_player.dart @@ -17,21 +17,21 @@ import '../progress_indicator.dart'; var rng = new Random(); class OBVideoPlayer extends StatefulWidget { - final File video; - final String videoUrl; - final String thumbnailUrl; - final Key visibilityKey; - final ChewieController chewieController; - final VideoPlayerController videoPlayerController; - final bool isInDialog; + final File? video; + final String? videoUrl; + final String? thumbnailUrl; + final Key? visibilityKey; + final ChewieController? chewieController; + final VideoPlayerController? videoPlayerController; + final bool? isInDialog; final bool autoPlay; - final OBVideoPlayerController controller; - final double height; - final double width; - final bool isConstrained; + final OBVideoPlayerController? controller; + final double? height; + final double? width; + final bool? isConstrained; const OBVideoPlayer( - {Key key, + {Key? key, this.video, this.videoUrl, this.thumbnailUrl, @@ -53,33 +53,33 @@ class OBVideoPlayer extends StatefulWidget { } class OBVideoPlayerState extends State { - VideoPlayerController _playerController; - ChewieController _chewieController; - OBVideoPlayerControlsController _obVideoPlayerControlsController; - UserPreferencesService _userPreferencesService; - OBVideoPlayerController _controller; + VideoPlayerController? _playerController; + ChewieController? _chewieController; + late OBVideoPlayerControlsController _obVideoPlayerControlsController; + late UserPreferencesService _userPreferencesService; + late OBVideoPlayerController _controller; - bool _videoInitialized; - bool _needsChewieBootstrap; + late bool _videoInitialized; + late bool _needsChewieBootstrap; - bool _isVideoHandover; - bool _hasVideoOpenedInDialog; - bool _isPausedDueToInvisibility; - bool _isPausedByUser; - bool _needsBootstrap; + late bool _isVideoHandover; + late bool _hasVideoOpenedInDialog; + late bool _isPausedDueToInvisibility; + late bool _isPausedByUser; + late bool _needsBootstrap; - Key _visibilityKey; + late Key _visibilityKey; - StreamSubscription _videosSoundSettingsChangeSubscription; + StreamSubscription? _videosSoundSettingsChangeSubscription; - Future _videoPreparationFuture; + late Future _videoPreparationFuture; @override void initState() { super.initState(); _controller = widget.controller == null ? OBVideoPlayerController() - : widget.controller; + : widget.controller!; _controller.attach(this); _obVideoPlayerControlsController = OBVideoPlayerControlsController(); _hasVideoOpenedInDialog = widget.isInDialog ?? false; @@ -95,11 +95,11 @@ class OBVideoPlayerState extends State { String visibilityKeyFallback; if (widget.videoUrl != null) { - visibilityKeyFallback = widget.videoUrl; + visibilityKeyFallback = widget.videoUrl!; } else if (widget.video != null) { - visibilityKeyFallback = widget.video.path; + visibilityKeyFallback = widget.video!.path; } else if (widget.videoPlayerController != null) { - visibilityKeyFallback = widget.videoPlayerController.dataSource; + visibilityKeyFallback = widget.videoPlayerController!.dataSource!; } else { throw Exception( 'Video dialog requires video, videoUrl or videoPlayerController.'); @@ -108,7 +108,7 @@ class OBVideoPlayerState extends State { visibilityKeyFallback += '-${rng.nextInt(1000)}'; _visibilityKey = widget.visibilityKey != null - ? widget.visibilityKey + ? widget.visibilityKey! : Key(visibilityKeyFallback); _videoPreparationFuture = _prepareVideo(); @@ -119,17 +119,17 @@ class OBVideoPlayerState extends State { super.dispose(); if (!_isVideoHandover && mounted && !_hasVideoOpenedInDialog) { _videosSoundSettingsChangeSubscription?.cancel(); - if (_playerController != null) _playerController.dispose(); - if (_chewieController != null) _chewieController.dispose(); + if (_playerController != null) _playerController!.dispose(); + if (_chewieController != null) _chewieController!.dispose(); } } void _onUserPreferencesVideosSoundSettingsChange( - VideosSoundSetting newVideosSoundSettings) { + VideosSoundSetting? newVideosSoundSettings) { if (newVideosSoundSettings == VideosSoundSetting.enabled) { - _playerController.setVolume(100); + _playerController?.setVolume(100); } else { - _playerController.setVolume(0); + _playerController?.setVolume(0); } } @@ -159,7 +159,7 @@ class OBVideoPlayerState extends State { if (widget.videoUrl != null) { _playerController = VideoPlayerController.network(widget.videoUrl); } else if (widget.video != null) { - _playerController = VideoPlayerController.file(widget.video); + _playerController = VideoPlayerController.file(widget.video!); } else if (widget.videoPlayerController != null) { _playerController = widget.videoPlayerController; } else { @@ -167,16 +167,16 @@ class OBVideoPlayerState extends State { 'Failed to initialize video. Video dialog requires video, videoUrl or videoPlayerController.'); } - _playerController.setVolume(0); + _playerController?.setVolume(0); debugLog('Initializing video player'); - await _playerController.initialize().timeout(Duration(seconds: 2)); - if (_playerController.value?.hasError == true) { + await _playerController?.initialize().timeout(Duration(seconds: 2)); + if (_playerController?.value.hasError == true) { debugLog('Player controller has error'); throw OBVideoPlayerInitializationException('Player controller had error'); } - if (_controller._attemptedToPlayWhileNotReady) _playerController.play(); + if (_controller._attemptedToPlayWhileNotReady) _playerController?.play(); if (mounted) { setState(() { @@ -187,7 +187,7 @@ class OBVideoPlayerState extends State { void _bootstrap() async { await _videoPreparationFuture; - VideosSoundSetting videosSoundSetting = + VideosSoundSetting? videosSoundSetting = await _userPreferencesService.getVideosSoundSetting(); _onUserPreferencesVideosSoundSettingsChange(videosSoundSetting); @@ -221,7 +221,7 @@ class OBVideoPlayerState extends State { height: widget.height, width: widget.width, controller: _chewieController, - isConstrained: widget.isConstrained), + isConstrained: widget.isConstrained ?? false), ); } @@ -233,7 +233,7 @@ class OBVideoPlayerState extends State { decoration: BoxDecoration( image: DecorationImage( fit: BoxFit.cover, - image: AdvancedNetworkImage(widget.thumbnailUrl, + image: AdvancedNetworkImage(widget.thumbnailUrl!, useDiskCache: true), )), ) @@ -293,11 +293,11 @@ class OBVideoPlayerState extends State { // Return back to config ChewieController _getChewieController() { - if (widget.chewieController != null) return widget.chewieController; - double aspectRatio = _playerController.value.aspectRatio; + if (widget.chewieController != null) return widget.chewieController!; + double aspectRatio = _playerController!.value.aspectRatio; return ChewieController( autoInitialize: false, - videoPlayerController: _playerController, + videoPlayerController: _playerController!, showControlsOnInitialize: false, customControls: OBVideoPlayerControls( controller: _obVideoPlayerControlsController, @@ -319,15 +319,15 @@ class OBVideoPlayerState extends State { debugLog( 'isVisible: ${isVisible.toString()} with fraction ${visibilityInfo.visibleFraction}'); - if (!isVisible && _playerController.value.isPlaying && mounted) { + if (!isVisible && _playerController!.value.isPlaying && mounted) { debugLog('Its not visible and the video is playing. Now pausing. .'); _isPausedDueToInvisibility = true; - _playerController.pause(); + _playerController!.pause(); } } void _pause() { - _playerController.pause(); + _playerController!.pause(); _isPausedByUser = false; _isPausedDueToInvisibility = false; } @@ -335,17 +335,18 @@ class OBVideoPlayerState extends State { void _play() { _isPausedDueToInvisibility = false; _isPausedByUser = false; - _playerController.play(); + _playerController!.play(); } void debugLog(String log) { - ValueKey key = _visibilityKey; - debugPrint('OBVideoPlayer:${key.value}: $log'); + // ValueKey key = _visibilityKey; + Key key = _visibilityKey; + debugPrint('OBVideoPlayer:$key: $log'); } } class OBVideoPlayerController { - OBVideoPlayerState _state; + late OBVideoPlayerState _state; bool _attemptedToPlayWhileNotReady = false; void attach(state) { @@ -372,7 +373,7 @@ class OBVideoPlayerController { bool isPlaying() { if (!isReady()) return false; - return _state._playerController.value.isPlaying; + return _state._playerController!.value.isPlaying; } bool isReady() { @@ -401,7 +402,7 @@ class OBVideoPlayerController { return 'unknown'; } - return _state._playerController.dataSource; + return _state._playerController!.dataSource!; } void debugLog(String log) { diff --git a/lib/widgets/video_player/widgets/chewie/chewie_player.dart b/lib/widgets/video_player/widgets/chewie/chewie_player.dart index 50703297e..5df464981 100644 --- a/lib/widgets/video_player/widgets/chewie/chewie_player.dart +++ b/lib/widgets/video_player/widgets/chewie/chewie_player.dart @@ -20,12 +20,12 @@ typedef Widget ChewieRoutePageBuilder( /// `video_player` is pretty low level. Chewie wraps it in a friendly skin to /// make it easy to use! class Chewie extends StatefulWidget { - final double height; - final double width; + final double? height; + final double? width; final bool isConstrained; Chewie({ - Key key, + Key? key, this.controller, this.height, this.width, @@ -34,7 +34,7 @@ class Chewie extends StatefulWidget { super(key: key); /// The [ChewieController] - final ChewieController controller; + final ChewieController? controller; @override ChewieState createState() { @@ -48,25 +48,25 @@ class ChewieState extends State { @override void initState() { super.initState(); - widget.controller.addListener(listener); + widget.controller!.addListener(listener); } @override void dispose() { - widget.controller.removeListener(listener); + widget.controller!.removeListener(listener); super.dispose(); } @override void didUpdateWidget(Chewie oldWidget) { if (oldWidget.controller != widget.controller) { - widget.controller.addListener(listener); + widget.controller!.addListener(listener); } super.didUpdateWidget(oldWidget); } void listener() async { - if (widget.controller.isFullScreen && !_isFullScreen) { + if (widget.controller!.isFullScreen && !_isFullScreen) { _isFullScreen = true; await _pushFullScreenWidget(context); } else if (_isFullScreen) { @@ -78,7 +78,7 @@ class ChewieState extends State { @override Widget build(BuildContext context) { return _ChewieControllerProvider( - controller: widget.controller, + controller: widget.controller!, child: PlayerWithControls( height: widget.height, width: widget.width, @@ -107,7 +107,7 @@ class ChewieState extends State { _ChewieControllerProvider controllerProvider) { return AnimatedBuilder( animation: animation, - builder: (BuildContext context, Widget child) { + builder: (BuildContext context, Widget? child) { return _buildFullScreenVideo(context, animation, controllerProvider); }, ); @@ -119,15 +119,15 @@ class ChewieState extends State { Animation secondaryAnimation, ) { var controllerProvider = _ChewieControllerProvider( - controller: widget.controller, + controller: widget.controller!, child: PlayerWithControls(), ); - if (widget.controller.routePageBuilder == null) { + if (widget.controller!.routePageBuilder == null) { return _defaultRoutePageBuilder( context, animation, secondaryAnimation, controllerProvider); } - return widget.controller.routePageBuilder( + return widget.controller!.routePageBuilder!( context, animation, secondaryAnimation, controllerProvider); } @@ -145,22 +145,22 @@ class ChewieState extends State { ]); } - if (!widget.controller.allowedScreenSleep) { + if (!widget.controller!.allowedScreenSleep) { Wakelock.enable(); } await Navigator.of(context, rootNavigator: true).push(route); _isFullScreen = false; - widget.controller.exitFullScreen(); + widget.controller!.exitFullScreen(); // The wakelock plugins checks whether it needs to perform an action internally, // so we do not need to check Wakelock.isEnabled. Wakelock.disable(); SystemChrome.setEnabledSystemUIOverlays( - widget.controller.systemOverlaysAfterFullScreen); + widget.controller!.systemOverlaysAfterFullScreen); SystemChrome.setPreferredOrientations( - widget.controller.deviceOrientationsAfterFullScreen); + widget.controller!.deviceOrientationsAfterFullScreen); } } @@ -176,7 +176,7 @@ class ChewieState extends State { /// `VideoPlayerController`. class ChewieController extends ChangeNotifier { ChewieController({ - this.videoPlayerController, + required this.videoPlayerController, this.aspectRatio, this.autoInitialize = false, this.autoPlay = false, @@ -218,7 +218,7 @@ class ChewieController extends ChangeNotifier { final bool autoPlay; /// Start video at a certain position - final Duration startAt; + final Duration? startAt; /// Whether or not the video should loop final bool looping; @@ -231,32 +231,32 @@ class ChewieController extends ChangeNotifier { /// Defines customised controls. Check [MaterialControls] or /// [CupertinoControls] for reference. - final Widget customControls; + final Widget? customControls; /// When the video playback runs into an error, you can build a custom /// error message. - final Widget Function(BuildContext context, String errorMessage) errorBuilder; + final Widget Function(BuildContext context, String errorMessage)? errorBuilder; /// The Aspect Ratio of the Video. Important to get the correct size of the /// video! /// /// Will fallback to fitting within the space allowed. - final double aspectRatio; + final double? aspectRatio; /// The colors to use for controls on iOS. By default, the iOS player uses /// colors sampled from the original iOS 11 designs. - final ChewieProgressColors cupertinoProgressColors; + final ChewieProgressColors? cupertinoProgressColors; /// The colors to use for the Material Progress Bar. By default, the Material /// player uses the colors from your Theme. - final ChewieProgressColors materialProgressColors; + final ChewieProgressColors? materialProgressColors; /// The placeholder is displayed underneath the Video before it is initialized /// or played. - final Widget placeholder; + final Widget? placeholder; /// A widget which is placed between the video and the controls - final Widget overlay; + final Widget? overlay; /// Defines if the player will start in fullscreen when play is pressed final bool fullScreenByDefault; @@ -280,7 +280,7 @@ class ChewieController extends ChangeNotifier { final List deviceOrientationsAfterFullScreen; /// Defines a custom RoutePageBuilder for the fullscreen - final ChewieRoutePageBuilder routePageBuilder; + final ChewieRoutePageBuilder? routePageBuilder; static ChewieController of(BuildContext context) { final chewieControllerProvider = @@ -313,7 +313,7 @@ class ChewieController extends ChangeNotifier { } if (startAt != null) { - await videoPlayerController.seekTo(startAt); + await videoPlayerController.seekTo(startAt!); } if (fullScreenByDefault) { @@ -370,9 +370,9 @@ class ChewieController extends ChangeNotifier { class _ChewieControllerProvider extends InheritedWidget { const _ChewieControllerProvider({ - Key key, - @required this.controller, - @required Widget child, + Key? key, + required this.controller, + required Widget child, }) : assert(controller != null), assert(child != null), super(key: key, child: child); diff --git a/lib/widgets/video_player/widgets/chewie/cupertino_controls.dart b/lib/widgets/video_player/widgets/chewie/cupertino_controls.dart index d78438c55..779c1ec2a 100644 --- a/lib/widgets/video_player/widgets/chewie/cupertino_controls.dart +++ b/lib/widgets/video_player/widgets/chewie/cupertino_controls.dart @@ -13,8 +13,8 @@ import 'package:video_player/video_player.dart'; class CupertinoControls extends StatefulWidget { const CupertinoControls({ - @required this.backgroundColor, - @required this.iconColor, + required this.backgroundColor, + required this.iconColor, }); final Color backgroundColor; @@ -27,26 +27,26 @@ class CupertinoControls extends StatefulWidget { } class _CupertinoControlsState extends State { - VideoPlayerValue _latestValue; - double _latestVolume; + VideoPlayerValue? _latestValue; + double? _latestVolume; bool _hideStuff = true; - Timer _hideTimer; + Timer? _hideTimer; final marginSize = 5.0; - Timer _expandCollapseTimer; - Timer _initTimer; + Timer? _expandCollapseTimer; + Timer? _initTimer; - VideoPlayerController controller; - ChewieController chewieController; + late VideoPlayerController controller; + late ChewieController chewieController; @override Widget build(BuildContext context) { chewieController = ChewieController.of(context); - if (_latestValue.hasError) { + if (_latestValue?.hasError == true) { return chewieController.errorBuilder != null - ? chewieController.errorBuilder( + ? chewieController.errorBuilder!( context, - chewieController.videoPlayerController.value.errorDescription, + chewieController.videoPlayerController.value.errorDescription ?? '', ) : Center( child: Icon( @@ -208,7 +208,7 @@ class _CupertinoControlsState extends State { Expanded _buildHitArea() { return Expanded( child: GestureDetector( - onTap: _latestValue != null && _latestValue.isPlaying + onTap: _latestValue != null && _latestValue!.isPlaying ? _cancelAndRestartTimer : () { _hideTimer?.cancel(); @@ -235,7 +235,7 @@ class _CupertinoControlsState extends State { onTap: () { _cancelAndRestartTimer(); - if (_latestValue.volume == 0) { + if (_latestValue?.volume == 0) { controller.setVolume(_latestVolume ?? 0.5); } else { _latestVolume = controller.value.volume; @@ -258,7 +258,7 @@ class _CupertinoControlsState extends State { right: buttonPadding, ), child: Icon( - (_latestValue != null && _latestValue.volume > 0) + (_latestValue != null && _latestValue!.volume > 0) ? Icons.volume_up : Icons.volume_off, color: iconColor, @@ -299,7 +299,7 @@ class _CupertinoControlsState extends State { Widget _buildPosition(Color iconColor) { final position = - _latestValue != null ? _latestValue.position : Duration(seconds: 0); + _latestValue != null ? _latestValue!.position : Duration(seconds: 0); return Padding( padding: EdgeInsets.only(right: 12.0), @@ -314,8 +314,8 @@ class _CupertinoControlsState extends State { } Widget _buildRemaining(Color iconColor) { - final position = _latestValue != null && _latestValue.duration != null - ? _latestValue.duration - _latestValue.position + final position = _latestValue != null && _latestValue!.duration != null + ? _latestValue!.duration! - _latestValue!.position : Duration(seconds: 0); return Padding( @@ -513,14 +513,14 @@ class _CupertinoControlsState extends State { void _skipBack() { _cancelAndRestartTimer(); final beginning = Duration(seconds: 0).inMilliseconds; - final skip = (_latestValue.position - Duration(seconds: 15)).inMilliseconds; + final skip = (_latestValue!.position - Duration(seconds: 15)).inMilliseconds; controller.seekTo(Duration(milliseconds: math.max(skip, beginning))); } void _skipForward() { _cancelAndRestartTimer(); - final end = _latestValue.duration.inMilliseconds; - final skip = (_latestValue.position + Duration(seconds: 15)).inMilliseconds; + final end = _latestValue!.duration!.inMilliseconds; + final skip = (_latestValue!.position + Duration(seconds: 15)).inMilliseconds; controller.seekTo(Duration(milliseconds: math.min(skip, end))); } diff --git a/lib/widgets/video_player/widgets/chewie/cupertino_progress_bar.dart b/lib/widgets/video_player/widgets/chewie/cupertino_progress_bar.dart index c083a9151..86c40afcb 100644 --- a/lib/widgets/video_player/widgets/chewie/cupertino_progress_bar.dart +++ b/lib/widgets/video_player/widgets/chewie/cupertino_progress_bar.dart @@ -6,7 +6,7 @@ import 'package:video_player/video_player.dart'; class CupertinoVideoProgressBar extends StatefulWidget { CupertinoVideoProgressBar( this.controller, { - ChewieProgressColors colors, + ChewieProgressColors? colors, this.onDragEnd, this.onDragStart, this.onDragUpdate, @@ -14,9 +14,9 @@ class CupertinoVideoProgressBar extends StatefulWidget { final VideoPlayerController controller; final ChewieProgressColors colors; - final Function() onDragStart; - final Function() onDragEnd; - final Function() onDragUpdate; + final Function()? onDragStart; + final Function()? onDragEnd; + final Function()? onDragUpdate; @override _VideoProgressBarState createState() { @@ -31,7 +31,7 @@ class _VideoProgressBarState extends State { }; } - VoidCallback listener; + late VoidCallback listener; bool _controllerWasPlaying = false; VideoPlayerController get controller => widget.controller; @@ -54,7 +54,7 @@ class _VideoProgressBarState extends State { final box = context.findRenderObject() as RenderBox; final Offset tapPos = box.globalToLocal(globalPosition); final double relative = tapPos.dx / box.size.width; - final Duration position = controller.value.duration * relative; + final Duration position = controller.value.duration! * relative; controller.seekTo(position); } @@ -82,7 +82,7 @@ class _VideoProgressBarState extends State { } if (widget.onDragStart != null) { - widget.onDragStart(); + widget.onDragStart!(); } }, onHorizontalDragUpdate: (DragUpdateDetails details) { @@ -92,7 +92,7 @@ class _VideoProgressBarState extends State { seekToRelativePosition(details.globalPosition); if (widget.onDragUpdate != null) { - widget.onDragUpdate(); + widget.onDragUpdate!(); } }, onHorizontalDragEnd: (DragEndDetails details) { @@ -101,7 +101,7 @@ class _VideoProgressBarState extends State { } if (widget.onDragEnd != null) { - widget.onDragEnd(); + widget.onDragEnd!(); } }, onTapDown: (TapDownDetails details) { @@ -145,12 +145,12 @@ class _ProgressBarPainter extends CustomPainter { return; } final double playedPartPercent = - value.position.inMilliseconds / value.duration.inMilliseconds; + value.position.inMilliseconds / value.duration!.inMilliseconds; final double playedPart = playedPartPercent > 1 ? size.width : playedPartPercent * size.width; for (DurationRange range in value.buffered) { - final double start = range.startFraction(value.duration) * size.width; - final double end = range.endFraction(value.duration) * size.width; + final double start = range.startFraction(value.duration!) * size.width; + final double end = range.endFraction(value.duration!) * size.width; canvas.drawRRect( RRect.fromRectAndRadius( Rect.fromPoints( diff --git a/lib/widgets/video_player/widgets/chewie/material_controls.dart b/lib/widgets/video_player/widgets/chewie/material_controls.dart index 104352ce2..6ff60de90 100644 --- a/lib/widgets/video_player/widgets/chewie/material_controls.dart +++ b/lib/widgets/video_player/widgets/chewie/material_controls.dart @@ -9,7 +9,7 @@ import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; class MaterialControls extends StatefulWidget { - const MaterialControls({Key key}) : super(key: key); + const MaterialControls({Key? key}) : super(key: key); @override State createState() { @@ -18,27 +18,27 @@ class MaterialControls extends StatefulWidget { } class _MaterialControlsState extends State { - VideoPlayerValue _latestValue; - double _latestVolume; + VideoPlayerValue? _latestValue; + double? _latestVolume; bool _hideStuff = true; - Timer _hideTimer; - Timer _initTimer; - Timer _showAfterExpandCollapseTimer; + Timer? _hideTimer; + Timer? _initTimer; + Timer? _showAfterExpandCollapseTimer; bool _dragging = false; final barHeight = 48.0; final marginSize = 5.0; - VideoPlayerController controller; - ChewieController chewieController; + VideoPlayerController? controller; + ChewieController? chewieController; @override Widget build(BuildContext context) { - if (_latestValue.hasError) { - return chewieController.errorBuilder != null - ? chewieController.errorBuilder( + if (_latestValue?.hasError == true) { + return chewieController?.errorBuilder != null + ? chewieController!.errorBuilder!( context, - chewieController.videoPlayerController.value.errorDescription, + chewieController!.videoPlayerController.value.errorDescription ?? '', ) : Center( child: Icon( @@ -56,9 +56,9 @@ class _MaterialControlsState extends State { child: Column( children: [ _latestValue != null && - !_latestValue.isPlaying && - _latestValue.duration == null || - _latestValue.isBuffering + !_latestValue!.isPlaying && + _latestValue!.duration == null || + _latestValue!.isBuffering ? const Expanded( child: const Center( child: const CircularProgressIndicator(), @@ -79,7 +79,7 @@ class _MaterialControlsState extends State { } void _dispose() { - controller.removeListener(_updateState); + controller!.removeListener(_updateState); _hideTimer?.cancel(); _initTimer?.cancel(); _showAfterExpandCollapseTimer?.cancel(); @@ -89,7 +89,7 @@ class _MaterialControlsState extends State { void didChangeDependencies() { final _oldController = chewieController; chewieController = ChewieController.of(context); - controller = chewieController.videoPlayerController; + controller = chewieController?.videoPlayerController; if (_oldController != chewieController) { _dispose(); @@ -102,7 +102,7 @@ class _MaterialControlsState extends State { AnimatedOpacity _buildBottomBar( BuildContext context, ) { - final iconColor = Theme.of(context).textTheme.button.color; + final iconColor = Theme.of(context).textTheme.button!.color; return AnimatedOpacity( opacity: _hideStuff ? 0.0 : 1.0, @@ -112,15 +112,15 @@ class _MaterialControlsState extends State { color: Theme.of(context).dialogBackgroundColor, child: Row( children: [ - _buildPlayPause(controller), - chewieController.isLive + _buildPlayPause(controller!), + chewieController!.isLive ? Expanded(child: const Text('LIVE')) - : _buildPosition(iconColor), - chewieController.isLive ? const SizedBox() : _buildProgressBar(), - chewieController.allowMuting - ? _buildMuteButton(controller) + : _buildPosition(iconColor!), + chewieController!.isLive ? const SizedBox() : _buildProgressBar(), + chewieController!.allowMuting + ? _buildMuteButton(controller!) : Container(), - chewieController.allowFullScreen + chewieController!.allowFullScreen ? _buildExpandButton() : Container(), ], @@ -144,7 +144,7 @@ class _MaterialControlsState extends State { ), child: Center( child: Icon( - chewieController.isFullScreen + chewieController!.isFullScreen ? Icons.fullscreen_exit : Icons.fullscreen, ), @@ -157,7 +157,7 @@ class _MaterialControlsState extends State { Expanded _buildHitArea() { return Expanded( child: GestureDetector( - onTap: _latestValue != null && _latestValue.isPlaying + onTap: _latestValue != null && _latestValue!.isPlaying ? _cancelAndRestartTimer : () { _playPause(); @@ -171,7 +171,7 @@ class _MaterialControlsState extends State { child: Center( child: AnimatedOpacity( opacity: - _latestValue != null && !_latestValue.isPlaying && !_dragging + _latestValue != null && !_latestValue!.isPlaying && !_dragging ? 1.0 : 0.0, duration: Duration(milliseconds: 300), @@ -201,7 +201,7 @@ class _MaterialControlsState extends State { onTap: () { _cancelAndRestartTimer(); - if (_latestValue.volume == 0) { + if (_latestValue == null || _latestValue?.volume == 0) { controller.setVolume(_latestVolume ?? 0.5); } else { _latestVolume = controller.value.volume; @@ -220,7 +220,7 @@ class _MaterialControlsState extends State { right: 8.0, ), child: Icon( - (_latestValue != null && _latestValue.volume > 0) + (_latestValue != null && _latestValue!.volume > 0) ? Icons.volume_up : Icons.volume_off, ), @@ -250,11 +250,11 @@ class _MaterialControlsState extends State { } Widget _buildPosition(Color iconColor) { - final position = _latestValue != null && _latestValue.position != null - ? _latestValue.position + final position = _latestValue != null && _latestValue!.position != null + ? _latestValue!.position : Duration.zero; - final duration = _latestValue != null && _latestValue.duration != null - ? _latestValue.duration + final duration = _latestValue != null && _latestValue!.duration != null + ? _latestValue!.duration! : Duration.zero; return Padding( @@ -278,16 +278,16 @@ class _MaterialControlsState extends State { } Future _initialize() async { - controller.addListener(_updateState); + controller?.addListener(_updateState); _updateState(); - if ((controller.value != null && controller.value.isPlaying) || - chewieController.autoPlay) { + if ((controller?.value != null && controller!.value.isPlaying) || + chewieController!.autoPlay) { _startHideTimer(); } - if (chewieController.showControlsOnInitialize) { + if (chewieController!.showControlsOnInitialize) { _initTimer = Timer(Duration(milliseconds: 200), () { setState(() { _hideStuff = false; @@ -300,7 +300,7 @@ class _MaterialControlsState extends State { setState(() { _hideStuff = true; - chewieController.toggleFullScreen(); + chewieController!.toggleFullScreen(); _showAfterExpandCollapseTimer = Timer(Duration(milliseconds: 300), () { setState(() { _cancelAndRestartTimer(); @@ -311,19 +311,19 @@ class _MaterialControlsState extends State { void _playPause() { setState(() { - if (controller.value.isPlaying) { + if (controller!.value.isPlaying) { _hideStuff = false; _hideTimer?.cancel(); - controller.pause(); + controller!.pause(); } else { _cancelAndRestartTimer(); - if (!controller.value.initialized) { - controller.initialize().then((_) { - controller.play(); + if (!controller!.value.initialized) { + controller!.initialize().then((_) { + controller!.play(); }); } else { - controller.play(); + controller!.play(); } } }); @@ -339,7 +339,7 @@ class _MaterialControlsState extends State { void _updateState() { setState(() { - _latestValue = controller.value; + _latestValue = controller!.value; }); } @@ -348,7 +348,7 @@ class _MaterialControlsState extends State { child: Padding( padding: EdgeInsets.only(right: 20.0), child: MaterialVideoProgressBar( - controller, + controller!, onDragStart: () { setState(() { _dragging = true; @@ -363,7 +363,7 @@ class _MaterialControlsState extends State { _startHideTimer(); }, - colors: chewieController.materialProgressColors ?? + colors: chewieController!.materialProgressColors ?? ChewieProgressColors( playedColor: Theme.of(context).accentColor, handleColor: Theme.of(context).accentColor, diff --git a/lib/widgets/video_player/widgets/chewie/material_progress_bar.dart b/lib/widgets/video_player/widgets/chewie/material_progress_bar.dart index b5a0b2fa7..672f491eb 100644 --- a/lib/widgets/video_player/widgets/chewie/material_progress_bar.dart +++ b/lib/widgets/video_player/widgets/chewie/material_progress_bar.dart @@ -6,7 +6,7 @@ import 'package:video_player/video_player.dart'; class MaterialVideoProgressBar extends StatefulWidget { MaterialVideoProgressBar( this.controller, { - ChewieProgressColors colors, + ChewieProgressColors? colors, this.onDragEnd, this.onDragStart, this.onDragUpdate, @@ -14,9 +14,9 @@ class MaterialVideoProgressBar extends StatefulWidget { final VideoPlayerController controller; final ChewieProgressColors colors; - final Function() onDragStart; - final Function() onDragEnd; - final Function() onDragUpdate; + final Function()? onDragStart; + final Function()? onDragEnd; + final Function()? onDragUpdate; @override _VideoProgressBarState createState() { @@ -31,7 +31,7 @@ class _VideoProgressBarState extends State { }; } - VoidCallback listener; + late VoidCallback listener; bool _controllerWasPlaying = false; VideoPlayerController get controller => widget.controller; @@ -54,7 +54,7 @@ class _VideoProgressBarState extends State { final box = context.findRenderObject() as RenderBox; final Offset tapPos = box.globalToLocal(globalPosition); final double relative = tapPos.dx / box.size.width; - final Duration position = controller.value.duration * relative; + final Duration position = controller.value.duration! * relative; controller.seekTo(position); } @@ -82,7 +82,7 @@ class _VideoProgressBarState extends State { } if (widget.onDragStart != null) { - widget.onDragStart(); + widget.onDragStart!(); } }, onHorizontalDragUpdate: (DragUpdateDetails details) { @@ -92,7 +92,7 @@ class _VideoProgressBarState extends State { seekToRelativePosition(details.globalPosition); if (widget.onDragUpdate != null) { - widget.onDragUpdate(); + widget.onDragUpdate!(); } }, onHorizontalDragEnd: (DragEndDetails details) { @@ -101,7 +101,7 @@ class _VideoProgressBarState extends State { } if (widget.onDragEnd != null) { - widget.onDragEnd(); + widget.onDragEnd!(); } }, onTapDown: (TapDownDetails details) { @@ -143,12 +143,12 @@ class _ProgressBarPainter extends CustomPainter { return; } final double playedPartPercent = - value.position.inMilliseconds / value.duration.inMilliseconds; + value.position.inMilliseconds / value.duration!.inMilliseconds; final double playedPart = playedPartPercent > 1 ? size.width : playedPartPercent * size.width; for (DurationRange range in value.buffered) { - final double start = range.startFraction(value.duration) * size.width; - final double end = range.endFraction(value.duration) * size.width; + final double start = range.startFraction(value.duration!) * size.width; + final double end = range.endFraction(value.duration!) * size.width; canvas.drawRRect( RRect.fromRectAndRadius( Rect.fromPoints( diff --git a/lib/widgets/video_player/widgets/chewie/player_with_controls.dart b/lib/widgets/video_player/widgets/chewie/player_with_controls.dart index 0dde6055d..79396c72e 100644 --- a/lib/widgets/video_player/widgets/chewie/player_with_controls.dart +++ b/lib/widgets/video_player/widgets/chewie/player_with_controls.dart @@ -13,7 +13,7 @@ class PlayerWithControls extends StatelessWidget { final bool isConstrained; const PlayerWithControls( - {Key key, this.height, this.width, this.isConstrained = false}) + {Key? key, this.height, this.width, this.isConstrained = false}) : super(key: key); @override @@ -71,7 +71,7 @@ class PlayerWithControls extends StatelessWidget { ) { return chewieController.showControls ? chewieController.customControls != null - ? chewieController.customControls + ? chewieController.customControls! : Theme.of(context).platform == TargetPlatform.android ? MaterialControls() : CupertinoControls( diff --git a/lib/widgets/video_player/widgets/video_player_controls.dart b/lib/widgets/video_player/widgets/video_player_controls.dart index e07e44f88..b57d79799 100644 --- a/lib/widgets/video_player/widgets/video_player_controls.dart +++ b/lib/widgets/video_player/widgets/video_player_controls.dart @@ -13,15 +13,15 @@ import 'package:video_player/video_player.dart'; import '../../icon.dart'; class OBVideoPlayerControls extends StatefulWidget { - final Function(Function) onExpandCollapse; - final Function(Function) onPause; - final Function(Function) onPlay; - final Function(Function) onMute; - final Function(Function) onUnmute; - final OBVideoPlayerControlsController controller; + final Function(Function)? onExpandCollapse; + final Function(Function)? onPause; + final Function(Function)? onPlay; + final Function(Function)? onMute; + final Function(Function)? onUnmute; + final OBVideoPlayerControlsController? controller; const OBVideoPlayerControls( - {Key key, + {Key? key, this.onExpandCollapse, this.controller, this.onMute, @@ -37,31 +37,31 @@ class OBVideoPlayerControls extends StatefulWidget { } class OBVideoPlayerControlsState extends State { - VideoPlayerValue _latestValue; - double _latestVolume; + VideoPlayerValue? _latestValue; + double? _latestVolume; bool _hideStuff = true; - Timer _hideTimer; - Timer _initTimer; - Timer _showAfterExpandCollapseTimer; + Timer? _hideTimer; + Timer? _initTimer; + Timer? _showAfterExpandCollapseTimer; bool _dragging = false; - bool _isDismissable; + bool? _isDismissable; final barHeight = 48.0; final marginSize = 5.0; - VideoPlayerController controller; - ChewieController chewieController; + VideoPlayerController? controller; + ChewieController? chewieController; @override Widget build(BuildContext context) { Widget mainWidget; bool isLoading = _latestValue != null && - !_latestValue.isPlaying && - _latestValue.duration == null || - _latestValue != null && _latestValue.isBuffering; + !_latestValue!.isPlaying && + _latestValue!.duration == null || + _latestValue != null && _latestValue!.isBuffering; - bool hasError = _latestValue != null && _latestValue.hasError; + bool hasError = _latestValue != null && _latestValue!.hasError; if (isLoading) { mainWidget = Expanded( @@ -72,10 +72,10 @@ class OBVideoPlayerControlsState extends State { ), ); } else if (hasError) { - mainWidget = chewieController.errorBuilder != null - ? chewieController.errorBuilder( + mainWidget = chewieController?.errorBuilder != null + ? chewieController!.errorBuilder!( context, - chewieController.videoPlayerController.value.errorDescription, + chewieController!.videoPlayerController.value.errorDescription ?? '', ) : Center( child: new OBIcon( @@ -99,10 +99,10 @@ class OBVideoPlayerControlsState extends State { new Column( children: [ mainWidget, - _buildBottomBar(context, controller), + _buildBottomBar(context, controller!), ], ), - _hideStuff || !_isDismissable + _hideStuff || _isDismissable == null || !_isDismissable! ? new Container() : new IconButton( icon: new OBIcon( @@ -111,7 +111,7 @@ class OBVideoPlayerControlsState extends State { ), onPressed: () async { print("pressed true"); - controller.pause(); + controller!.pause(); Navigator.pop(context); }, ), @@ -122,7 +122,7 @@ class OBVideoPlayerControlsState extends State { void initState() { super.initState(); _isDismissable = false; - if (widget.controller != null) widget.controller.attach(this); + if (widget.controller != null) widget.controller!.attach(this); } @override @@ -132,7 +132,7 @@ class OBVideoPlayerControlsState extends State { } void _dispose() { - controller.removeListener(_updateState); + controller!.removeListener(_updateState); _hideTimer?.cancel(); _initTimer?.cancel(); _showAfterExpandCollapseTimer?.cancel(); @@ -142,7 +142,7 @@ class OBVideoPlayerControlsState extends State { void didChangeDependencies() { final _oldController = chewieController; chewieController = ChewieController.of(context); - controller = chewieController.videoPlayerController; + controller = chewieController!.videoPlayerController; if (_oldController != chewieController) { _dispose(); @@ -168,7 +168,7 @@ class OBVideoPlayerControlsState extends State { _buildPosition(Colors.white), _buildProgressBar(), _buildMuteButton(controller), - chewieController.allowFullScreen + chewieController!.allowFullScreen ? _buildExpandButton() : const SizedBox(), ], @@ -181,7 +181,7 @@ class OBVideoPlayerControlsState extends State { return new GestureDetector( onTap: widget.onExpandCollapse != null ? () { - widget.onExpandCollapse(_onExpandCollapse); + widget.onExpandCollapse!(_onExpandCollapse); } : _onExpandCollapse, child: new AnimatedOpacity( @@ -196,7 +196,7 @@ class OBVideoPlayerControlsState extends State { ), child: new Center( child: new OBIcon( - chewieController.isFullScreen + chewieController!.isFullScreen ? OBIcons.fullscreen_exit : OBIcons.fullscreen, color: Colors.white, @@ -210,7 +210,7 @@ class OBVideoPlayerControlsState extends State { Expanded _buildHitArea() { return new Expanded( child: new GestureDetector( - onTap: _latestValue != null && _latestValue.isPlaying + onTap: _latestValue != null && _latestValue!.isPlaying ? () { _playPause(); //_cancelAndRestartTimer; @@ -229,7 +229,7 @@ class OBVideoPlayerControlsState extends State { child: new Center( child: new AnimatedOpacity( opacity: - _latestValue != null && !_latestValue.isPlaying && !_dragging + _latestValue != null && !_latestValue!.isPlaying && !_dragging ? 1.0 : 0.0, duration: new Duration(milliseconds: 300), @@ -263,15 +263,15 @@ class OBVideoPlayerControlsState extends State { onTap: () { _cancelAndRestartTimer(); - if (_latestValue.volume == 0) { + if (_latestValue?.volume == 0) { if (widget.onUnmute != null) { - widget.onUnmute(_unMute); + widget.onUnmute!(_unMute); } else { _unMute(); } } else { if (widget.onMute != null) { - widget.onMute(_mute); + widget.onMute!(_mute); } else { _mute(); } @@ -289,7 +289,7 @@ class OBVideoPlayerControlsState extends State { right: 8.0, ), child: new OBIcon( - (_latestValue != null && _latestValue.volume > 0) + (_latestValue != null && _latestValue!.volume > 0) ? OBIcons.volume_up : OBIcons.volume_off, color: Colors.white, @@ -302,12 +302,12 @@ class OBVideoPlayerControlsState extends State { } void _mute() { - _latestVolume = controller.value.volume; - controller.setVolume(0.0); + _latestVolume = controller!.value.volume; + controller!.setVolume(0.0); } void _unMute() { - controller.setVolume(_latestVolume ?? 0.5); + controller!.setVolume(_latestVolume ?? 0.5); } GestureDetector _buildPlayPause(VideoPlayerController controller) { @@ -322,11 +322,11 @@ class OBVideoPlayerControlsState extends State { } Widget _buildPosition(Color iconColor) { - final position = _latestValue != null && _latestValue.position != null - ? _latestValue.position + final position = _latestValue != null && _latestValue!.position != null + ? _latestValue!.position : Duration.zero; - final duration = _latestValue != null && _latestValue.duration != null - ? _latestValue.duration + final duration = _latestValue != null && _latestValue!.duration != null + ? _latestValue!.duration! : Duration.zero; return new Padding( @@ -351,16 +351,16 @@ class OBVideoPlayerControlsState extends State { } Future _initialize() async { - controller.addListener(_updateState); + controller?.addListener(_updateState); _updateState(); - if ((controller.value != null && controller.value.isPlaying) || - chewieController.autoPlay) { + if ((controller?.value != null && controller!.value.isPlaying) || + chewieController!.autoPlay) { _startHideTimer(); } - if (chewieController.showControlsOnInitialize) { + if (chewieController!.showControlsOnInitialize) { _initTimer = Timer(Duration(milliseconds: 200), () { setState(() { _hideStuff = false; @@ -373,7 +373,7 @@ class OBVideoPlayerControlsState extends State { setState(() { _hideStuff = true; - chewieController.toggleFullScreen(); + chewieController!.toggleFullScreen(); _showAfterExpandCollapseTimer = Timer(Duration(milliseconds: 300), () { setState(() { _cancelAndRestartTimer(); @@ -384,15 +384,15 @@ class OBVideoPlayerControlsState extends State { void _playPause() { setState(() { - if (controller.value.isPlaying) { + if (controller!.value.isPlaying) { if (widget.onPause != null) { - widget.onPause(_pause); + widget.onPause!(_pause); } else { _pause(); } } else { if (widget.onPlay != null) { - widget.onPlay(_play); + widget.onPlay!(_play); } else { _play(); } @@ -403,18 +403,18 @@ class OBVideoPlayerControlsState extends State { void _pause() { _hideStuff = false; _hideTimer?.cancel(); - controller.pause(); + controller!.pause(); } void _play() { _cancelAndRestartTimer(); - if (!controller.value.initialized) { - controller.initialize().then((_) { - controller.play(); + if (!controller!.value.initialized) { + controller!.initialize().then((_) { + controller!.play(); }); } else { - controller.play(); + controller!.play(); } } @@ -428,7 +428,7 @@ class OBVideoPlayerControlsState extends State { void _updateState() { setState(() { - _latestValue = controller.value; + _latestValue = controller!.value; }); } @@ -452,7 +452,7 @@ class OBVideoPlayerControlsState extends State { child: new Padding( padding: new EdgeInsets.only(right: 20.0), child: MaterialVideoProgressBar( - controller, + controller!, onDragStart: () { setState(() { _dragging = true; @@ -483,7 +483,7 @@ class OBVideoPlayerControlsState extends State { } class OBVideoPlayerControlsController { - OBVideoPlayerControlsState _state; + late OBVideoPlayerControlsState _state; OBVideoPlayerControlsController(); diff --git a/lib/widgets/video_player/widgets/video_progress_bar.dart b/lib/widgets/video_player/widgets/video_progress_bar.dart index e5a303ccd..bbb72b4a8 100755 --- a/lib/widgets/video_player/widgets/video_progress_bar.dart +++ b/lib/widgets/video_player/widgets/video_progress_bar.dart @@ -7,13 +7,13 @@ class OBVideoProgressBar extends StatefulWidget { final VideoPlayerController controller; final ChewieProgressColors colors; - final Function() onDragStart; - final Function() onDragEnd; - final Function() onDragUpdate; + final Function()? onDragStart; + final Function()? onDragEnd; + final Function()? onDragUpdate; OBVideoProgressBar( this.controller, { - ChewieProgressColors colors, + ChewieProgressColors? colors, this.onDragEnd, this.onDragStart, this.onDragUpdate, @@ -26,7 +26,7 @@ class OBVideoProgressBar extends StatefulWidget { } class _VideoProgressBarState extends State { - VoidCallback listener; + late VoidCallback listener; bool _controllerWasPlaying = false; @@ -53,16 +53,16 @@ class _VideoProgressBarState extends State { @override Widget build(BuildContext context) { void seekToRelativePosition(Offset globalPosition) { - final RenderBox box = context.findRenderObject(); + final RenderBox box = context.findRenderObject()! as RenderBox; final Offset tapPos = box.globalToLocal(globalPosition); final double relative = tapPos.dx / box.size.width; - final Duration position = controller.value.duration * relative; + final Duration position = controller.value.duration! * relative; controller.seekTo(position); } return new GestureDetector( child: (controller.value.hasError) - ? new Text(controller.value.errorDescription) + ? new Text(controller.value.errorDescription ?? '') : new Center( child: new Container( height: MediaQuery.of(context).size.height / 2, @@ -86,7 +86,7 @@ class _VideoProgressBarState extends State { } if (widget.onDragStart != null) { - widget.onDragStart(); + widget.onDragStart!(); } }, onHorizontalDragUpdate: (DragUpdateDetails details) { @@ -96,7 +96,7 @@ class _VideoProgressBarState extends State { seekToRelativePosition(details.globalPosition); if (widget.onDragUpdate != null) { - widget.onDragUpdate(); + widget.onDragUpdate!(); } }, onHorizontalDragEnd: (DragEndDetails details) { @@ -105,7 +105,7 @@ class _VideoProgressBarState extends State { } if (widget.onDragEnd != null) { - widget.onDragEnd(); + widget.onDragEnd!(); } }, onTapDown: (TapDownDetails details) { @@ -147,11 +147,11 @@ class _ProgressBarPainter extends CustomPainter { return; } final double playedPart = value.position.inMilliseconds / - value.duration.inMilliseconds * + value.duration!.inMilliseconds * size.width; for (DurationRange range in value.buffered) { - final double start = range.startFraction(value.duration) * size.width; - final double end = range.endFraction(value.duration) * size.width; + final double start = range.startFraction(value.duration!) * size.width; + final double end = range.endFraction(value.duration!) * size.width; canvas.drawRRect( new RRect.fromRectAndRadius( new Rect.fromPoints( diff --git a/pubspec.lock b/pubspec.lock index e9e1d04ab..82c4b767b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -7,224 +7,238 @@ packages: name: _fe_analyzer_shared url: "https://pub.dartlang.org" source: hosted - version: "7.0.0" + version: "22.0.0" analyzer: dependency: transitive description: name: analyzer url: "https://pub.dartlang.org" source: hosted - version: "0.39.17" + version: "1.7.2" archive: dependency: transitive description: name: archive url: "https://pub.dartlang.org" source: hosted - version: "2.0.13" + version: "3.1.2" args: - dependency: transitive + dependency: "direct overridden" description: name: args url: "https://pub.dartlang.org" source: hosted - version: "1.6.0" + version: "2.1.0" async: dependency: transitive description: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.5.0-nullsafety.1" + version: "2.8.1" back_button_interceptor: dependency: "direct main" description: name: back_button_interceptor url: "https://pub.dartlang.org" source: hosted - version: "4.4.0" + version: "5.0.0" boolean_selector: dependency: transitive description: name: boolean_selector url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.1" + version: "2.1.0" cached_network_image: dependency: "direct main" description: name: cached_network_image url: "https://pub.dartlang.org" source: hosted - version: "2.3.3" + version: "3.1.0" + cached_network_image_platform_interface: + dependency: transitive + description: + name: cached_network_image_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.0" + cached_network_image_web: + dependency: transitive + description: + name: cached_network_image_web + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" characters: dependency: transitive description: name: characters url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.3" + version: "1.1.0" charcode: dependency: transitive description: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" + version: "1.3.1" cli_util: dependency: transitive description: name: cli_util url: "https://pub.dartlang.org" source: hosted - version: "0.2.0" + version: "0.3.0" clock: dependency: transitive description: name: clock url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.1" + version: "1.1.0" collection: - dependency: transitive + dependency: "direct main" description: name: collection url: "https://pub.dartlang.org" source: hosted - version: "1.15.0-nullsafety.3" + version: "1.15.0" connectivity: dependency: "direct main" description: name: connectivity url: "https://pub.dartlang.org" source: hosted - version: "0.4.9+5" + version: "3.0.6" connectivity_for_web: dependency: transitive description: name: connectivity_for_web url: "https://pub.dartlang.org" source: hosted - version: "0.3.1+2" + version: "0.4.0" connectivity_macos: dependency: transitive description: name: connectivity_macos url: "https://pub.dartlang.org" source: hosted - version: "0.1.0+5" + version: "0.2.0" connectivity_platform_interface: dependency: transitive description: name: connectivity_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.6" + version: "2.0.1" convert: dependency: transitive description: name: convert url: "https://pub.dartlang.org" source: hosted - version: "2.1.1" - coverage: + version: "3.0.0" + cross_file: dependency: transitive description: - name: coverage + name: cross_file url: "https://pub.dartlang.org" source: hosted - version: "0.14.1" + version: "0.3.1+5" crypto: dependency: transitive description: name: crypto url: "https://pub.dartlang.org" source: hosted - version: "2.1.5" + version: "3.0.1" csslib: dependency: transitive description: name: csslib url: "https://pub.dartlang.org" source: hosted - version: "0.16.2" + version: "0.17.0" cupertino_icons: dependency: "direct main" description: name: cupertino_icons url: "https://pub.dartlang.org" source: hosted - version: "0.1.3" + version: "1.0.3" dart_style: dependency: transitive description: name: dart_style url: "https://pub.dartlang.org" source: hosted - version: "1.3.6" + version: "2.0.1" dcache: dependency: "direct main" description: name: dcache url: "https://pub.dartlang.org" source: hosted - version: "0.1.0" + version: "0.4.0" device_info: dependency: "direct main" description: name: device_info url: "https://pub.dartlang.org" source: hosted - version: "0.4.2+9" + version: "2.0.2" device_info_platform_interface: dependency: transitive description: name: device_info_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.1" + version: "2.0.1" exif: dependency: "direct main" description: name: exif url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "2.2.0" expandable: dependency: "direct main" description: name: expandable url: "https://pub.dartlang.org" source: hosted - version: "4.1.4" + version: "5.0.1" fake_async: dependency: transitive description: name: fake_async url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" + version: "1.2.0" ffi: dependency: transitive description: name: ffi url: "https://pub.dartlang.org" source: hosted - version: "0.1.3" + version: "1.1.1" file: dependency: transitive description: name: file url: "https://pub.dartlang.org" source: hosted - version: "5.2.1" + version: "6.1.1" file_picker: dependency: "direct main" description: name: file_picker url: "https://pub.dartlang.org" source: hosted - version: "2.1.5+1" + version: "3.0.2+2" flutter: dependency: "direct main" description: flutter @@ -234,53 +248,53 @@ packages: dependency: "direct main" description: path: "." - ref: "bugfix/fix-breaking-master-change" - resolved-ref: "536fb1408d0983de0e5f9905f34cb74ab0ab3674" - url: "https://github.com/OkunaOrg/flutter_advanced_networkimage.git" + ref: "0b2c9775f8ab375c47f812a459f276b9feb107b8" + resolved-ref: "0b2c9775f8ab375c47f812a459f276b9feb107b8" + url: "https://github.com/jozsefsallai/flutter_advanced_networkimage.git" source: git - version: "0.6.0" + version: "0.7.0" flutter_blurhash: dependency: transitive description: name: flutter_blurhash url: "https://pub.dartlang.org" source: hosted - version: "0.5.0" + version: "0.6.0" flutter_cache_manager: dependency: "direct main" description: name: flutter_cache_manager url: "https://pub.dartlang.org" source: hosted - version: "1.4.2" + version: "3.1.0" flutter_colorpicker: dependency: "direct main" description: name: flutter_colorpicker url: "https://pub.dartlang.org" source: hosted - version: "0.3.4" + version: "0.6.0" flutter_ffmpeg: dependency: "direct main" description: name: flutter_ffmpeg url: "https://pub.dartlang.org" source: hosted - version: "0.3.0" + version: "0.4.2" flutter_image_compress: dependency: "direct main" description: name: flutter_image_compress url: "https://pub.dartlang.org" source: hosted - version: "0.7.0" + version: "1.1.0" flutter_launcher_icons: dependency: "direct dev" description: name: flutter_launcher_icons url: "https://pub.dartlang.org" source: hosted - version: "0.7.5" + version: "0.9.0" flutter_localizations: dependency: "direct main" description: flutter @@ -292,42 +306,42 @@ packages: name: flutter_markdown url: "https://pub.dartlang.org" source: hosted - version: "0.2.0" + version: "0.6.6" flutter_pagewise: dependency: "direct main" description: name: flutter_pagewise url: "https://pub.dartlang.org" source: hosted - version: "1.2.3" + version: "2.0.1" flutter_plugin_android_lifecycle: dependency: transitive description: name: flutter_plugin_android_lifecycle url: "https://pub.dartlang.org" source: hosted - version: "1.0.11" + version: "2.0.2" flutter_secure_storage: dependency: "direct main" description: name: flutter_secure_storage url: "https://pub.dartlang.org" source: hosted - version: "3.3.5" + version: "4.2.1" flutter_slidable: dependency: "direct main" description: name: flutter_slidable url: "https://pub.dartlang.org" source: hosted - version: "0.5.7" + version: "0.6.0" flutter_svg: dependency: "direct main" description: name: flutter_svg url: "https://pub.dartlang.org" source: hosted - version: "0.18.0" + version: "0.22.0" flutter_test: dependency: "direct dev" description: flutter @@ -344,184 +358,156 @@ packages: name: glob url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "2.0.1" html: dependency: "direct main" description: name: html url: "https://pub.dartlang.org" source: hosted - version: "0.14.0+4" + version: "0.15.0" http: dependency: "direct main" description: name: http url: "https://pub.dartlang.org" source: hosted - version: "0.12.2" - http_multi_server: - dependency: transitive - description: - name: http_multi_server - url: "https://pub.dartlang.org" - source: hosted - version: "2.2.0" + version: "0.13.3" http_parser: dependency: transitive description: name: http_parser url: "https://pub.dartlang.org" source: hosted - version: "3.1.4" + version: "4.0.0" http_retry: dependency: "direct main" description: name: http_retry url: "https://pub.dartlang.org" source: hosted - version: "0.1.1+3" + version: "0.2.0" image: dependency: transitive description: name: image url: "https://pub.dartlang.org" source: hosted - version: "2.1.18" + version: "3.0.2" image_cropper: dependency: "direct main" description: name: image_cropper url: "https://pub.dartlang.org" source: hosted - version: "1.3.1" + version: "1.4.1" image_picker: dependency: "direct main" description: name: image_picker url: "https://pub.dartlang.org" source: hosted - version: "0.6.7+21" + version: "0.8.4+2" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.3" image_picker_platform_interface: dependency: transitive description: name: image_picker_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.1.1" + version: "2.4.1" intercom_flutter: dependency: "direct main" description: name: intercom_flutter url: "https://pub.dartlang.org" source: hosted - version: "2.3.3" + version: "3.2.1" + intercom_flutter_platform_interface: + dependency: transitive + description: + name: intercom_flutter_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "0.0.1" intl: dependency: transitive description: name: intl url: "https://pub.dartlang.org" source: hosted - version: "0.16.1" - intl_translation: + version: "0.17.0" + intl_generator: dependency: "direct dev" description: - name: intl_translation + name: intl_generator url: "https://pub.dartlang.org" source: hosted - version: "0.17.10+1" + version: "0.1.0+0" inview_notifier_list: dependency: "direct main" description: path: "." - ref: d60972d4928463352781e027f20bd5eca0007cd9 - resolved-ref: d60972d4928463352781e027f20bd5eca0007cd9 + ref: e52a3bb077dfb8815e6b7ac51f98ae1603ff26b2 + resolved-ref: e52a3bb077dfb8815e6b7ac51f98ae1603ff26b2 url: "https://github.com/OkunaOrg/inview_notifier_list.git" source: git - version: "1.0.0" - io: - dependency: transitive - description: - name: io - url: "https://pub.dartlang.org" - source: hosted - version: "0.3.4" + version: "1.1.0" js: dependency: transitive description: name: js url: "https://pub.dartlang.org" source: hosted - version: "0.6.3-nullsafety.2" - logging: - dependency: transitive - description: - name: logging - url: "https://pub.dartlang.org" - source: hosted - version: "0.11.4" + version: "0.6.3" markdown: dependency: transitive description: name: markdown url: "https://pub.dartlang.org" source: hosted - version: "2.1.8" + version: "4.0.0" matcher: dependency: transitive description: name: matcher url: "https://pub.dartlang.org" source: hosted - version: "0.12.10-nullsafety.1" + version: "0.12.10" meta: dependency: transitive description: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.3" + version: "1.7.0" mime: dependency: "direct main" description: name: mime url: "https://pub.dartlang.org" source: hosted - version: "0.9.7" - node_interop: - dependency: transitive - description: - name: node_interop - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.1" - node_io: - dependency: transitive - description: - name: node_io - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.1" - node_preamble: - dependency: transitive - description: - name: node_preamble - url: "https://pub.dartlang.org" - source: hosted - version: "1.4.12" + version: "1.0.0" octo_image: dependency: transitive description: name: octo_image url: "https://pub.dartlang.org" source: hosted - version: "0.3.0" + version: "1.0.0+1" onesignal_flutter: dependency: "direct main" description: name: onesignal_flutter url: "https://pub.dartlang.org" source: hosted - version: "2.6.2" + version: "3.2.3" open_iconic_flutter: dependency: "direct main" description: @@ -535,161 +521,196 @@ packages: name: package_config url: "https://pub.dartlang.org" source: hosted - version: "1.9.3" + version: "2.0.0" package_info: dependency: "direct main" description: name: package_info url: "https://pub.dartlang.org" source: hosted - version: "0.4.3" + version: "2.0.2" + package_info_plus: + dependency: transitive + description: + name: package_info_plus + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + package_info_plus_linux: + dependency: transitive + description: + name: package_info_plus_linux + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.2" + package_info_plus_macos: + dependency: transitive + description: + name: package_info_plus_macos + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.1" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + package_info_plus_web: + dependency: transitive + description: + name: package_info_plus_web + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + package_info_plus_windows: + dependency: transitive + description: + name: package_info_plus_windows + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" path: dependency: "direct main" description: name: path url: "https://pub.dartlang.org" source: hosted - version: "1.8.0-nullsafety.1" + version: "1.8.0" path_drawing: dependency: transitive description: name: path_drawing url: "https://pub.dartlang.org" source: hosted - version: "0.4.1+1" + version: "0.5.1" path_parsing: dependency: transitive description: name: path_parsing url: "https://pub.dartlang.org" source: hosted - version: "0.1.4" + version: "0.2.1" path_provider: dependency: transitive description: name: path_provider url: "https://pub.dartlang.org" source: hosted - version: "1.6.22" + version: "2.0.2" path_provider_linux: dependency: transitive description: name: path_provider_linux url: "https://pub.dartlang.org" source: hosted - version: "0.0.1+2" + version: "2.0.0" path_provider_macos: dependency: transitive description: name: path_provider_macos url: "https://pub.dartlang.org" source: hosted - version: "0.0.4+4" + version: "2.0.0" path_provider_platform_interface: dependency: transitive description: name: path_provider_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "2.0.1" path_provider_windows: dependency: transitive description: name: path_provider_windows url: "https://pub.dartlang.org" source: hosted - version: "0.0.4+1" + version: "2.0.1" pedantic: dependency: transitive description: name: pedantic url: "https://pub.dartlang.org" source: hosted - version: "1.10.0-nullsafety.2" + version: "1.11.0" petitparser: dependency: transitive description: name: petitparser url: "https://pub.dartlang.org" source: hosted - version: "3.1.0" + version: "4.1.0" photo_view: dependency: "direct main" description: name: photo_view url: "https://pub.dartlang.org" source: hosted - version: "0.9.2" + version: "0.12.0" pigment: dependency: "direct main" description: name: pigment url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" + version: "1.0.4" platform: dependency: transitive description: name: platform url: "https://pub.dartlang.org" source: hosted - version: "2.2.1" + version: "3.0.0" plugin_platform_interface: dependency: transitive description: name: plugin_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.3" - pool: - dependency: transitive - description: - name: pool - url: "https://pub.dartlang.org" - source: hosted - version: "1.5.0-nullsafety.2" + version: "2.0.0" process: dependency: transitive description: name: process url: "https://pub.dartlang.org" source: hosted - version: "3.0.13" + version: "4.2.1" pub_semver: dependency: transitive description: name: pub_semver url: "https://pub.dartlang.org" source: hosted - version: "1.4.4" + version: "2.0.0" public_suffix: dependency: "direct main" description: name: public_suffix url: "https://pub.dartlang.org" source: hosted - version: "1.2.1" + version: "3.0.0" punycode: dependency: transitive description: name: punycode url: "https://pub.dartlang.org" source: hosted - version: "0.1.0" + version: "1.0.0" retry: dependency: "direct main" description: name: retry url: "https://pub.dartlang.org" source: hosted - version: "3.0.1" + version: "3.1.0" rxdart: dependency: "direct main" description: name: rxdart url: "https://pub.dartlang.org" source: hosted - version: "0.24.1" + version: "0.27.2" screen: dependency: "direct main" description: @@ -703,222 +724,201 @@ packages: name: sentry url: "https://pub.dartlang.org" source: hosted - version: "4.0.3" + version: "5.0.0" sentry_flutter: dependency: "direct main" description: name: sentry_flutter url: "https://pub.dartlang.org" source: hosted - version: "4.0.3" - share: + version: "5.0.0" + share_plus: dependency: "direct main" description: - name: share + name: share_plus url: "https://pub.dartlang.org" source: hosted - version: "0.6.5+4" - shared_preferences: - dependency: "direct main" + version: "2.1.4" + share_plus_linux: + dependency: transitive description: - name: shared_preferences + name: share_plus_linux url: "https://pub.dartlang.org" source: hosted - version: "0.5.12+2" - shared_preferences_linux: + version: "2.0.3" + share_plus_macos: dependency: transitive description: - name: shared_preferences_linux + name: share_plus_macos url: "https://pub.dartlang.org" source: hosted - version: "0.0.2+2" - shared_preferences_macos: + version: "2.0.2" + share_plus_platform_interface: dependency: transitive description: - name: shared_preferences_macos + name: share_plus_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "0.0.1+10" - shared_preferences_platform_interface: + version: "2.0.1" + share_plus_web: dependency: transitive description: - name: shared_preferences_platform_interface + name: share_plus_web url: "https://pub.dartlang.org" source: hosted - version: "1.0.4" - shared_preferences_web: + version: "2.0.4" + share_plus_windows: dependency: transitive description: - name: shared_preferences_web + name: share_plus_windows url: "https://pub.dartlang.org" source: hosted - version: "0.1.2+7" - shared_preferences_windows: + version: "2.0.3" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.8" + shared_preferences_linux: dependency: transitive description: - name: shared_preferences_windows + name: shared_preferences_linux url: "https://pub.dartlang.org" source: hosted - version: "0.0.1+1" - shelf: + version: "2.0.0" + shared_preferences_macos: dependency: transitive description: - name: shelf + name: shared_preferences_macos url: "https://pub.dartlang.org" source: hosted - version: "0.7.9" - shelf_packages_handler: + version: "2.0.0" + shared_preferences_platform_interface: dependency: transitive description: - name: shelf_packages_handler + name: shared_preferences_platform_interface url: "https://pub.dartlang.org" source: hosted version: "2.0.0" - shelf_static: + shared_preferences_web: dependency: transitive description: - name: shelf_static + name: shared_preferences_web url: "https://pub.dartlang.org" source: hosted - version: "0.2.8" - shelf_web_socket: + version: "2.0.0" + shared_preferences_windows: dependency: transitive description: - name: shelf_web_socket + name: shared_preferences_windows url: "https://pub.dartlang.org" source: hosted - version: "0.2.3" + version: "2.0.0" shimmer: dependency: "direct main" description: name: shimmer url: "https://pub.dartlang.org" source: hosted - version: "1.1.2" + version: "2.0.0" sky_engine: dependency: transitive description: flutter source: sdk version: "0.0.99" - source_map_stack_trace: - dependency: transitive - description: - name: source_map_stack_trace - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.0-nullsafety.3" - source_maps: - dependency: transitive - description: - name: source_maps - url: "https://pub.dartlang.org" - source: hosted - version: "0.10.10-nullsafety.2" source_span: dependency: transitive description: name: source_span url: "https://pub.dartlang.org" source: hosted - version: "1.8.0-nullsafety.2" + version: "1.8.1" sprintf: dependency: "direct main" description: name: sprintf url: "https://pub.dartlang.org" source: hosted - version: "4.1.0" + version: "6.0.0" sqflite: dependency: transitive description: name: sqflite url: "https://pub.dartlang.org" source: hosted - version: "1.3.2+1" + version: "2.0.0+3" sqflite_common: dependency: transitive description: name: sqflite_common url: "https://pub.dartlang.org" source: hosted - version: "1.0.2+1" + version: "2.0.0+2" stack_trace: dependency: transitive description: name: stack_trace url: "https://pub.dartlang.org" source: hosted - version: "1.10.0-nullsafety.1" + version: "1.10.0" stream_channel: dependency: transitive description: name: stream_channel url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.1" + version: "2.1.0" stream_transform: dependency: transitive description: name: stream_transform url: "https://pub.dartlang.org" source: hosted - version: "1.2.0" + version: "2.0.0" string_scanner: dependency: transitive description: name: string_scanner url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.1" + version: "1.1.0" synchronized: dependency: transitive description: name: synchronized url: "https://pub.dartlang.org" source: hosted - version: "2.2.0+2" + version: "3.0.0" term_glyph: dependency: transitive description: name: term_glyph url: "https://pub.dartlang.org" source: hosted - version: "1.2.0-nullsafety.1" - test: - dependency: transitive - description: - name: test - url: "https://pub.dartlang.org" - source: hosted - version: "1.16.0-nullsafety.5" + version: "1.2.0" test_api: dependency: transitive description: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.2.19-nullsafety.2" - test_core: - dependency: transitive - description: - name: test_core - url: "https://pub.dartlang.org" - source: hosted - version: "0.3.12-nullsafety.5" + version: "0.4.2" throttling: dependency: "direct main" description: name: throttling url: "https://pub.dartlang.org" source: hosted - version: "0.8.0" + version: "1.0.0" timeago: dependency: "direct main" description: name: timeago url: "https://pub.dartlang.org" source: hosted - version: "2.0.28" + version: "3.1.0" tinycolor: dependency: "direct main" description: @@ -932,163 +932,184 @@ packages: name: typed_data url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.3" + version: "1.3.0" uni_links: dependency: "direct main" description: name: uni_links url: "https://pub.dartlang.org" source: hosted - version: "0.2.0" + version: "0.5.1" + uni_links_platform_interface: + dependency: transitive + description: + name: uni_links_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.0" + uni_links_web: + dependency: transitive + description: + name: uni_links_web + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.0" url_launcher: dependency: "direct main" description: name: url_launcher url: "https://pub.dartlang.org" source: hosted - version: "5.7.10" + version: "6.0.12" url_launcher_linux: dependency: transitive description: name: url_launcher_linux url: "https://pub.dartlang.org" source: hosted - version: "0.0.1+4" + version: "2.0.0" url_launcher_macos: dependency: transitive description: name: url_launcher_macos url: "https://pub.dartlang.org" source: hosted - version: "0.0.1+9" + version: "2.0.0" url_launcher_platform_interface: dependency: transitive description: name: url_launcher_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "1.0.9" + version: "2.0.3" url_launcher_web: dependency: transitive description: name: url_launcher_web url: "https://pub.dartlang.org" source: hosted - version: "0.1.5+1" + version: "2.0.0" url_launcher_windows: dependency: transitive description: name: url_launcher_windows url: "https://pub.dartlang.org" source: hosted - version: "0.0.1+3" + version: "2.0.0" uuid: dependency: "direct main" description: name: uuid url: "https://pub.dartlang.org" source: hosted - version: "2.2.2" + version: "3.0.4" validators: dependency: "direct main" description: name: validators url: "https://pub.dartlang.org" source: hosted - version: "1.0.0+1" + version: "3.0.0" vector_math: dependency: transitive description: name: vector_math url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.3" + version: "2.1.0" video_player: dependency: "direct main" description: path: "packages/video_player" - ref: "ricardo/develop2" - resolved-ref: "7c584243c4960ba9aa0bd4f144545191c0ccf87e" - url: "https://github.com/OkunaOrg/plugins.git" + ref: nullsafety + resolved-ref: "747bf52fc00d3bbae6198544f9be3a4339442654" + url: "https://github.com/jozsefsallai/flutter-plugins.git" source: git - version: "0.11.0" + version: "0.12.0" video_thumbnail: dependency: "direct main" description: name: video_thumbnail url: "https://pub.dartlang.org" source: hosted - version: "0.2.5+1" + version: "0.4.3" visibility_detector: dependency: "direct main" description: name: visibility_detector url: "https://pub.dartlang.org" source: hosted - version: "0.1.5" - vm_service: + version: "0.2.0" + wakelock: + dependency: "direct main" + description: + name: wakelock + url: "https://pub.dartlang.org" + source: hosted + version: "0.5.6" + wakelock_macos: dependency: transitive description: - name: vm_service + name: wakelock_macos url: "https://pub.dartlang.org" source: hosted - version: "5.3.1" - wakelock: - dependency: "direct main" + version: "0.4.0" + wakelock_platform_interface: + dependency: transitive description: - name: wakelock + name: wakelock_platform_interface url: "https://pub.dartlang.org" source: hosted - version: "0.1.4+2" - watcher: + version: "0.3.0" + wakelock_web: dependency: transitive description: - name: watcher + name: wakelock_web url: "https://pub.dartlang.org" source: hosted - version: "0.9.7+15" - web_socket_channel: + version: "0.4.0" + wakelock_windows: dependency: transitive description: - name: web_socket_channel + name: wakelock_windows url: "https://pub.dartlang.org" source: hosted - version: "1.1.0" - webkit_inspection_protocol: + version: "0.2.0" + watcher: dependency: transitive description: - name: webkit_inspection_protocol + name: watcher url: "https://pub.dartlang.org" source: hosted - version: "0.7.3" + version: "1.0.0" win32: dependency: transitive description: name: win32 url: "https://pub.dartlang.org" source: hosted - version: "1.7.3" + version: "2.0.5" xdg_directories: dependency: transitive description: name: xdg_directories url: "https://pub.dartlang.org" source: hosted - version: "0.1.2" + version: "0.2.0" xml: dependency: transitive description: name: xml url: "https://pub.dartlang.org" source: hosted - version: "4.5.1" + version: "5.1.1" yaml: dependency: transitive description: name: yaml url: "https://pub.dartlang.org" source: hosted - version: "2.2.1" + version: "3.1.0" sdks: - dart: ">=2.10.2 <2.11.0" - flutter: ">=1.22.2 <2.0.0" + dart: ">=2.14.0 <3.0.0" + flutter: ">=2.5.0" diff --git a/pubspec.yaml b/pubspec.yaml index 9b03f848e..2a4c6c604 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -7,76 +7,77 @@ description: Social Network # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # Read more about versioning at semver.org. -version: 1.0.1+99 +version: 1.1.1+99 environment: - sdk: ">=2.1.0 <3.0.0" + sdk: ">=2.12.0 <3.0.0" publish_to: none dependencies: - exif: ^1.0.2 - html: ^0.14.0+2 - expandable: ^4.1.4 - uuid: ^2.0.1 - flutter_image_compress: ^0.7.0 + collection: ^1.15.0 + exif: ^2.2.0 + html: ^0.15.0 + expandable: ^5.0.1 + uuid: ^3.0.4 + flutter_image_compress: ^1.1.0 inview_notifier_list: git: url: https://github.com/OkunaOrg/inview_notifier_list.git - ref: d60972d4928463352781e027f20bd5eca0007cd9 - connectivity: ^0.4.4 - visibility_detector: ^0.1.5 - http_retry: ^0.1.1+3 - video_thumbnail: ^0.2.5+1 - flutter_ffmpeg: ^0.3.0 + ref: e52a3bb077dfb8815e6b7ac51f98ae1603ff26b2 + connectivity: ^3.0.6 + visibility_detector: ^0.2.0 + http_retry: ^0.2.0 + video_thumbnail: ^0.4.3 + flutter_ffmpeg: ^0.4.2 open_iconic_flutter: ^0.3.0 - retry: ^3.0.0+1 - shared_preferences: ^0.5.2 - flutter_markdown: ^0.2.0 - file_picker: ^2.1.5+1 - sentry_flutter: ^4.0.1 + retry: ^3.1.0 + shared_preferences: ^2.0.8 + flutter_markdown: ^0.6.6 + file_picker: ^3.0.2+2 + sentry_flutter: ^5.0.0 screen: ^0.0.5 - back_button_interceptor: ^4.0.1 - flutter_colorpicker: any - intercom_flutter: ^2.3.3 - device_info: ^0.4.0+1 - flutter_pagewise: ^1.2.2 - tinycolor: ^1.0.2 - onesignal_flutter: ^2.6.2 + back_button_interceptor: ^5.0.0 + flutter_colorpicker: ^0.6.0 + intercom_flutter: ^3.2.1 + device_info: ^2.0.2 + flutter_pagewise: ^2.0.1 + tinycolor: ^1.0.3 + onesignal_flutter: ^3.2.3 flutter_advanced_networkimage: git: - url: https://github.com/OkunaOrg/flutter_advanced_networkimage.git - ref: bugfix/fix-breaking-master-change - dcache: ^0.1.0 - validators: ^1.0.0+1 - url_launcher: ^5.7.10 - uni_links: ^0.2.0 - flutter_slidable: "^0.5.7" - flutter_cache_manager: ^1.4.1 - cached_network_image: ^2.2.0+1 - timeago: ^2.0.9 - public_suffix: ^1.2.0 - pigment: ^1.0.3 - photo_view: ^0.9.2 - flutter_svg: 0.18.0 - flutter_secure_storage: ^3.1.2 - mime: ^0.9.6+2 - http: ^0.12.0 - throttling: ^0.8.0 - wakelock: ^0.1.3 - rxdart: ^0.24.1 + url: https://github.com/jozsefsallai/flutter_advanced_networkimage.git + ref: 0b2c9775f8ab375c47f812a459f276b9feb107b8 + dcache: ^0.4.0 + validators: ^3.0.0 + url_launcher: ^6.0.12 + uni_links: ^0.5.1 + flutter_slidable: "^0.6.0" + flutter_cache_manager: ^3.1.0 + cached_network_image: ^3.1.0 + timeago: ^3.1.0 + public_suffix: ^3.0.0 + pigment: ^1.0.4 + photo_view: ^0.12.0 + flutter_svg: ^0.22.0 + flutter_secure_storage: ^4.2.1 + mime: ^1.0.0 + http: ^0.13.3 + throttling: ^1.0.0 + wakelock: ^0.5.6 + rxdart: ^0.27.2 video_player: git: - url: https://github.com/OkunaOrg/plugins.git - ref: ricardo/develop2 + url: https://github.com/jozsefsallai/flutter-plugins.git + ref: nullsafety path: packages/video_player - sprintf: "^4.0.0" - image_picker: 0.6.7+21 - image_cropper: ^1.3.1 - shimmer: ^1.0.0 - share: ^0.6.4 - path: ^1.7.0 - package_info: ^0.4.0 + sprintf: "^6.0.0" + image_picker: ^0.8.4+2 + image_cropper: ^1.4.1 + shimmer: ^2.0.0 + share_plus: ^2.1.4 + path: ^1.8.0 + package_info: ^2.0.2 flutter: sdk: flutter flutter_localizations: @@ -84,13 +85,18 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^0.1.2 + cupertino_icons: ^1.0.3 dev_dependencies: flutter_test: sdk: flutter - flutter_launcher_icons: ^0.7.0 - intl_translation: ^0.17.10+1 + flutter_launcher_icons: ^0.9.0 + intl_generator: ^0.1.0+0 + +# VERY HACKY WORKAROUND. This is temporary until `flutter_launcher_icons` and +# `intl_generator` are playing nice with each other. +dependency_overrides: + args: ^2.0.0 flutter_icons: android: true