Failed to get token - flutter

Trying to fetch some data into the cloud firestore database and when I do this I get this error Failed to get token: com.google.firebase.firestore.FirebaseFirestoreException: getToken aborted due to token change..
pubspec.yaml
cloud_firestore: ^0.9.7
firebase_auth: ^0.8.1+4
android/build.gradle:
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:3.1.0'
}
Method that fetched the employee_information:
static addEmployee(Map<String, dynamic> snapshot){
Firestore.instance.runTransaction((Transaction tx) async{
await tx.set(Firestore.instance.collection('employee').document(),snapshot);
});
}
If you've come across this issue let me know, thanks!

for ERROR [FirestoreCallCredentials]: Failed to get token:
go to https://console.cloud.google.com/ - select your project
Select API&Services
Select Credentials
and Update the values in API Keys

Related

Firebase Cloud Messaging (Flutter): Error message when subscribing to topic

I have included Firebase Messaging in my app and I am getting the following error when I try to subscribe to topics.
FLTFirebaseMessaging: An error occurred while calling method Messaging#subscribeToTopic, errorOrNil => {
NSLocalizedFailureReason = "Invalid registration response :'Error=INVALID_PARAMETERS'. It is missing 'token' field.";
}
flutter: subscription error: [firebase_messaging/unknown] An unknown error has occurred.
As you can see it simply says "An unknown error has occurred", which is not very helpful to me.
Here is my code which is meant to obtain permissions for push notifications, then gets the token and subscribes to a list of topics...
Future<void> requestMessagingPermission() async {
FirebaseMessaging messaging = FirebaseMessaging.instance;
NotificationSettings settings = await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
print('User granted permission: ${settings.authorizationStatus}');
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted notifiactions permission');
messaging.getToken().then((token) async {
print('Messaging token: $token');
//configure notification topics
//gets a list of strings (topic names) from provider and loops through them to subscribe to them all
GlobalProvider provider = context.read<GlobalProvider>();
if (provider.notificationTopicsSet == false) {
//subscribe to topics
for (var topic in provider.notificationTopics) {
print('topic subscribing... $topic');
try {
await messaging.subscribeToTopic(topic).then((value) => print('topic subscribed: $topic'));
} catch (e) {
print('subscription error: $e');
}
}
}
});
}
}
I am getting the same error in the console for every topic that is being looped through and subscribed to. The weird thing is that push notifications were working before, but now they don't seem to be.
I have tried updating Flutter to the latest version (3.3.7), I have tried updating both the Firebase Core package (2.1.1) and the Firebase messaging package to their latest versions (14.0.4) and I am still getting the error.
From pubspec.yaml:
firebase_core: ^2.1.1
firebase_messaging: ^14.0.4
What is this token that is missing? The subscribeToTopic() function only seems to take the topic name string. Am I missing something?
Thank you, any help will be greatly appreciated.
This ended up being only an issue with the iOS simulator. The error did not occur with the Android emulator and push notifications work fine on physical devices.

I get Error: Type 'Dio' not found when using Retrofit and Dio together

I just added retrofit to my Flutter app and generated a class as explained here.
But when I want to run my app I get the following error:
Running Gradle task 'assembleAppdevDebug'...
lib/folder/service.g.dart:14:9: Error: Type 'Dio' not found.
I use the following dependencies
dependencies:
dio: ^4.0.6
retrofit: 3.0.1
dev_dependencies:
json_serializable: ^6.2.0
analyzer: ^2.8.0
build_verify: ^3.0.0
retrofit_generator: 3.0.1
build_runner: ^2.1.2
The class definition looks like this
#RestApi(baseUrl: 'https://someapi.com/')
abstract classService {
factory Service(dio.Dio dio, {String baseUrl}) = _Service;
#Headers({
'contentType': 'application/json',
})
#POST('path')
Future<User> createUser(
#Body() User user,
);
}
I found out what the problem was. When I defined the abstract class and added the #Headers annotation the IDE complained that both DIO and Retrofit contained a headers annotation and that I therefore should specify an alias import:
Which I then did by specifying import 'package:dio/dio.dart' as dio;
The alias import though was the reason why the generated _Service file couldn't find Dio.
Solution:
Import retrofit as import 'package:retrofit/retrofit.dart' as rf;
Define the headers as rf.Headers()
#rf.Headers({
'contentType': 'application/json',
})
#POST('path')
Future<User> createUser(
#Body() User user,
);

MockClient 1 positional argument(s) expected, but 0 found

