Skip to content

Instantly share code, notes, and snippets.

@callmephil
Last active April 9, 2024 11:23
Show Gist options
  • Save callmephil/f0df00e905e0566ec40c5dac83896a98 to your computer and use it in GitHub Desktop.
Save callmephil/f0df00e905e0566ec40c5dac83896a98 to your computer and use it in GitHub Desktop.
borken connectivity widget flutter
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:internet_connection_checker_plus/internet_connection_checker_plus.dart';
import 'package:xverse_flutter/utils/environment.dart';
class ConnectivityWidget extends StatefulWidget {
const ConnectivityWidget({
super.key,
required this.builder,
});
factory ConnectivityWidget.icons() => ConnectivityIconsWidget();
final Widget Function(BuildContext context, bool hasNetwork) builder;
@override
State<ConnectivityWidget> createState() => _ConnectivityWidgetState();
}
class _ConnectivityWidgetState extends State<ConnectivityWidget> {
InternetStatus? _connectionStatus;
late StreamSubscription<InternetStatus> _subscription;
@override
void initState() {
super.initState();
InternetConnection.createInstance(
checkInterval: const Duration(milliseconds: 500),
useDefaultOptions: false,
customCheckOptions: [
InternetCheckOption(uri: Uri.parse(Environment.epUrl)),
],
);
_subscription = InternetConnection().onStatusChange.listen((status) {
print('Connection status: $status');
// final oldStatus = _connectionStatus;
// if (oldStatus == status) return;
if (mounted) {
setState(() {
_connectionStatus = status;
});
}
});
}
@override
void dispose() {
_subscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext _) {
if (_connectionStatus == null) {
return const Center(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: CircularProgressIndicator(),
),
);
}
return widget.builder(
context,
_connectionStatus == InternetStatus.connected,
);
}
}
class ConnectivityIconsWidget extends ConnectivityWidget {
ConnectivityIconsWidget({
super.key,
}) : super(
builder: (context, hasNetwork) {
print('Connection status: recall 2 $hasNetwork');
return switch (hasNetwork) {
true => const Icon(
Icons.signal_wifi_statusbar_connected_no_internet_4,
color: Colors.green,
),
false => const Icon(
Icons.signal_wifi_statusbar_connected_no_internet_4_outlined,
color: Colors.red,
),
};
},
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment