Skip to content

Connectivity check #1026

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 108 additions & 4 deletions app/lib/apps/news/news_screen.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import 'dart:async';
import 'dart:convert';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:http/http.dart' as http;
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:threebotlogin/helpers/globals.dart';
import 'package:threebotlogin/helpers/logger.dart';
import 'package:threebotlogin/widgets/layout_drawer.dart';
import 'package:xml2json/xml2json.dart';
import 'package:url_launcher/url_launcher.dart';
Expand All @@ -22,6 +25,8 @@ class _NewsScreenState extends State<NewsScreen> {
final PagingController<int, Map<String, dynamic>> _pagingController =
PagingController(firstPageKey: 0);
final String newsUrl = Globals().newsUrl;
bool _isLoading = false;
String? _errorMessage;

@override
void initState() {
Expand All @@ -30,8 +35,25 @@ class _NewsScreenState extends State<NewsScreen> {
}

Future<void> getArticles(int pageKey) async {
if (_isLoading) return;

_isLoading = true;
try {
final response = await http.get(Uri.parse(newsUrl));
final connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult.contains(ConnectivityResult.none)) {
throw Exception('No internet connection. Please check your network.');
}

final response = await http.get(Uri.parse(newsUrl)).timeout(
const Duration(seconds: 30),
onTimeout: () {
throw TimeoutException('Loading news feed timed out');
},
);

if (response.statusCode != 200) {
throw Exception('Failed to load news feed: ${response.statusCode}');
}
xml2json.parse(response.body);

var data = json.decode(xml2json.toGData());
Expand All @@ -47,11 +69,50 @@ class _NewsScreenState extends State<NewsScreen> {
isLastPage
? _pagingController.appendLastPage(newArticles)
: _pagingController.appendPage(newArticles, pageKey + 1);
} catch (e) {
_pagingController.error = e;

_isLoading = false;
_errorMessage = null;
} on TimeoutException catch (e) {
_handleError(
'Loading news feed timed out. Please check your connection.', e);
} on Exception catch (e) {
_handleError(
e.toString().contains('No internet connection')
? 'No internet connection. Please check your network.'
: 'Failed to load news feed. Please try again.',
e);
}
}

void _handleError(String message, Exception error) {
logger.e('News feed error: $message', error: error);

_isLoading = false;
_errorMessage = message;

_pagingController.error = message;

if (mounted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
message,
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Theme.of(context).colorScheme.errorContainer),
),
duration: const Duration(seconds: 3),
),
);
}
}

Future<void> _refreshNews() async {
_pagingController.refresh();
return Future.delayed(const Duration(milliseconds: 300));
}

@override
void dispose() {
_pagingController.dispose();
Expand All @@ -63,7 +124,7 @@ class _NewsScreenState extends State<NewsScreen> {
return LayoutDrawer(
titleText: 'News',
content: RefreshIndicator(
onRefresh: () async => _pagingController.refresh(),
onRefresh: _refreshNews,
child: PagedListView<int, Map<String, dynamic>>(
pagingController: _pagingController,
builderDelegate: PagedChildBuilderDelegate<Map<String, dynamic>>(
Expand All @@ -82,6 +143,49 @@ class _NewsScreenState extends State<NewsScreen> {
],
),
),
firstPageErrorIndicatorBuilder: (context) => Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error_outline,
size: 48,
color: Theme.of(context).colorScheme.error,
),
const SizedBox(height: 8),
Text(
_errorMessage ?? 'Failed to load news feed',
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: Theme.of(context).colorScheme.onSurface),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _refreshNews,
icon: const Icon(Icons.refresh),
label: const Text('Try Again'),
),
],
),
),
noItemsFoundIndicatorBuilder: (context) => Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.article_outlined,
size: 48,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(height: 8),
Text(
'No articles found',
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
color: Theme.of(context).colorScheme.onSurface),
),
],
),
),
),
),
),
Expand Down
106 changes: 79 additions & 27 deletions app/lib/screens/signing/signing_mixin.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
Expand All @@ -14,6 +17,7 @@ mixin SigningMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
bool isLoading = false;
bool isLoadingWallets = false;
bool loadingFailed = false;
String? walletLoadingError;
String? walletError;
String? destUrlError;

