Q:Flutter How to get value from parameter inside class - firebase

I'm newbie for android and flutter development, I want to ask something about push notification, I build firebase_messaging by own self because its not support big notification image
The problem is I cant get the _url
int _selectedTab = 1;
static String _url = "";
static const platform =
const MethodChannel('com.example.loop_app_flutter_v2');
#override
Future<void> _firebaseMessageListener() async {
String getRedirect;
String url;
try {
final String result =
await platform.invokeMethod('getFirebaseMessagePayload');
getRedirect = '$result';
Map<String, dynamic> notif = jsonDecode(getRedirect);
url = notif["url"]; //payload success and url show up
} on PlatformException catch (e) {
getRedirect = "Failed : '${e.message}'.";
}
this.loadNotificationData(getRedirect);
setState(() {
_url = url; // i want to assign url to _url and put in List Widget
print(url); //print show up url
});
}
#override
void initState() {
_firebaseMessageListener();
}
final List<Widget> _children = [
new MainArtikel(),
new Webpage(url: _url),
new FeedBack(),
new Setting()
];

Related

The getter 'bodyBytes' isn't defined for the type 'Future<Response> Function(Uri, {Map<String, String>? headers})'

I have updated dat to version 2.12 and I am getting this error:
The getter 'bodyBytes' isn't defined for the type 'Future Function(Uri, {Map<String, String>? headers})'.
Try importing the library that defines 'bodyBytes', correcting the name to the name of an existing getter, or defining a getter or field named 'bodyBytes'.
By code is like the following below:
I am getting 2 red lines below as
"bodyBytes": 1
"result.paths.first": 2
Code
pdf.dart:
class PDFApi {
static Future<File> loadAsset(String path) async {
final data = await rootBundle.load(path);
final bytes = data.buffer.asUint8List();
return _storeFile(path, bytes);
}
static Future<File> loadNetwork(String url) async {
final response = await http.get; Uri.parse(url);
final bytes = response.bodyBytes; <-- here: "bodyBytes": 1
return _storeFile(url, bytes);
}
static Future<File?> pickFile() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if (result == null) return null;
return File(result.paths.first); <-- here: "result.paths.first": 2
}
static Future<File?> loadFirebase(String url) async {
try {
final refPDF = FirebaseStorage.instance.ref().child(url);
final bytes = await refPDF.getData();
return _storeFile(url, bytes!);
} catch (e) {
return null;
}
}
static Future<File> _storeFile(String url, List<int> bytes) async {
final filename = basename(url);
final dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/$filename');
await file.writeAsBytes(bytes, flush: true);
return file;
}
}
I changed final response = await http.get; Uri.parse(url); to final response = await http.get(Uri.parse(url)); thnx to pskink and return File(result.paths.first); to return File(result.paths.first!); , then it works just fine.

A value of type 'Future<String>' can't be assigned to a variable of type 'String'

I have this code where am supposed to upload an image and get the downloaded url but whenever i do that I get this error
my url is String url;. So please why is this not working as it is supposed to
PS
I checked other website to learn how to properly upload but it keeps giving me an error or is there a better way to do this.
My code image
uploadTask.whenComplete(()async{
url = await refs.getDownLoadURL();
....
});
Since it returns a Future you need to wait for it to be accessed
Example :
Future<String> createFolder(String folderName) async {
final dir = Directory(
'${(io.Platform.isAndroid ? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory() //FOR IOS
)!.path}/$folderName');
var status = await Permission.storage.status;
if (!status.isGranted) {
await Permission.storage.request();
}
if ((await dir.exists())) {
return dir.path;
} else {
dir.create();
return dir.path;
}
}
Future<String> getIslamiSahittoBookFilePath(String savename) async {
Future<String> s = createFolder("Islami_Sahitto");
String filePath = await s;
Map<Permission, PermissionStatus> statuses = await [
Permission.storage,
//add more permission to request here.
].request();
io.File? f = null;
if (statuses[Permission.storage]!.isGranted) {
Directory? dir = await DownloadsPath.downloadsDirectory();
if (dir != null) {
String savePath = "${dir.path}/$filePath/$savename";
f = new io.File(savePath);
if (await f.exists()) {}
}
}
return f.toString();
}
Now this block You can use AnyWhere : Future String, to String :
bool isPreviousDownloaded = false;
String previousFilePath = "null";
getIslamiSahittoBookFilePath(fileNameToDownload).then((value) {
if (value != null) {
setState(() {
isPreviousDownloaded = true;
previousFilePath = value;
});
}
});

Can't assign a data value to a string - returns null - flutter

