Use of Tokens on flutter - flutter

I´m new in this site and in flutter, I´m trying to get connected to an API,and I have been running into issues with white spaces I´m using uri.https, and im currently using single and double quotes because that's the only way I found I can avoid the "+" from show in the white space ok the TOKEN. whithout that I receive this error.
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Unexpected character (at character 1)
Having say it that this is my code:
String _token='"Token 25e94e9fc7d38d6a10bb9328fb07546881602467"';
final Map<String, String> header={
'Authorization':_token
};
final response = await http.post(url,headers:header,body: json.encode(androidid));
final Map<String, dynamic> decodedResp = json.decode(response.body.toString());
print(decodedResp);
print(response.statusCode);
print(header);
and after that I get this:
I/flutter (24825): {detail: Authentification credentials were not provided.}
I/flutter (24825): 401
I/flutter (24825): {Authorization: "Token 25e94e9fc7d38d6a10bb9328fb07546881602467"}
it supose that the API is waiting for something as {Authorization: Token 25e9............
I have been trying to the request in that way, ´cause I´m working on a team and it´s like they´re waiting that I process the data, I´m not even sure if it´s possible do it in that way(using the word and the number)

I don't think that "Token" should be inside a token

Related

Post request flutter

i'm trying to do a post request but all the time i get this error
Uncaught Error: XMLHttpRequest error.
i' working on dartpad on line and i'm using the package http.dart .I don't get the problem despite i post a json format i dont understand why the error is with the xml ?!
this my code :
import 'package:http/http.dart' as http;
void main() async {
// This will be sent as form data in the post requst
var map = new Map<String, dynamic>();
map['username'] = '**********';
map['password'] = '**********';
final response = await http.post(
Uri.parse('************'),
body: map,
);
print(response.body);
}
I suggest the following:
Verify that your URI is correct, I tried your code on DartPad with a simple GET request onto a Free API I found on the web and I get no errors
Verify that your endpoint has no weird CORS errors with another client (e.g. postman or Dio, see below)
Verify that you don't have weird cache values onto your machine. Doing a flutter clean && flutter pub get might help
Consider using Dio (pub.dev) as your http client as the dart's inner http package isn't quite ready for production imho.

event input dialog flowtter

I want to raise a Dialogflow event from the flutter app using dialog flowtter. There is an exception. 400 field input not set. what can I do?
DetectIntentResponse response = await dialogFlowtter.detectIntent(
queryInput: QueryInput(
eventInput:
EventInput(name:"username",languageCode: "en", parameters:{username: user!.uid})),
audioConfig: OutputAudioConfig(),
);
Unhandled Exception: Exception: INVALID_ARGUMENT: Field input not set., (400)
I found out it was a bug from the dialog flowtter library. it is now changed in version 0.3.2

Unexpected character (at character 2) while parsing json using dio

I was getting data from api using dio. It was successful but when data gets and it gets an exception.
Unexpected character (at character 2) {data:{id:5, name: ....
in error log, shows an arrow in beneath d(data)
What to do?
When I changed responsetype only for this API. It worked.
await dio.get(
url,
options: Options(
responseType: ResponseType.plain,
),
This is not related to Dio however, I had this error when accessing data from the local repository (Shared Preferences).
After hours I discovered that the data was not correctly saved as a json string which made the decoding throw an error.
Correct way.
await _prefs?.setStringList(
_itemsKey, itemsJson.map((e) => json.encode(e)).toList());

Unhandled Exception: Bad State: Stream has already been listened to

I have the following code to navigate the user to the Home Screen upon successful authentication
Future navigateToHomeScreen(
StreamedResponse value,
BuildContext context,
) async {
print('Navigating to Home Screen');
String userString = await value.stream.bytesToString();
Map<String, dynamic> logInResponseData = jsonDecode(userString)['data'];
UserManager.persistUser(logInResponseData);
Navigator.of(context).pushReplacementNamed(HomeWidget.routePath);
}
After a successful sign up or sign in the above function is called but I keep getting:
Unhandled Exception: Bad state: Stream has already been listened to.
How do I fix this?
You can't add multiple listeners to a regular stream. In your code, if your navigateToHomeScreen function is getting called multiple times, you are basically adding that many listeners to the stream. You have two ways to fix it.
Check if the stream is already having any listener or not. If it has, remove it before adding a new one.
This is a bit easier one but not the best solution. You can convert your stream to a BroadcastStream by doing : value.stream.asBroadcastStream().bytesToString(); This will convert your regular stream to broadcast stream. By doing this you can add multiple listeners to your stream by why it's not the best option becuase if your previous stream listeners are not killed, they will keep getting notified and will keep consuming your reads. If you are using a service which charge you based on read writes(like cloud firestore) then this might not be a good idea.
https://medium.com/flutter-community/flutter-stream-basics-for-beginners-eda23e44e32f Here is a link to gain better understanding of Streams in Dart and Flutter

How to solve the {code: UNAUTHENTICATED, details: null, message: UNAUTHENTICATED}) error using Google Cloud Functions?

I am currently facing the above mentioned error when using the cloud_functions dependency on my Flutter app. My function https call is as follows:
final HttpsCallable callable = CloudFunctions(region: "region name").getHttpsCallable(functionName: 'function-name')..timeout = const Duration(seconds:30);
And my function invocation within the code is as given below:
onPressed: () async {
try {
dynamic resp = await callable.call(<String, dynamic>{
'message':'hello!',
'url': urlController.text,
});
setState(() {
imgurl = resp.data['image'];
time = resp.data['timestamp'];
});
I have added the ID I am using for authentication to my function via the console IAM. Unfortunately, I still keep receiving the following error:
PlatformException(functionsError, Cloud function failed with exception., {code: UNAUTHENTICATED, details: null, message: UNAUTHENTICATED})
How can I resolve that?
Thanks for your help in advance.
If you have deployed your function in "private mode", I mean, allow only authenticated user, you have to add a valid identity_token in the header of your request.
You have an example here, mostly on end user because it's your use case. Don't use a service account key file because your flutter app is public and you will share your secret publicly.
You can also use Cloud Endpoint with Firebase authentication mode. I wrote an article for setting up an authentication with API key. Simply update the authentication mode and it will works.