refactor: Migrate routes to go router

This commit is contained in:
krille-chan 2023-08-07 18:40:02 +02:00
commit ee957ab1f6
No known key found for this signature in database
52 changed files with 584 additions and 612 deletions

View file

@ -154,7 +154,7 @@ class ChatSettingsPopupMenuState extends State<ChatSettingsPopupMenu> {
future: () => widget.room.leave(),
);
if (success.error == null) {
VRouter.of(context).to('/rooms');
context.go('/rooms');
}
}
break;
@ -195,10 +195,10 @@ class ChatSettingsPopupMenuState extends State<ChatSettingsPopupMenu> {
);
void _showChatDetails() {
if (VRouter.of(context).path.endsWith('/details')) {
VRouter.of(context).toSegments(['rooms', widget.room.id]);
if (GoRouterState.of(context).uri.path.endsWith('/details')) {
context.go(['', 'rooms', widget.room.id].join('/'));
} else {
VRouter.of(context).toSegments(['rooms', widget.room.id, 'details']);
context.go(['', 'rooms', widget.room.id, 'details'].join('/'));
}
}
}

View file

@ -1,4 +1,3 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
@ -12,17 +11,14 @@ import '../config/app_config.dart';
import '../utils/custom_scroll_behaviour.dart';
import 'matrix.dart';
class FluffyChatApp extends StatefulWidget {
class FluffyChatApp extends StatelessWidget {
final Widget? testWidget;
final List<Client> clients;
final Map<String, String>? queryParameters;
static GlobalKey<VRouterState> routerKey = GlobalKey<VRouterState>();
static GlobalKey<MatrixState> matrixKey = GlobalKey<MatrixState>();
const FluffyChatApp({
Key? key,
this.testWidget,
required this.clients,
this.queryParameters,
}) : super(key: key);
/// getInitialLink may rereturn the value multiple times if this view is
@ -30,59 +26,23 @@ class FluffyChatApp extends StatefulWidget {
/// in with qr code or magic link.
static bool gotInitialLink = false;
@override
FluffyChatAppState createState() => FluffyChatAppState();
}
class FluffyChatAppState extends State<FluffyChatApp> {
bool? columnMode;
String? _initialUrl;
@override
void initState() {
super.initState();
_initialUrl =
widget.clients.any((client) => client.isLogged()) ? '/rooms' : '/home';
}
@override
Widget build(BuildContext context) {
return ThemeBuilder(
builder: (context, themeMode, primaryColor) => LayoutBuilder(
builder: (context, constraints) {
final isColumnMode =
FluffyThemes.isColumnModeByWidth(constraints.maxWidth);
if (isColumnMode != columnMode) {
Logs().v('Set Column Mode = $isColumnMode');
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
_initialUrl = FluffyChatApp.routerKey.currentState?.url;
columnMode = isColumnMode;
FluffyChatApp.routerKey = GlobalKey<VRouterState>();
});
});
}
return VRouter(
key: FluffyChatApp.routerKey,
title: AppConfig.applicationName,
debugShowCheckedModeBanner: false,
themeMode: themeMode,
theme: FluffyThemes.buildTheme(Brightness.light, primaryColor),
darkTheme: FluffyThemes.buildTheme(Brightness.dark, primaryColor),
scrollBehavior: CustomScrollBehavior(),
logs: kReleaseMode ? VLogs.none : VLogs.info,
localizationsDelegates: L10n.localizationsDelegates,
supportedLocales: L10n.supportedLocales,
initialUrl: _initialUrl ?? '/',
routes: AppRoutes(columnMode ?? false).routes,
builder: (context, child) => Matrix(
key: FluffyChatApp.matrixKey,
context: context,
clients: widget.clients,
child: child,
),
);
},
builder: (context, themeMode, primaryColor) => MaterialApp.router(
title: AppConfig.applicationName,
themeMode: themeMode,
theme: FluffyThemes.buildTheme(Brightness.light, primaryColor),
darkTheme: FluffyThemes.buildTheme(Brightness.dark, primaryColor),
scrollBehavior: CustomScrollBehavior(),
localizationsDelegates: L10n.localizationsDelegates,
supportedLocales: L10n.supportedLocales,
routerConfig: GoRouter(routes: AppRoutes(clients).routes),
builder: (context, child) => Matrix(
context: context,
clients: clients,
child: child,
),
),
);
}

View file

@ -1,31 +0,0 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:matrix/matrix.dart';
import 'package:fluffychat/utils/update_checker_no_store.dart';
import 'package:fluffychat/widgets/layouts/empty_page.dart';
import 'package:fluffychat/widgets/matrix.dart';
class LoadingView extends StatelessWidget {
const LoadingView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback(
(_) async {
await UpdateCheckerNoStore(context).checkUpdate();
VRouter.of(context).to(
Matrix.of(context).widget.clients.any(
(client) =>
client.onLoginStateChanged.value == LoginState.loggedIn,
)
? '/rooms'
: '/home',
queryParameters: VRouter.of(context).queryParameters,
);
},
);
return const EmptyPage(loading: true);
}
}

