I wrote an one-page desktop app to communicate with TCP Server.
In my code, I use Socket.listen() method to receive data and it is OK.
I used single subscription and it was enough for me.
I tried to convert it to StreamProvider[Riverpod] and I failed.
I used StreamController() then I get bad state.
I used StreamController.broadcast() and I couldn't get data from socket
Could you suggest me correct way?
For a side note: I'm not an experienced flutter developer, just try to learn :)
I added code blocks to below and also full code.
For the full code: https://gist.github.com/sphinxlikee/3cbfa47817a5187c7b67905028674041
UI:
Working code;
Future<void> createConnection() async {
try {
_socket = await Socket.connect(serverAddress, serverPort);
_changeConnectionState();
} catch (e) {
print('connection has an error and socket is null.');
print(e);
return;
}
listenSocket();
}
void listenSocket() {
_socket.listen(
(event) {
_getData(String.fromCharCodes(event));
print('received: $receivedData');
if (!_dataReceived) {
_changeDataReceivedState();
}
},
)
..onDone(
() {
_changeConnectionState();
_streamDone();
print('socket is closed');
},
)
..onError(
(error, stackTrace) {
print('$error');
},
);
}
Working code - UI side
class ReceivedData extends ConsumerWidget {
#override
Widget build(BuildContext context, ScopedReader watch) {
final receivedData = watch(tcpClientProvider).receivedData;
return Text('Received data: $receivedData');
}
}
For the StreamProvider I tried,
Future<void> createConnection() async {
try {
_socket = await Socket.connect(serverAddress, serverPort);
streamController.sink.add(_socket.listen((event) => String.fromCharCodes(event)));
_changeConnectionState();
} catch (e) {
print('connection has an error and socket is null.');
print(e);
return;
}
}
StreamProvider - UI side
final streamProvider = StreamProvider.autoDispose(
(ref) async* {
await for (final value in ref.watch(tcpClientProvider).streamController.stream) {
yield value;
}
},
);
class ReceivedDataWithProvider extends ConsumerWidget {
#override
Widget build(BuildContext context, ScopedReader watch) {
AsyncValue receivedData = watch(streamProvider);
return receivedData.when(
data: (data) => Text('Received data: $data'),
loading: () => const CircularProgressIndicator(),
error: (err, stack) => Text('error'),
);
}
}
Socket implements Stream, so you could just write:
final streamProvider = StreamProvider.autoDispose<Uint8List>((ref) {
return ref.watch(tcpClientProvider)._socket;
});
If you still want to add a listener, there's no harm in having one if you need:
final streamProvider = StreamProvider.autoDispose<Uint8List>((ref) {
final client = ref.watch(tcpClientProvider);
return client._socket
..listen(
(event) {},
).onDone(
() {
client
.._changeConnectionState()
.._streamDone();
print('socket is closed');
},
);
});
Related
my test is throwing an exception because there is a StateNotifierProvider inside which is not overridden. for a regular Provider, i can override it using providerContainer, but for the state of a stateNotifierProvider, I don't know how to do it. I tried my best but I reached the limit of my best. I already saw this and this but it didn't help.
Appreciate much if someone could help me out of this. Thanks
My service File
class ReportService {
final Ref ref;
ReportService({
required this.ref,
});
Future<void> testReport() async {
//* How can i override this provider ?
final connection = ref.read(connectivityServiceProvider);
if (connection) {
try {
await ref.read(reportRepositoryProvider).testFunction();
} on FirebaseException catch (e, st) {
ref.read(errorLoggerProvider).logError(e, st);
throw Exception(e.message);
}
} else {
throw Exception('Check internet connection...');
}
}
}
final reportServiceProvider = Provider<ReportService>((ref) => ReportService(
ref: ref,
));
My test file
void main() {
WidgetsFlutterBinding.ensureInitialized();
final reportRepository = MockReportRepository();
ReportService makeReportService() {
final container = ProviderContainer(overrides: [
reportRepositoryProvider.overrideWithValue(reportRepository),
]);
addTearDown(container.dispose);
return container.read(reportServiceProvider);
}
test('test test', () async {
//How to stub the connectivityServiceProvider here ?
when(reportRepository.testFunction)
.thenAnswer((invocation) => Future.value());
final service = makeReportService();
await service.testReport();
verify(reportRepository.testFunction).called(1);
});
My StateNotifierProvider
class ConnectivityService extends StateNotifier<bool> {
ConnectivityService() : super(false);
}
final connectivityServiceProvider =
StateNotifierProvider<ConnectivityService, bool>(
(ref) => ConnectivityService());
I'm working on a small app with GoogleSignIn-Auth. and stumbled upon a bug I cannot wrap my head around.
It seems like the fold of an Either seems to be skipped. It used to work before, when I had a complicated pile of blocs. Since I started reorganizing my widgets it started to this.
Future<Either<Failure, SignUpSuccess>> signInWithGoogle() async {
try {
final signUpSuccess = await googleRemoteDataSource.signInWithGoogle();
signUpSuccess.fold(
(failure) => () {
print("Got failure!");
return Left(GeneralFailure());
},
(success) => () {
return Right(signUpSuccess);
});
print("I skipped the fold!");
} catch (e) {
print("Caught exception!");
return Left(GeneralFailure());
}
print("Instant fail!");
return Left(GeneralFailure());
}
I have a widget that's listening to a SignInBloc emitting the states:
class SignUpRoot extends StatelessWidget {
SignUpRoot({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: BlocProvider(
create: (context) => sl<SignInBloc>(),
child: BlocListener<SignInBloc, SignInState>(
listener: (context, state) {
if (state is SignInWithGoogleLoaded) {
// Navigate to SignInNamePage
print("This seems to work!");
} else if (state is SignInWithGoogleLoading) {
// Navigate to loading page
print("Loading Google...");
} else if (state is SignInError) {
// Navigate to error page
print("An error occured while signing in!");
}
},
child: const SignUpMainPage(),
)));
}
And last but not least my bloc:
class SignInBloc extends Bloc<SignInEvent, SignInState> {
final SignUpUseCases useCases;
SignInBloc({required this.useCases}) : super(SignInInitial()) {
on<SignInWithGooglePressed>((event, emit) async {
// Show Loading indicator
emit(SignInWithGoogleLoading());
// wait for sign in response
Either<Failure, SignUpSuccess> successOrFailure =
await useCases.signInWithGoogle();
// emit corresponding state
successOrFailure.fold(
(failure) => emit(SignInError()),
(success) => () {
// emit sign in loaded state
emit(SignInWithGoogleLoaded());
// create new (local) user
// assign user data e.g. display name
});
});
}
}
Thanks for any help!
The problem is that the fold method returns the value of the left or right functions.
https://pub.dev/documentation/dartz/latest/dartz/Either/fold.html
B fold<B>(
B ifLeft(
L l
),
B ifRight(
R r
)
)
Your code should be corrected to:
Future<Either<Failure, SignUpSuccess>> signInWithGoogle() async {
try {
final signUpSuccess = await googleRemoteDataSource.signInWithGoogle();
return signUpSuccess.fold(
(failure) => () {
return Left(GeneralFailure());
},
(success) => () {
return Right(signUpSuccess);
});
} catch (e) {
return Left(GeneralFailure());
}
return Left(GeneralFailure());
}
I just added the return at the start of the fold, now the value returned from left or right will be returned by your function.
You just have to remove the arrow in the success part of the fold.
Future<Either<Failure, SignUpSuccess>> signInWithGoogle() async {
try {
final signUpSuccess = await googleRemoteDataSource.signInWithGoogle();
signUpSuccess.fold(
(failure) => () {
print("Got failure!");
return Left(GeneralFailure());
},
(success){
return Right(signUpSuccess);
});
print("I skipped the fold!");
} catch (e) {
print("Caught exception!");
return Left(GeneralFailure());
}
print("Instant fail!");
return Left(GeneralFailure());
}
class SignInBloc extends Bloc<SignInEvent, SignInState> {
final SignUpUseCases useCases;
SignInBloc({required this.useCases}) : super(SignInInitial()) {
on<SignInWithGooglePressed>((event, emit) async {
// Show Loading indicator
emit(SignInWithGoogleLoading());
// wait for sign in response
Either<Failure, SignUpSuccess> successOrFailure =
await useCases.signInWithGoogle();
// emit corresponding state
successOrFailure.fold(
(failure) => emit(SignInError()),
(success) {
emit(SignInWithGoogleLoaded());
});
});
}
}
Future<bool> connectServer(BuildContext context) async {
try {
// await _displayTextInputDialog(context);
// socket = await Socket.connect(_textFieldController.text, 2508,
// timeout: const Duration(seconds: 4));
socket = await Socket.connect("192.168.14.148", 2508,
timeout: const Duration(seconds: 4));
stream = socket.listen(null);
return true;
} on SocketException {
await Navigator.pushNamed(
context,
'/connectionE',
);
return false;
}
}
Future<dynamic> receiveMessage() {
final completer = Completer();
print("before");
stream.onData((data) {
print(data);
if (data.contains(49)) {
print(data);
completer.complete(extractData(data));
stream.cancel();
}
});
print('after');
return completer.future;
}
Future<String> sendAndWait(
BuildContext context, String message, int code) async {
try {
sendMessage(message, code);
print("sended");
String reply = await receiveMessage();
stream.onData((data) {});
print(reply);
return "";
} on SocketException {
Navigator.pushReplacementNamed(
context,
'/serverDownE',
);
}
return "2";
}
receiveMessage work on the first time, but then stop working, it doesn't even get into the onData function. Does someone know why is this happening? I cant use cancel on the subscription, cancel and start new one because when I start listening again I get an error Bad state stream has already been listening. I can't close the socket because the the server is a stateful server.
I am using a MultiBlocProvider which is working for all Bloc before I migrate it to v8.0.1. Now, only the first Bloc (SignInBloc) is working.
This is on my main.dart
return MultiBlocProvider(
providers: [
BlocProvider<SignInBloc>(
create: (context) => SignInBloc(
authenticationRepository: authenticationRepository,
userDataRepository: userDataRepository,
),
),
BlocProvider<SignUpBloc>(
create: (context) => SignUpBloc(
authenticationRepository: authenticationRepository,
userDataRepository: userDataRepository,
),
),
Edit: here is my SignInBloc
SignInBloc(
{required this.authenticationRepository,
required this.userDataRepository})
: super(SignInInitialState()) {
on<CheckIfSignedInEvent>(mapCheckIfSignedInEventToState);
}
Future<void> mapCheckIfSignedInEventToState(
CheckIfSignedInEvent event,
Emitter<SignInState> emit,
) async {
try {
bool isSignedIn = await authenticationRepository.checkIfSignedIn();
if (isSignedIn) {
emit(CheckIfSignedInEventCompletedState(true));
} else {
emit(CheckIfSignedInEventCompletedState(false));
}
} catch (e) {
print(e);
emit(CheckIfSignedInEventFailedState());
}
}
I am not sure what to show but here is my SignUpBloc which is similar to my SignInBloc
SignUpBloc(
{required this.authenticationRepository,
required this.userDataRepository})
: super(SignUpInitialState()) {
on<SignUpWithGoogle>(mapSignUpWithGoogleEventToState);
}
Stream<SignUpState> mapSignUpWithGoogleEventToState(
SignUpWithGoogle event,
Emitter<SignUpState> emit,
) async* {
emit(SignUpInProgressState());
try {
User? checkUser = await authenticationRepository.checkIfUserExists();
if (checkUser != null) {
emit(SignUpWithGoogleInitialExistState());
} else {
bool checkDup =
await authenticationRepository.checkIfUserDup(event.name);
if (checkDup == true) {
emit(SignUpWithNameExistState());
} else {
User firebaseUser = await authenticationRepository.signUpWithGoogle();
emit(SignUpWithGoogleInitialCompletedState(firebaseUser));
}
}
} catch (e) {
print(e);
emit(SignUpWithGoogleInitialFailedState());
}
}
My main.dart will call the splash screen which has the declaration of the bloc
late SignInBloc signInBloc;
late SignUpBloc signupBloc;
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
signInBloc = BlocProvider.of<SignInBloc>(context);
signupBloc = BlocProvider.of<SignUpBloc>(context);
What I tried to do it to put alot of Print statement in order to check which part is getting called but I don't get why the SignUpBloc is not getting called anymore. Please help. Thanks!
Edit: I tried to debug.
This will trigger my SignInBloc. I'm able to listen to my SignInBloc.
signInBloc.add(CheckIfSignedInEvent());
This should trigger my SignUpBloc. But it doesn't do anything similar to my SignInBloc.
signupBloc.add(SignUpWithGoogle(name: selectedName));
Here's both of my events for comparison:
class CheckIfSignedInEvent extends SignInEvent {
#override
String toString() => 'CheckIfSignedInEvent';
}
class SignUpWithGoogle extends SignUpEvent {
final String name;
SignUpWithGoogle({required this.name});
#override
String toString() => 'SignUpWithGoogleEvent';
}
This is the part where I listen to the states which is both in my splash screen. Only signInBloc is able to listen.
signupBloc.stream.listen((state) {
print('BLOC: signupBloc splash screen init : $state');
});
signInBloc.stream.listen((state) {
print('BLOC: signinBloc splash screen init : $state');
});
It turns out that changing the Stream to Future will fix my issue. async* should also be changed to async
Future<void> mapSignUpWithGoogleEventToState(
SignUpWithGoogle event,
Emitter<SignUpState> emit,
) async {
emit(SignUpInProgressState());
try {
User? checkUser = await authenticationRepository.checkIfUserExists();
if (checkUser != null) {
emit(SignUpWithGoogleInitialExistState());
} else {
bool checkDup =
await authenticationRepository.checkIfUserDup(event.name);
if (checkDup == true) {
emit(SignUpWithNameExistState());
} else {
User firebaseUser = await authenticationRepository.signUpWithGoogle();
emit(SignUpWithGoogleInitialCompletedState(firebaseUser));
}
}
} catch (e) {
print(e);
emit(SignUpWithGoogleInitialFailedState());
}
}
I am using uni_links to get deeplink form other apps and trying to open the url in app using flutter_web_browser but when I open the app through deeplink it does not open the url instead its throwing an error called "dependOnInheritedWidgetOfExactType<_InheritedTheme>() or dependOnInheritedElement() was called before _HomeState.initState() completed." Below is my main.dart and homepage.dart
main.dart
import 'package:flutter/material.dart';
import 'home_widget.dart';
void main(){
runApp(new MaterialApp(
debugShowCheckedModeBanner: false,
title: 'title',
theme: ThemeData(
// Define the default Brightness and Colors
brightness: Brightness.light,
primaryColor: Colors.deepOrange[800],
accentColor: Colors.orange[600],
),
home: Home(),
));
}
Homepage.dart
class Home extends StatefulWidget {
const Home({
Key key,
}) : super(key: key);
#override
State<StatefulWidget> createState() {
return _HomeState();
}
}
class _HomeState extends State<Home> {
String _latestLink = 'Unknown';
Uri _latestUri;
StreamSubscription _sub;
UniLinksType _type = UniLinksType.string;
#override
void initState(){
super.initState();
initPlatformState();
}
initPlatformState() async {
if (_type == UniLinksType.string) {
await initPlatformStateForStringUniLinks();
} else {
await initPlatformStateForUriUniLinks();
}
}
initPlatformStateForStringUniLinks() async {
// Attach a listener to the links stream
_sub = getLinksStream().listen((String link) {
if (!mounted) return;
setState(() {
_latestLink = link ?? 'Unknown';
_latestUri = null;
try {
if (link != null) _latestUri = Uri.parse(link);
} on FormatException {}
});
}, onError: (err) {
if (!mounted) return;
setState(() {
_latestLink = 'Failed to get latest link: $err.';
_latestUri = null;
});
});
// Attach a second listener to the stream
getLinksStream().listen((String link) {
print('got link: $link');
// launchURL(link);
}, onError: (err) {
print('got err: $err');
});
// Get the latest link
String initialLink;
Uri initialUri;
launchURL(initialLink);
// Platform messages may fail, so we use a try/catch PlatformException.
try {
initialLink = await getInitialLink();
if (initialLink != null) initialUri = Uri.parse(initialLink);
print('initial link: $initialLink');
} on PlatformException {
initialLink = 'Failed to get initial link.';
initialUri = null;
print(initialLink);
} on FormatException {
initialLink = 'Failed to parse the initial link as Uri.';
initialUri = null;
print(initialLink);
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_latestLink = initialLink;
_latestUri = initialUri;
});
}
initPlatformStateForUriUniLinks() async {
// Attach a listener to the Uri links stream
_sub = getUriLinksStream().listen((Uri uri) {
if (!mounted) return;
setState(() {
_latestUri = uri;
_latestLink = uri?.toString() ?? 'Unknown';
});
}, onError: (err) {
if (!mounted) return;
setState(() {
_latestUri = null;
_latestLink = 'Failed to get latest link: $err.';
});
});
// Attach a second listener to the stream
getUriLinksStream().listen((Uri uri) {
print('got uri: ${uri?.path} ${uri?.queryParametersAll}');
}, onError: (err) {
print('got err: $err');
});
// Get the latest Uri
Uri initialUri;
String initialLink;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
initialUri = await getInitialUri();
print('initial uri: ${initialUri?.path}'
' ${initialUri?.queryParametersAll}');
initialLink = initialUri?.toString();
} on PlatformException {
initialUri = null;
initialLink = 'Failed to get initial uri.';
} on FormatException {
initialUri = null;
initialLink = 'Bad parse the initial link as Uri.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_latestUri = initialUri;
print("latestUri : $_latestUri");
_latestLink = initialLink;
print("latestLink: $_latestLink");
});
}
launchURL(link) async {
await FlutterWebBrowser.openWebPage(url: link,androidToolbarColor: Theme.of(context).primaryColor);
}
#override
Widget build(BuildContext context){
return Scaffold(...)
}
#override
void dispose() {
// _bannerAd?.dispose();
super.dispose();
}
Try to call initPlatformState() after initState() has completed.
Something like this:
#override
void initState() {
super.initState();
Future.delayed(Duration.zero, () {
initPlatformState();
});
}
Another workaround is by adding a frame callback, which is better than using Future.delayed with a zero duration.
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
initPlatformState();
});
}
It is more explicit and clear as to what is happening. This kind of situation is what frame callback was designed for.