In my code, am trying a assign a string value to an empty string and display on the page but it keeps showing null but when I print it out, it shows the value.
String fName = '';
#override
void initState() {
super.initState();
getData();
}
getData() async {
FirebaseAuth _auth = FirebaseAuth.instance;
User _firebaseUser = _auth.currentUser;
print("============ MyHome ================");
print(_firebaseUser.uid);
_currentUser = await Database().getUserData(_firebaseUser.uid);
if (_currentUser != null) {
fName = _currentUser.firstName;
print(_currentUser.firstName);
}
}
database
Future<UserData> getUserData(String uid) async {
UserData returnValue = UserData();
try {
DocumentSnapshot _docSnapshot =
await _firestore.collection("users").doc(uid).get();
returnValue.uid = uid;
returnValue.firstName = _docSnapshot.data()["firstName"];
returnValue.lastName = _docSnapshot.data()["lastName"];
returnValue.userMail = _docSnapshot.data()["userMail"];
returnValue.userType = _docSnapshot.data()["userType"];
print("====================== on getData =============");
print(returnValue.firstName);
} catch (e) {
print(e);
}
return returnValue;
}
And whenever I try displaying the data it gives me null
Text("Hello, $fName"),
Please how do I do this or am I missing something
use setState to rebuild the widget tree with the value:
setState(() {
fName = _currentUser.firstName;
});
Since the getData function is async, flutter has already built the widget tree before getData finished. You'll now have to update the state using setstate.
setState(() {
fName = _currentUser.firstName;
});
You need to set the new state since we have made changes to the previous state (since your getData function is async.
setState(() {
fName = _currentUser.firstName;
});

Storing thumnail to SqlLite from Flutter App

Here i want to store the thumbnail to My database which is sqlite, and i am not able to store it. i am able to store it in local directory but. i wana call it from my data model. please help
Here is my Code.
_getThumb(videoPathUrl) async {
var appDocDir = await getApplicationDocumentsDirectory();
final folderPath = appDocDir.path;
print(folderPath);
String thumb = await Thumbnails.getThumbnail(
thumbnailFolder: folderPath,
videoFile: videoPathUrl,
imageType: ThumbFormat.JPEG,
quality: 25,
);
print('thumbnail: $thumb');
return thumb = model.thumbnail;
}
}
I Have Found a Solution "the Problem is not with the plugin or the method it adopts to store the Image" The problem is that it is not clear that how should a Unit8List is to be stored in the database.
In My case. __
I am Using this code to Store the Image.
_getThumb(videoPathUrl) async {
final thumb = await VideoThumbnail.thumbnailData(
video: videoPathUrl,
imageFormat: ImageFormat.JPEG,
maxWidth: 100,
maxHeight: 100,
quality: 75,
);
}
Then I am Using this final thumb to be saved against my VideoModel Variable of thumbnail
_getThumb(videoPathUrl) async {
final thumb = await VideoThumbnail.thumbnailData(
video: videoPathUrl,
imageFormat: ImageFormat.JPEG,
maxWidth: 100,
maxHeight: 100,
quality: 75,
);
print('thumbnail $thumb'); //Add these lines
model.thumbnail = thumb; //Add these Lines
return thumb; //Add these lines
}
And Once i have saved it i can see the print result in my debug console. Once i have that i am sure that it is saved.
Now i have to save it as a Blob in my db not as a String.
and thumbnail should be a Unit8List variable not a String Variable.
See the example
and in database
I am Also adding the full Video Model and DbHelper files for Others to use.
VideoModel.dart
import 'dart:typed_data';
import 'model.dart';
class VideoModel extends Model {
static String table = 'videos';
int id;
String videoName;
String video;
Uint8List thumbnail;
VideoModel({
this.id,
this.videoName,
this.video,
this.thumbnail,
});
static VideoModel fromMap(Map<String, dynamic> map) {
return VideoModel(
id: map["id"],
videoName: map['videoName'].toString(),
video: map['video'],
thumbnail: map['thumbnail'],
);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'id': id,
'videoName': videoName,
'video': video,
'thumbnail': thumbnail,
};
if (id != null) {
map['id'] = id;
}
return map;
}
}
DbHelper.dart
abstract class DB {
static Database _db;
static int get _version => 1;
static Future<void> init() async {
if (_db != null) {
return;
}
try {
var databasesPath = await getDatabasesPath();
String _path = p.join(databasesPath, 'video.db');
_db = await openDatabase(_path, version: _version, onCreate: onCreate);
} catch (ex) {
print(ex);
}
}
static void onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE videos (id INTEGER PRIMARY KEY AUTOINCREMENT, videoName STRING, video STRING, thumbnail BLOB)');
}
static Future<List<Map<String, dynamic>>> query(String table) async =>
_db.query(table);
static Future<int> insert(String table, Model model) async =>
await _db.insert(table, model.toMap());
static Future<int> update(String table, Model model) async => await _db
.update(table, model.toMap(), where: 'id = ?', whereArgs: [model.id]);
static Future<int> delete(String table, Model model) async =>
await _db.delete(table, where: 'id = ?', whereArgs: [model.id]);
static Future<Batch> batch() async => _db.batch();
}
Now when you have done these edits You can just all your image using
Image.memory(add your Image Here);
see example:
I hope that this will help some of you if you need help Let me know. Thanks

