How to get parameter value from link in flutter? - flutter

I am using Firebase dynamic links and I save it to a deepLink variable and pass it to the next page. Tell me, how can I get the code and pageName parameters from the link so that I can use them in the future?
url
https://.........app?pageName=emailActivationPage&code=7075
code
await Firebase.initializeApp();
final PendingDynamicLinkData? initialLink =
await FirebaseDynamicLinks.instance.getInitialLink();
if (widget.initialLink != null) {
final Uri deepLink = widget.initialLink!.link;
routeCubit.toForgotPasswordPage(deepLink.path, true);
} else {
routeCubit.toPhoneNumberPage();
}

You can access the data through the queryParameter property. It also should be a good idea to check beforehand if the key is given in the Map
if(deepLink.queryParameters.containsKey('code')){
final code = deepLink.queryParameters['code'];
}

Related

How to pass header to URL in Flutter

I have a question regarding how to view a PDF from URL.
I’m using flutter_pdfview library and I try to get a PDF from an URL and to view it in my Flutter app.
The problem is that my URL can be accessed ONLY with a token (session ID/header), but I don’t know how to pass it because is not working on the way I do it at the moment.
Here is an example of how the owner of the flutter_pdfview library is getting the PDF from an URL (without a Header): https://github.com/endigo/flutter_pdfview/blob/master/example/lib/main.dart#L49
And here is my code where I don’t know how else to pass the header than like this:
Future<File> createFileOfPdfUrl() async {
Completer<File> completer = Completer();
if (kDebugMode) {
print("Start download file from internet!");
}
try {
String url =
"$customURL.pdf";
if (kDebugMode) {
print("url: $url");
}
final filename = url.substring(url.lastIndexOf("/") + 1);
var client = HttpClient();
HttpClientRequest request = await client.getUrl(Uri.parse(url));
request.headers.add(
HttpHeaders.acceptHeader,
HeaderValue(
"text/plain", {'APPAUTH': '${widget.authService.loginToken}'})); // this method doesn't seems to work for me. I'm getting an empty PDF.
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
var dir = await getApplicationDocumentsDirectory();
if (kDebugMode) {
print("Download files");
print("${dir.path}/$filename");
}
File file = File("${dir.path}/$filename");
await file.writeAsBytes(bytes, flush: true);
completer.complete(file);
} catch (e) {
throw Exception('Error parsing asset file!');
}
return completer.future;
}
DO NOT do this:
request.headers.add(
HttpHeaders.acceptHeader, // here is the problem
HeaderValue(
"text/plain", {'APPAUTH': '${widget.authService.loginToken}'}));
SOLUTION for me:
request.headers.add("APPAUTH", "12345abcde67890defgh");
For some reason if you provide a HeaderValue you also need to provide a string value before it, which can be HttpHeaders.acceptHeader or HttpHeaders.serverHeader etc. I tried a lot of them from that enum list and none worked for me so I used the above solution where you don't need to pass that HttpHeader value type.

In Flutter "final response = await http.get(url);" I am getting an error in the url part of the code

I am getting an error in the url part of the code, I have shown the error in the screenshot. How can I fix my code without changing its function.
Future<List<Articles>?> getNews() async {
String url = "https://jsonplaceholder.typicode.com/posts";
final response = await http.get(url);
if (response.body.isEmpty) {
final responseJson = json.decode(response.body);
News news = News.fromJson(responseJson);
return news.articles;
}
return null;}
You need to pass Uri instead of string.
final response = await http.get(Uri.parse(url));
You can assign uri something like this
var uri= Uri.https('jsonplaceholder.typicode.com', 'posts');
And if you want to add queryparametrs then use below code
final queryParameters =
{
'key' : 'value',
};
var uri= Uri.https('jsonplaceholder.typicode.com', 'posts',queryParameters);
And use this uri in place of Url.
final response = await http.get(uri);

How to use firebase Dynamic Link with flutter go_route package

in firebase doc they call FirebaseDynamicLinks.instance.getInitialLink() in main funtion but with go route can i call it main funtion and how to handle initialLink
where i call getInitialLink() !!
Future<void> fBdynamicLink() async {
// Get any initial links
final PendingDynamicLinkData? initialLink =
await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
debugPrint('initialLink ${initialLink.toString()}');
final Uri deepLink = initialLink.link;
// Example of using the dynamic link to push the user to a different screen
context.push(deepLink.path);
}
}

How to get the google docs/spreadsheet id using google drive api in flutter?

I have created a function that is implemented in my flutter app, I set up all the configurations in the google cloud console for uploading files to google drive API. My function looks like this
Future<void> uploadFileOnDrive() async {
try {
//auth credentials
final googleSignIn =
signIn.GoogleSignIn.standard(scopes: [drive.DriveApi.driveScope]);
final signIn.GoogleSignInAccount? account = await googleSignIn.signIn();
// print("User account $account");
final authHeaders = await account!.authHeaders;
final authenticateClient = GoogleAuthClient(authHeaders);
final driveApi = drive.DriveApi(authenticateClient);
//Uploading the file with "hi" text
final Stream<List<int>> mediaStream =
Future.value([104, 105]).asStream().asBroadcastStream();
var media = new drive.Media(mediaStream, 2);
var driveFile = new drive.File();
driveFile.name = "hello_world.txt";
final result = await driveApi.files.create(driveFile, uploadMedia: media);
//printing the values
print(result.driveId);
print(result.name);
print(result.id);
print(result.createdTime);
print("Upload result: $result");
Fluttertoast.showToast(msg: "Uploaded succesfully");
} catch (e) {
Fluttertoast.showToast(msg: e.toString());
}
}
This function is uploading files successfully on my drive but I need to edit these files for which I need their ID.
The result contains the Instance of 'file' but when I try to print the result.driveId, I get null value but result.name is printing "hello_world.txt" correctly and result.id is also printing some id which is not the actual id of the "hello_world.txt" file (I checked the URL, it does not match).
Am I doing anything wrong here? Please correct me. Thanks

How to use Uri function properly in Flutter? Difference between Uri and Url

I am confused with the URL and Uri in dart/flutter.
I created this function to be used in my PDF viewer.
static Future<File> loadNetwork(String url) async {
final response = await http.get(Uri.parse(url));
final bytes = response.bodyBytes;
return _storeFile(url, bytes);
}
and I want to call this function to display the specific PDF after clicking a button.
onTap: () async {
setState(() {
isLoading = true;
});
final url = 'http://www.africau.edu/images/default/sample.pdf';
final file = await PDFApi.loadNetwork(url);
openPDF(context, file);
setState(() {
isLoading = false;
});
},
But, still, how do I properly use the Uri and fetch the pdf link. There is an error and I suspect I am using the function wrongly.
It says invalid internet address.
Thanks!
To convert a url to Uri use Uri.parse("url here")