I'm trying to create some tests for flutter app with Mockito.
This is my code:
#GenerateMocks([http.Client])
main() {
group('sendUrlPost', () {
test('returns alias and links if the post call is successful', () async {
final client = MockClient();
String apiUrl = "someApiURL";
String longUrl = "someUrl";
when(client.post(Uri.parse(apiUrl),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(
{"url": longUrl}))).thenAnswer((_) async => http.Response(
'{"alias":"70492","_links":{"self":"https://www.youtube.com","short":"https://url-shortener-nu.herokuapp.com/short/70492"}}',
200));
expect(await UrlPostConnector.sendUrlPost(longUrl), isA<UrlResponse>());
});
});
}
I have followed exactly what the official guide has:
https://docs.flutter.dev/cookbook/testing/unit/mocking
but when I create the mock client I get the following error:
final client = MockClient();
1 positional argument(s) expected, but 0 found. Try adding the
missing arguments
I'm guessing the guide is outdated but I haven't found a way to make it work. I would apprecieate if you can tellme what I'm doing wrong and if there is a better way to test an Http request.
Thanks
I was missing the generated mocks.dart file that is created by running
flutter pub run build_runner build
Thanks to #jamesdlin for pointing that out.
You have to lower down the version to 5.0.0
mockito: ^5.0.0
Make sure you run this command after creating test class
flutter pub run build_runner build

Flutter google sign in serverAuthCode

I'm using this flutter plugin google_sign_in 5.2.1
works good I get the response
{displayName: Mario Mc, email: myemail#gmail.com, id: 117816213074325689769, photoUrl: https://lh3.googleusercontent.com/a-/AOh14GgyaPy7ik693hjyIBmtW5IRXUdCXluaeI=s96-c, serverAuthCode: 4/0AX4XfWiqJ1DMfPaDbgf6gOFVMCfgMicyPqGk25bxjKfA4wq7bJCCu-TWRB8c3rAz_g}
My question is: what is serverAuthCode?
And what's id: 117816213074325689769 used for
And after I send that serverAuthCode to the server, how do I verify that code is legit by calling google servers(as you know any person can send a fake serverAuthCode, so we need to verify it before saving it or do something with it)
I want to use PHP in the server side
thanks
What you can do is use this to get the accessToken then send it to the server
// sign In With Google
_googleSignIn.signIn().then((userData) {
userData.authentication.then((googleKey) {
setState(() {
// Retrieve the email from Google auth
googleEmail = userData.email;
googleId = userData.id;
googlePhotoUrl = userData.photoUrl;
googleServerAuthCode = userData.serverAuthCode;
googleAccessToken = googleKey.accessToken;
googleIdToken = googleKey.idToken;
});
print("googleAccessToken");
print(googleAccessToken);
// call your login function if no errors
checkInternetAndLoginWithGoogle();
}).catchError((err) {
print('inner error');
});
}).catchError((err) {
print('error occurred');
print(err);
});
in the server side, you can verify that access token by calling
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access token>
you will get an answer if that token is valid or expired
Also, you can call this to get user info such as name, email, photo etc.
https://www.googleapis.com/oauth2/v3/userinfo?access_token=<access token>

UNPROCESSABLE ENTITY saving user on Ionic Platform Beta

I have moved from Ionic Platform Alpha to Beta.
I have implemented signup and
login with success, but everytime I try to execute
save action I get this error:
Failed to load resource: the server responded with
a status of 422 (UNPROCESSABLE ENTITY)
Just a snippet of my code:
user = Ionic.User.current();
console.log("User %s is authenticated: %s", user.id, user.isAuthenticated());
user.set('age', '25');
user.save();
This is the output:
User ee18171e-1384-4911-98ed-e1b2fc6e89bf is authenticated: true
Failed to load resource: the server responded with a status
of 422 (UNPROCESSABLE ENTITY) (https://api.ionic.io/auth/user...
Ionic User: Object {response: XMLHttpRequest, error: Error}
Analyzing the error this is shown:
Field may not be null
But I can't figure which field is null is this request ....
Does someone know how to perform a save action on Ionic Platform Beta?
Probably a little late for a reply here,
but just in case someone is looking for an answer.
When setting a user, Ionic is looking for an email address and password:
var details = {
'email': '$scope.data.email',
'password': $scope.data.password
}
Ionic.Auth.signup(details).then(
function(user){
user.migrate();
user.save(); // save the user to persist the migration changes
console.log('success');
},
function(user){
console(user + 'not added to ionic')
}
);
This will register the user