View file

@ -1,7 +1,5 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:fluffychat/config/themes.dart';
class SideViewLayout extends StatelessWidget {
@ -12,14 +10,12 @@ class SideViewLayout extends StatelessWidget {
: super(key: key);
@override
Widget build(BuildContext context) {
var currentUrl = Uri.decodeFull(VRouter.of(context).url);
if (!currentUrl.endsWith('/')) currentUrl += '/';
final hideSideView = currentUrl.split('/').length == 4;
final sideView = this.sideView;
final hideSideView =
!FluffyThemes.isThreeColumnMode(context) || sideView == null;
return sideView == null
? mainView
: MediaQuery.of(context).size.width < FluffyThemes.columnWidth * 3.5 &&
!hideSideView
: hideSideView
? sideView
: Row(
children: [

View file

@ -1,15 +1,15 @@
import 'package:flutter/material.dart';
import '../../config/themes.dart';
class TwoColumnLayout extends StatelessWidget {
final Widget mainView;
final Widget sideView;
final bool displayNavigationRail;
const TwoColumnLayout({
Key? key,
required this.mainView,
required this.sideView,
required this.displayNavigationRail,
}) : super(key: key);
@override
Widget build(BuildContext context) {
@ -20,8 +20,7 @@ class TwoColumnLayout extends StatelessWidget {
Container(
clipBehavior: Clip.antiAlias,
decoration: const BoxDecoration(),
width: 360.0 +
(FluffyThemes.getDisplayNavigationRail(context) ? 64 : 0),
width: 360.0 + (displayNavigationRail ? 64 : 0),
child: mainView,
),
Container(

View file

@ -34,9 +34,9 @@ extension LocalNotificationsExtension on MatrixState {
final event = Event.fromJson(eventUpdate.content, room);
final title =
room.getLocalizedDisplayname(MatrixLocals(L10n.of(widget.context)!));
room.getLocalizedDisplayname(MatrixLocals(L10n.of(navigatorContext)!));
final body = await event.calcLocalizedBody(
MatrixLocals(L10n.of(widget.context)!),
MatrixLocals(L10n.of(navigatorContext)!),
withSenderNamePrefix:
!room.isDirectChat || room.lastEvent?.senderId == client.userID,
plaintextBody: true,
@ -95,11 +95,11 @@ extension LocalNotificationsExtension on MatrixState {
actions: [
NotificationAction(
DesktopNotificationActions.openChat.name,
L10n.of(widget.context)!.openChat,
L10n.of(navigatorContext)!.openChat,
),
NotificationAction(
DesktopNotificationActions.seen.name,
L10n.of(widget.context)!.markAsRead,
L10n.of(navigatorContext)!.markAsRead,
),
],
hints: [
@ -114,7 +114,7 @@ extension LocalNotificationsExtension on MatrixState {
room.setReadMarker(event.eventId, mRead: event.eventId);
break;
case DesktopNotificationActions.openChat:
VRouter.of(navigatorContext).toSegments(['rooms', room.id]);
navigatorContext.go(['', 'rooms', room.id].join('/'));
break;
}
});

View file

@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:matrix/matrix.dart';
class LogViewer extends StatefulWidget {
@ -22,7 +23,9 @@ class LogViewerState extends State<LogViewer> {
backgroundColor: Colors.black,
appBar: AppBar(
title: Text(logLevel.toString()),
leading: const BackButton(),
leading: BackButton(
onPressed: () => context.go('/'),
),
actions: [
IconButton(
icon: const Icon(Icons.zoom_in_outlined),

View file

@ -8,9 +8,7 @@ import 'package:flutter/material.dart';
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:collection/collection.dart';
import 'package:desktop_notifications/desktop_notifications.dart';
import 'package:flutter_app_lock/flutter_app_lock.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:future_loading_dialog/future_loading_dialog.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
@ -18,7 +16,6 @@ import 'package:image_picker/image_picker.dart';
import 'package:matrix/encryption.dart';
import 'package:matrix/matrix.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:universal_html/html.dart' as html;
import 'package:url_launcher/url_launcher_string.dart';
@ -33,7 +30,6 @@ import '../pages/key_verification/key_verification_dialog.dart';
import '../utils/account_bundles.dart';
import '../utils/background_push.dart';
import '../utils/famedlysdk_store.dart';
import 'fluffy_chat_app.dart';
import 'local_notifications_extension.dart';
// import 'package:flutter_secure_storage/flutter_secure_storage.dart';
@ -41,8 +37,7 @@ import 'local_notifications_extension.dart';
class Matrix extends StatefulWidget {
final Widget? child;
GlobalKey<VRouterState> get router => FluffyChatApp.routerKey;
@Deprecated('')
final BuildContext context;
final List<Client> clients;
@ -177,7 +172,7 @@ class MatrixState extends State<Matrix> with WidgetsBindingObserver {
ClientManager.addClientNameToStore(_loginClientCandidate!.clientName);
_registerSubs(_loginClientCandidate!.clientName);
_loginClientCandidate = null;
widget.router.currentState!.to('/rooms');
navigatorContext.go('/rooms');
});
return candidate;
}
@ -244,7 +239,8 @@ class MatrixState extends State<Matrix> with WidgetsBindingObserver {
bool webHasFocus = true;
String? get activeRoomId => navigatorContext.vRouter.pathParameters['roomid'];
String? get activeRoomId =>
GoRouterState.of(navigatorContext).pathParameters['roomid'];
final linuxNotifications =
PlatformInfos.isLinux ? NotificationsClient() : null;
@ -334,15 +330,21 @@ class MatrixState extends State<Matrix> with WidgetsBindingObserver {
);
if (state != LoginState.loggedIn) {
widget.router.currentState?.to(
'/rooms',
queryParameters: widget.router.currentState?.queryParameters ?? {},
navigatorContext.go(
Uri(
path: '/rooms',
queryParameters:
GoRouterState.of(navigatorContext).uri.queryParameters,
).toString(),
);
}
} else {
widget.router.currentState?.to(
state == LoginState.loggedIn ? '/rooms' : '/home',
queryParameters: widget.router.currentState?.queryParameters ?? {},
navigatorContext.go(
Uri(
path: state == LoginState.loggedIn ? '/rooms' : '/home',
queryParameters:
GoRouterState.of(navigatorContext).uri.queryParameters,
).toString(),
);
}
});
@ -375,23 +377,6 @@ class MatrixState extends State<Matrix> with WidgetsBindingObserver {
}
void initMatrix() {
// Display the app lock
if (PlatformInfos.isMobile) {
WidgetsBinding.instance.addPostFrameCallback((_) {
([TargetPlatform.linux].contains(Theme.of(context).platform)
? SharedPreferences.getInstance()
.then((prefs) => prefs.getString(SettingKeys.appLockKey))
: const FlutterSecureStorage()
.read(key: SettingKeys.appLockKey))
.then((lock) {
if (lock?.isNotEmpty ?? false) {
AppLock.of(widget.context)!.enable();
AppLock.of(widget.context)!.showLockScreen();
}
});
});
}
_initWithStore();
for (final c in widget.clients) {
@ -405,8 +390,7 @@ class MatrixState extends State<Matrix> with WidgetsBindingObserver {
if (PlatformInfos.isMobile) {
backgroundPush = BackgroundPush(
client,
context,
this,
onFcmError: (errorMsg, {Uri? link}) async {
final result = await showOkCancelAlertDialog(
barrierDismissible: true,
@ -435,7 +419,7 @@ class MatrixState extends State<Matrix> with WidgetsBindingObserver {
voipPlugin = null;
return;
}
voipPlugin = webrtcIsSupported ? VoipPlugin(client) : null;
voipPlugin = webrtcIsSupported ? VoipPlugin(this) : null;
}
@override
@ -529,30 +513,6 @@ class MatrixState extends State<Matrix> with WidgetsBindingObserver {
}
}
class FixedThreepidCreds extends ThreepidCreds {
FixedThreepidCreds({
required String sid,
required String clientSecret,
String? idServer,
String? idAccessToken,
}) : super(
sid: sid,
clientSecret: clientSecret,
idServer: idServer,
idAccessToken: idAccessToken,
);
@override
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['sid'] = sid;
data['client_secret'] = clientSecret;
if (idServer != null) data['id_server'] = idServer;
if (idAccessToken != null) data['id_access_token'] = idAccessToken;
return data;
}
}
class _AccountBundleWithClient {
final Client? client;
final AccountBundle? bundle;

View file

@ -25,7 +25,8 @@ class ProfileBottomSheet extends StatelessWidget {
future: () => client.startDirectChat(userId),
);
if (result.error == null) {
VRouter.of(context).toSegments(['rooms', result.result!]);
context.go(['', 'rooms', result.result!].join('/'));
Navigator.of(context, rootNavigator: false).pop();
return;
}

View file

@ -31,7 +31,6 @@ class PublicRoomBottomSheet extends StatelessWidget {
final client = Matrix.of(context).client;
final chunk = this.chunk;
final navigator = Navigator.of(context);
final router = VRouter.of(context);
final result = await showFutureLoadingDialog<String>(
context: context,
future: () async {
@ -54,7 +53,7 @@ class PublicRoomBottomSheet extends StatelessWidget {
navigator.pop();
// don't open the room if the joined room is a space
if (!client.getRoomById(result.result!)!.isSpace) {
router.toSegments(['rooms', result.result!]);
context.go(['', 'rooms', result.result!].join('/'));
}
return;
}