Stripe.net in Xamarin.Forms PCL with ASP.NET Core MVC Web API

I am trying to implement Stripe.net into my Xamarin.Forms PCL using an ASP.NET Core MVC Web API. The goal is to process credit card payment from users. My web API runs locally on http://localhost:port for testing purposes.
In the PaymentPage, a user enters their credit card information into Entry objects and when they click the submit Button, a method in the PaymentPageViewModel is called to start the logic:
async void OnFinishBookingClicked(object sender, System.EventArgs e)
{
// TODO: Stripe integration
var viewModel = (PaymentPageViewModel)this.BindingContext;
await viewModel.ProcessPayment();
}
This is part of the PaymentPageViewModel:
private readonly IStripeRepository _repository;
private readonly IAPIRepository _api;
public PaymentPageViewModel(IStripeRepository repository, IAPIRepository api)
{
_repository = repository;
_api = api;
}
public async Task ProcessPayment()
{
try
{
if (string.IsNullOrEmpty(ExpirationDate))
ExpirationDate = "09/18";
var exp = ExpirationDate.Split('/');
var token = _repository.CreateToken(CreditCardNumber, exp[0], exp[1], SecurityCode);
await Application.Current.MainPage.DisplayAlert("Test Message", token, "OK");
await _api.ChargeCard(token, 5.00M);
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
}
}
This is what the APIRepository looks like:
public class APIRepository: IAPIRepository
{
const string Url = "http://localhost:5000";
private string authorizationKey;
private async Task<HttpClient> GetClient()
{
HttpClient client = new HttpClient();
if (string.IsNullOrEmpty(authorizationKey))
{
authorizationKey = await client.GetStringAsync(Url);
authorizationKey = JsonConvert.DeserializeObject<string>(authorizationKey);
}
client.DefaultRequestHeaders.Add("Authorization", authorizationKey);
client.DefaultRequestHeaders.Add("Accept", "application/json");
return client;
}
public async Task<string> ChargeCard(string token, decimal amount)
{
HttpClient client = await GetClient();
var json = JsonConvert.SerializeObject(new { token, amount });
var response = await client.PostAsync("/api/Stripe", new StringContent(json));
return await response.Content.ReadAsStringAsync();
}
}
The issue is that I get a series of errors during await _api.ChargeCard(token, 5.00M):
The first exception happens during authorizationKey = await client.GetStringAsync(Url); the exception message is the following:
{System.Net.Http.HttpRequestException: 404 (Not Found) at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode () [0x0000a] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.2.0.11/src/mono/mcs/class/System.Net.Http/System.Net.Http/HttpResponseM…}
I get another exception during response = await client.PostAsync("/api/Stripe", new StringContent(json));
{System.InvalidOperationException: The request URI must either be an absolute URI or BaseAddress must be set at System.Net.Http.HttpClient.SendAsync (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Thr…}
The third exception happens at the catch block of the viewModel.ProcessPayment() method:
{System.NullReferenceException: Object reference not set to an instance of an object at Zwaby.Services.APIRepository+d__3.MoveNext () [0x00184] in /Users/carlos/Projects/Zwaby/Zwaby/Services/APIRepository.cs:57 --- End of stack trace from previou…}
In my Web API project, I have a StripeController, but my implementation may not be fully correct:
[Route("api/Stripe")]
public class StripeController : Controller
{
private readonly StripeContext _context;
public StripeController(StripeContext context)
{
_context = context;
if (_context.StripeCharges.Count() == 0)
{
_context.StripeCharges.Add(new StripeItem { });
_context.SaveChanges();
}
}
[HttpGet]
public IActionResult Get(string key)
{
// TODO: implement method that returns authorization key
}
[HttpPost]
public IActionResult Charge(string stripeToken, decimal amount)
{
var customers = new StripeCustomerService();
var charges = new StripeChargeService();
var customer = customers.Create(new StripeCustomerCreateOptions
{
SourceToken = stripeToken
});
var charge = charges.Create(new StripeChargeCreateOptions
{
Amount = (int)amount,
Description = "Sample Charge",
Currency = "usd",
CustomerId = customer.Id
});
return View();
}
}
For completeness, I am including the StripeRepository class, the other parameter of the PaymentPageViewModel:
public class StripeRepository: IStripeRepository
{
public string CreateToken(string cardNumber, string cardExpMonth, string cardExpYear, string cardCVC)
{
StripeConfiguration.SetApiKey("my_test_key");
//TODO: Wireup card information below
var tokenOptions = new StripeTokenCreateOptions()
{
Card = new StripeCreditCardOptions()
{
Number = "4242424242424242",
ExpirationYear = 2018,
ExpirationMonth = 10,
Cvc = "123"
}
};
var tokenService = new StripeTokenService();
StripeToken stripeToken = tokenService.Create(tokenOptions);
return stripeToken.Id;
}
}
Thank you so much!

Resources