Expand Down Expand Up @@ -132,20 +136,41 @@ mixin SigningMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
}

Future<void> checkWalletsListed() async {
final connectivityResult = await Connectivity().checkConnectivity();

if (connectivityResult.contains(ConnectivityResult.none)) {
_handleWalletLoadingFailure(
'No internet connection. Please check your network.');
return;
}

final walletsNotifierRef = ref.read(walletsNotifier.notifier);
if (!walletsNotifierRef.isListed) {
setState(() {
isLoadingWallets = true;
loadingFailed = false;
walletLoadingError = null;
selectedWallet = null;
});

try {
await walletsNotifierRef.list();
await walletsNotifierRef.list().timeout(
const Duration(seconds: 30),
onTimeout: () {
throw TimeoutException('Loading wallets timed out');
},
);
} on TimeoutException catch (e) {
logger.e('Wallet loading timed out: $e');
if (mounted) {
_handleWalletLoadingFailure(
'Loading wallets timed out. Please check your connection.');
}
} catch (e) {
logger.e('Failed to load wallets: $e');
if (mounted) {
setState(() {
loadingFailed = true;
});
_handleWalletLoadingFailure(
'Failed to load wallets. Please try again.');
}
} finally {
if (mounted) {
Expand All @@ -157,18 +182,56 @@ mixin SigningMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
}
}

void _handleWalletLoadingFailure(String errorMessage) {
setState(() {
isLoadingWallets = false;
loadingFailed = true;
walletLoadingError = errorMessage;
});

if (mounted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
errorMessage,
style: Theme.of(context)
.textTheme
.bodyMedium!
.copyWith(color: Theme.of(context).colorScheme.errorContainer),
),
duration: const Duration(seconds: 3),
),
);
}
}

Future<void> retryLoadingWallets() async {
final connectivityResult = await Connectivity().checkConnectivity();

if (connectivityResult.contains(ConnectivityResult.none)) {
_handleWalletLoadingFailure(
'No internet connection. Please check your network.');
return;
}

setState(() {
isLoadingWallets = true;
loadingFailed = false;
walletLoadingError = null;
selectedWallet = null;
});

final walletsNotifierRef = ref.read(walletsNotifier.notifier);
walletsNotifierRef.clear();

try {
await walletsNotifierRef.list();
await walletsNotifierRef.list().timeout(
const Duration(seconds: 30),
onTimeout: () {
throw TimeoutException('Loading wallets timed out');
},
);

if (mounted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
Expand All @@ -181,28 +244,17 @@ mixin SigningMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
),
);
}
} on TimeoutException catch (e) {
logger.e('Wallet loading timed out on retry: $e');
if (mounted) {
_handleWalletLoadingFailure(
'Loading wallets timed out. Please check your connection.');
}
} catch (e) {
logger.e('Failed to load wallets on retry: $e');
if (mounted) {
setState(() {
loadingFailed = true;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Failed to load wallets. Please check your connection.',
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Theme.of(context).colorScheme.errorContainer),
),
duration: const Duration(seconds: 3),
action: SnackBarAction(
label: 'Retry',
textColor: Theme.of(context).colorScheme.errorContainer,
onPressed: () {
retryLoadingWallets();
},
),
),
);
_handleWalletLoadingFailure(
'Failed to load wallets. Please try again.');
}
} finally {
if (mounted) {
Expand Down Expand Up @@ -258,8 +310,8 @@ mixin SigningMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
child: Text(wallet.name,
style: Theme.of(context)
.textTheme
.bodyMedium
!.copyWith(
.bodyMedium!
.copyWith(
color:
Theme.of(context).colorScheme.onSurface,
)),
Expand Down
Loading