I make a program to save photo in the Firebase Storage and then take a url and write it to the Firebase database.
File sampleImage;
String changePhoto;
Future getImage() async {
var tempImage = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
sampleImage = tempImage;
});
}
Future getUrl(name) async
{
final ref = FirebaseStorage.instance.ref().child(name);
changePhoto = await ref.getDownloadURL();
print(changePhoto);
return changePhoto;
}
Widget submitButton() {
final name = productName.text;
return RaisedButton(
textColor: Colors.white,
color: Color(0xffd50000),
child: Text("Add"),
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0)),
onPressed: () {
final StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child(name);
final StorageUploadTask task =
firebaseStorageRef.putFile(sampleImage);
getUrl(name);
_bloc.submit(changePhoto);
print(5);
Navigator.of(context).pop();
});
}
But i have problem with
changePhoto = await ref.getDownloadURL();
because ref.getDownloadURL() returns a dynamic variable. I tried to use
Future loadPhoto(name)
{
final StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child(name);
final StorageUploadTask task =
firebaseStorageRef.putFile(sampleImage);
}
onPressed: () {
loadPhoto(name).then((snapshot){
final ref = FirebaseStorage.instance.ref().child(name);
changePhoto = snapshot.ref.getDownloadURL();
print(changePhoto);
_bloc.submit(changePhoto);
print(5);
Navigator.of(context).pop();
});
But it doesn't work. What is my mistake or how I can get snapshot?
Any help is much appreciated.
Wait to finish upload process like;
var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
Related
I'm trying to track location in the background using flutter and to do so I'm using the background_locator plugin. It has been implemented in such a way that there are certain static callback functions that were registered. I've declared a class variable of File type to save the log in the background. The global variable is built at the very beginning of the class.
Issue: While invoking the callback method, the global variable built is becoming null. So though I could see the location log in my console, I couldn't write it to the file as the object is null.
Tries:
I've tried with the exact example provided in their documentation.
I've declared it as non static property and tried to access with the class object.
Tried it out declaring it as static property as well.
Tried building file object with the same path every time needed but it is throwing following issue.
No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider
Here is my complete source code for reference.
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'dart:ui';
import 'package:background_locator/background_locator.dart';
import 'package:background_locator/location_dto.dart';
import 'package:background_locator/settings/android_settings.dart';
import 'package:background_locator/settings/ios_settings.dart';
import 'package:background_locator/settings/locator_settings.dart';
import 'package:flutter/material.dart';
import 'package:location_permissions/location_permissions.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart' as ph;
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
ReceivePort port = ReceivePort();
String logStr = '';
bool isRunning = false;
LocationDto? lastLocation;
bool permissionsGranted = false;
static const String isolateName = 'LocatorIsolate';
static int _count = -1;
static File? finalFile;
void requestPermission() async {
var storageStatus = await ph.Permission.storage.status;
if (!storageStatus.isGranted) {
await ph.Permission.storage.request();
}
if (storageStatus.isGranted) {
permissionsGranted = true;
setPrerequisites();
}
setState(() {});
}
static Future<void> init(Map<dynamic, dynamic> params) async {
//TODO change logs
print("***********Init callback handler");
if (params.containsKey('countInit')) {
dynamic tmpCount = params['countInit'];
if (tmpCount is double) {
_count = tmpCount.toInt();
} else if (tmpCount is String) {
_count = int.parse(tmpCount);
} else if (tmpCount is int) {
_count = tmpCount;
} else {
_count = -2;
}
} else {
_count = 0;
}
print("$_count");
await setLogLabel("start");
final SendPort? send = IsolateNameServer.lookupPortByName(isolateName);
send?.send(null);
}
static Future<void> disposeLocationService() async {
await setLogLabel("end");
final SendPort? send = IsolateNameServer.lookupPortByName(isolateName);
send?.send(null);
}
static Future<void> callback(LocationDto locationDto) async {
await setLogPosition(_count, locationDto);
final SendPort? send = IsolateNameServer.lookupPortByName(isolateName);
send?.send(locationDto);
_count++;
}
static Future<void> setLogLabel(String label) async {
final date = DateTime.now();
await _MyAppState().writeToLogFile(
'------------\n$label: ${formatDateLog(date)}\n------------\n');
}
static Future<void> setLogPosition(int count, LocationDto data) async {
final date = DateTime.now();
await _MyAppState().writeToLogFile(
'$count : ${formatDateLog(date)} --> ${formatLog(data)} --- isMocked: ${data.isMocked}\n');
}
static double dp(double val, int places) {
num mod = pow(10.0, places);
return ((val * mod).round().toDouble() / mod);
}
static String formatDateLog(DateTime date) {
return date.hour.toString() +
":" +
date.minute.toString() +
":" +
date.second.toString();
}
static String formatLog(LocationDto locationDto) {
return dp(locationDto.latitude, 4).toString() +
" " +
dp(locationDto.longitude, 4).toString();
}
#override
void initState() {
super.initState();
if (permissionsGranted) {
setPrerequisites();
} else {
requestPermission();
}
}
void setPrerequisites() async {
finalFile = await _getTempLogFile();
if (IsolateNameServer.lookupPortByName(isolateName) != null) {
IsolateNameServer.removePortNameMapping(isolateName);
}
IsolateNameServer.registerPortWithName(port.sendPort, isolateName);
port.listen(
(dynamic data) async {
await updateUI(data);
},
);
initPlatformState();
setState(() {});
}
Future<void> updateUI(LocationDto data) async {
final log = await readLogFile();
await _updateNotificationText(data);
setState(() {
if (data != null) {
lastLocation = data;
}
logStr = log;
});
}
Future<void> _updateNotificationText(LocationDto data) async {
if (data == null) {
return;
}
await BackgroundLocator.updateNotificationText(
title: "new location received",
msg: "${DateTime.now()}",
bigMsg: "${data.latitude}, ${data.longitude}");
}
Future<void> initPlatformState() async {
print('Initializing...');
await BackgroundLocator.initialize();
logStr = await readLogFile();
print('Initialization done');
final _isRunning = await BackgroundLocator.isServiceRunning();
setState(() {
isRunning = _isRunning;
});
print('Running ${isRunning.toString()}');
}
#override
Widget build(BuildContext context) {
final start = SizedBox(
width: double.maxFinite,
child: ElevatedButton(
child: const Text('Start'),
onPressed: () {
_onStart();
},
),
);
final stop = SizedBox(
width: double.maxFinite,
child: ElevatedButton(
child: Text('Stop'),
onPressed: () {
onStop();
},
),
);
final clear = SizedBox(
width: double.maxFinite,
child: ElevatedButton(
child: Text('Clear Log'),
onPressed: () {
clearLogFile();
setState(() {
logStr = '';
});
},
),
);
String msgStatus = "-";
if (isRunning != null) {
if (isRunning) {
msgStatus = 'Is running';
} else {
msgStatus = 'Is not running';
}
}
final status = Text("Status: $msgStatus");
final log = Text(
logStr,
);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter background Locator'),
),
body: Container(
width: double.maxFinite,
padding: const EdgeInsets.all(22),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[start, stop, clear, status, log],
),
),
),
),
);
}
void onStop() async {
await BackgroundLocator.unRegisterLocationUpdate();
final _isRunning = await BackgroundLocator.isServiceRunning();
setState(() {
isRunning = _isRunning;
});
}
void _onStart() async {
if (await _checkLocationPermission()) {
await _startLocator();
final _isRunning = await BackgroundLocator.isServiceRunning();
setState(() {
isRunning = _isRunning;
lastLocation = null;
});
} else {
// show error
}
}
static Future<void> initCallback(Map<dynamic, dynamic> params) async {
await init(params);
}
static Future<void> disposeCallback() async {
await disposeLocationService();
}
Future<void> locationServicecallback(LocationDto locationDto) async {
await callback(locationDto);
}
static Future<void> notificationCallback() async {
print('***notificationCallback');
}
Future<void> writeToLogFile(String log) async {
await finalFile!.writeAsString(log, mode: FileMode.append);
}
Future<String> readLogFile() async {
return finalFile!.readAsString();
}
static Future<File?> _getTempLogFile() async {
File file =
File('${(await getApplicationDocumentsDirectory()).path}/log.txt');
if (file.existsSync()) {
return file;
} else {
file = await file.create(recursive: true);
}
return file;
}
Future<void> clearLogFile() async {
await finalFile!.writeAsString('');
}
Future<bool> _checkLocationPermission() async {
final access = await LocationPermissions().checkPermissionStatus();
switch (access) {
case PermissionStatus.unknown:
case PermissionStatus.denied:
case PermissionStatus.restricted:
final permission = await LocationPermissions().requestPermissions(
permissionLevel: LocationPermissionLevel.locationAlways,
);
if (permission == PermissionStatus.granted) {
return true;
} else {
return false;
}
case PermissionStatus.granted:
return true;
default:
return false;
}
}
Future<void> _startLocator() async {
Map<String, dynamic> data = {'countInit': 1};
return await BackgroundLocator.registerLocationUpdate(
callback,
initCallback: initCallback,
initDataCallback: data,
disposeCallback: disposeCallback,
iosSettings: const IOSSettings(
accuracy: LocationAccuracy.NAVIGATION, distanceFilter: 0),
autoStop: false,
androidSettings: const AndroidSettings(
accuracy: LocationAccuracy.NAVIGATION,
interval: 5,
distanceFilter: 0,
client: LocationClient.google,
androidNotificationSettings: AndroidNotificationSettings(
notificationChannelName: 'Location tracking',
notificationTitle: 'Start Location Tracking',
notificationMsg: 'Track location in background',
notificationBigMsg:
'Background location is on to keep the app up-tp-date with your location. This is required for main features to work properly when the app is not running.',
notificationIconColor: Colors.grey,
notificationTapCallback: notificationCallback,
),
),
);
}
}
Any help/suggestion would be highly appreciated. Thank you!
The callback function not getting called was an issue I faced inthe version 1.6.12.
I fixed the problem by
forking the background_locator repo on github.
cloning the repo to my computer
opened the location_dto.dart file and went to fromJson function.
added json[Keys.ARG_PROVIDER] ?? '' instead
commited and pushed to my forked repository
in pubspec.yaml, I updated my dependency to point to my forked repository as follows:
background_locator:
git:
url: git#github.com:frankvollebregt/background_locator.git
Please follow these two github issues if you find any problem:
https://github.com/rekabhq/background_locator/issues/320
https://github.com/rekabhq/background_locator/issues/301
background_locator dosen't work on latest flutter sdk versions
for me it's worked when I do this steps
Flutter sdk version should be :3.0.1
In pubspec.yaml file change sdk: ">=2.8.0 <3.0.0"
Don't migrate your code to null safety
in gradle-wrapper.properties change gradle version to gradle-6.5
android/build gradle change ext.kotlin_version to '1.4.31'
android/app/build gradle change compileSdkVersion to 31, minSdkVersion to 19 and targetSdkVersion to 30
This is not a problem with the background locator plugin. When the plugin/library is not registered with Flutter Engine, the 'No implementation' error occurs.
You have been attempting to access the path provider methods from within a Background Isolate. Normally, the path provider plugin will be registered with main isolate.
If you want to use it in your background isolate, you must manually register it with the engine.
Follow the steps below and add these two functions to the Init function in location_service_repositary.dart
if (Platform.isAndroid) PathProviderAndroid.registerWith();
if (Platform.isIOS) PathProviderIOS.registerWith();
Have a good day.
I am creating a dynamic link to navigate me to a specified page, when trying it on emulator it work fine but when trying it on actual device the link only open the app
Creating the dynamic link
Future<void> createDynamicLink(bool short, int lecID, String lecName) async{
setState(() {
_isCreatingLink = true;
});
final DynamicLinkParameters parameters = DynamicLinkParameters(
uriPrefix: 'https://geneapp.page.link',
link: Uri.parse('https://www.geneapp.com/lecture?lecID=$lecID&lecName=$lecName'),
androidParameters: AndroidParameters(packageName: 'com.example.teams',minimumVersion: 0),
dynamicLinkParametersOptions: DynamicLinkParametersOptions(
shortDynamicLinkPathLength: ShortDynamicLinkPathLength.short
),
socialMetaTagParameters: SocialMetaTagParameters(
title: "$lecName",
description: "new"
)
);
print("https://geneapp.page.link/lecture?lecID=$lecID&lecName=$lecName");
Uri url;
if (short) {
final ShortDynamicLink shortLink = await parameters.buildShortLink();
url = shortLink.shortUrl;
} else {
url = await parameters.buildUrl();
}
setState(() {
_linkMessage = url.toString();
_isCreatingLink = false;
});
print(url);
Clipboard.setData(new ClipboardData(text: '$url'));
FocusScope.of(context).requestFocus(new FocusNode());
scaffoldKey.currentState?.removeCurrentSnackBar();
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text("copied",style: TextStyle(fontSize: 16)),
Padding(
padding: EdgeInsets.fromLTRB(10.0,0.0,0.0,0.0),
child: Icon(Icons.check_circle,color: Colors.grey,),
)
],
),
backgroundColor: Colors.green,
duration: Duration(seconds: 3),
));
}
Handling the deep link:
void initDynamicLinks() async{
FirebaseDynamicLinks.instance.onLink(
onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink = dynamicLink?.link;
if (deepLink != null) {
var isLec = deepLink.pathSegments.contains('lecture');
if(isLec){
var lecName = deepLink.queryParameters['lecName'];
var lecID = int.parse(deepLink.queryParameters['lecID']);
print("initDynamicLinks | lecName : $lecName lecID : $lecID");
await _openPDF(lecName, lecID);
}
}
else
print('its null');
}, onError: (OnLinkErrorException e) async {
print('onLinkError');
print(e.message);
});
final PendingDynamicLinkData data = await FirebaseDynamicLinks.instance.getInitialLink();
final Uri deeplink = data?.link;
if(deeplink != null){
var lecName = deeplink.queryParameters['lecName'];
var lecID = int.parse(deeplink.queryParameters['lecID']);
print("initDynamicLinks | lecName : $lecName lecID : $lecID");
await _openPDF(lecName, lecID);
}
}
_openPDF(String lecName, int lecID) async{
final filename = lecName;
String dir = (await getApplicationDocumentsDirectory()).path;
if (await File('$dir/$filename').exists()){
navigatorKey.currentState.pushNamed('/pdf', arguments: '$dir/$filename');
}
else{
//..
//
navigatorKey.currentState.pushNamed('/pdf', arguments: '$dir/$filename');
}
}
in my main build function I am setting initialRoute to a splash screen,
then in my splash screen initstate I am calling the initDynamicLinks():
There can be various reasons for app not launching, the android device your using, the browser used to launch the link (if a link is copy pasted in chrome they do not work), DynamicLinks setup.
You can try few things
encode your lecName variable in the Long URL.
Send the dynamic-short link over message and try to click and launch the app.
Can you please tell me how to Send and fetch the arguments using the flutter plugin firebase_dynamic_links[https://pub.dev/packages/firebase_dynamic_links#-readme-tab-]?
I want to pass parameters like username and password in the deeplink/dynamic link as follow :
uriPrefix: 'https://test.page.link/appinvite?username=Test&password=123456',
link: Uri.parse('https://test.page.link/appinvite?username=Test&password=123456'),
Is this the correct way to pass the data ?
After that i am using below code to fetch data,
await FirebaseDynamicLinks.instance.getInitialLink();
final Uri deepLink = data?.link;
But, it is providing me the dummy web URL i have added in the firebase console for firebase dynamic links in Deep Link URL
currently i am able to open the app from firebase dynamic link but, unable to fetch custom parameters.
Any help will be appreciated.
Updated Code :
For sending invite :
_generateAndShareDynamicLink() async {
final DynamicLinkParameters parameters = DynamicLinkParameters(
uriPrefix: 'https://test.page.link/groupinvite',
link: Uri.parse('https://test.page.link/groupinvite'),
androidParameters: AndroidParameters(
packageName: 'com.test.flutter_authentication',
minimumVersion: 0,
),
dynamicLinkParametersOptions: DynamicLinkParametersOptions(
shortDynamicLinkPathLength: ShortDynamicLinkPathLength.unguessable,
),
);
Uri url = await parameters.buildUrl();
shareURL(Uri.https(url.authority, url.path, {"username": "Test"}));
}
For fetching data inside initState() :
FirebaseDynamicLinks.instance.onLink(
onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink = dynamicLink?.link;
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("deepLink2 : ${deepLink}",)));
if (deepLink != null) {
Map sharedListId = deepLink.queryParameters;
print("sharedListId : ${sharedListId}");
String username=sharedListId["username"];
print("username : ${username}");
Navigator.pushNamed(context, deepLink.path);
}
}, onError: (OnLinkErrorException e) async {
print('onLinkError');
print(e.message);
});
Still retrieved data is null.
Can anybody help ?
The best way to use dynamic links are,
import 'package:firebase_dynamic_links/firebase_dynamic_links.dart';
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
#override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
#override
void initState() {
super.initState();
fetchLinkData();
}
void fetchLinkData() async {
// FirebaseDynamicLinks.getInitialLInk does a call to firebase to get us the real link because we have shortened it.
var link = await FirebaseDynamicLinks.instance.getInitialLink();
// This link may exist if the app was opened fresh so we'll want to handle it the same way onLink will.
handleLinkData(link);
// This will handle incoming links if the application is already opened
FirebaseDynamicLinks.instance.onLink(onSuccess: (PendingDynamicLinkData dynamicLink) async {
handleLinkData(dynamicLink);
});
}
void handleLinkData(PendingDynamicLinkData data) {
final Uri uri = data?.link;
if(uri != null) {
final queryParams = uri.queryParameters;
if(queryParams.length > 0) {
String userName = queryParams["username"];
// verify the username is parsed correctly
print("My users username is: $userName");
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sample"),
),
body: Center(
child: Text("Test"),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
var dynamicLink = await createDynamicLink(userName: "Test");
// dynamicLink has been generated. share it with others to use it accordingly.
print("Dynamic Link: $dynamicLink");
},
child: Icon(
Icons.add,
color: Colors.white,
),
),
);
}
Future<Uri> createDynamicLink({#required String userName}) async {
final DynamicLinkParameters parameters = DynamicLinkParameters(
// This should match firebase but without the username query param
uriPrefix: 'https://test.page.link',
// This can be whatever you want for the uri, https://yourapp.com/groupinvite?username=$userName
link: Uri.parse('https://test.page.link/groupinvite?username=$userName'),
androidParameters: AndroidParameters(
packageName: 'com.test.demo',
minimumVersion: 1,
),
iosParameters: IosParameters(
bundleId: 'com.test.demo',
minimumVersion: '1',
appStoreId: '',
),
);
final link = await parameters.buildUrl();
final ShortDynamicLink shortenedLink = await DynamicLinkParameters.shortenUrl(
link,
DynamicLinkParametersOptions(shortDynamicLinkPathLength: ShortDynamicLinkPathLength.unguessable),
);
return shortenedLink.shortUrl;
}
}
You're done.
This worked for me
The sending side:
Future<String> generateLink() async {
final DynamicLinkParameters parameters = DynamicLinkParameters(
uriPrefix: 'https://<your-domain-name>.page.link',
link: Uri.parse(
'https://<your-domain-name>.page.link/<your-route>/?id=acb&name=me'), // <- your paramaters
dynamicLinkParametersOptions: DynamicLinkParametersOptions(
shortDynamicLinkPathLength: ShortDynamicLinkPathLength.unguessable),
androidParameters: AndroidParameters(
packageName: '<package-name>',
minimumVersion: 0,
),
socialMetaTagParameters: SocialMetaTagParameters(
title: "click the link",
),
);
final Uri dynamicUrl = await parameters.buildUrl();
final ShortDynamicLink shortenedLink =
await DynamicLinkParameters.shortenUrl(
dynamicUrl,
DynamicLinkParametersOptions(
shortDynamicLinkPathLength: ShortDynamicLinkPathLength.unguessable),
);
final Uri shortUrl = shortenedLink.shortUrl;
return "https://<your-domain-name>.page.link" + shortUrl.path;
}
The receiving side:
FirebaseDynamicLinks.instance.onLink(
onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink = dynamicLink?.link;
if (deepLink != null) {
print(deepLink.queryParameters['id']); // <- prints 'abc'
}
}, onError: (OnLinkErrorException e) async {
print('onLinkError');
print(e.message);
}
);
i got an error when i press the login with google button ,
Exception has occurred.
PlatformException (PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 7: , null))
i already try this step >https://console.developers.google.com/apis/credentials/consent
and also already try to change my gradle and etc
this is my auth.dart code
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:rxdart/rxdart.dart';
class AuthService {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
final Firestore _db = Firestore.instance;
Observable<FirebaseUser> user; // firebase user
Observable<Map<String, dynamic>> profile; // custom user data in Firestore
AuthService() {
user = Observable(_auth.onAuthStateChanged);
profile = user.switchMap((FirebaseUser u) {
if (u != null) {
return _db
.collection('users')
.document(u.uid)
.snapshots()
.map((snap) => snap.data);
} else {
return Observable.just({});
}
});
}
Future<FirebaseUser> googleSignIn() async {
GoogleSignInAccount googleUser = await _googleSignIn.signIn();
GoogleSignInAuthentication googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
final AuthResult authResult = await _auth.signInWithCredential(credential);
FirebaseUser user = authResult.user;
print("signed in " + user.displayName);
return user;
}
void signOut() {
_auth.signOut();
}
}
final AuthService authService = AuthService();
and this is my sign in button code
Widget button() {
return RaisedButton(
elevation: 0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30.0)),
onPressed: () => authService.googleSignIn().whenComplete(() {
Navigator.of(context).pushNamed(HOME_PAGE);
}),
textColor: Colors.white,
padding: EdgeInsets.all(0.0),
child: Container(
alignment: Alignment.center,
width: _large ? _width / 4 : (_medium ? _width / 3.75 : _width / 3.5),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
gradient: LinearGradient(
colors: <Color>[Colors.orange[200], Colors.pinkAccent],
),
),
padding: const EdgeInsets.all(12.0),
child: Text('SIGN IN',
style: TextStyle(fontSize: _large ? 14 : (_medium ? 12 : 10))),
),
);
}
i expect after login i can go to HOME_PAGE but it return error message,
Exception has occurred.
PlatformException (PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 7: , null))
This issue usually comes when the device has network connectivity issue.
Happy Learning!
I tried to use the image path to upload images, before my application was fine. when I try to add import 'package: path / path.dart'; and basename (image.path) for the purpose of uploading my image, I get a new error in my dialog alert. more details in context: context. This is my code:
import 'package:path/path.dart';
Future uploadFile() async {
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
final userId = user.uid;
_imageList.forEach((_image) {
final StorageReference firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('category')
.child('food')
.child('images')
.child(username)
.child(basename(_image.path));
final StorageUploadTask task = firebaseStorageRef.putFile(_image);
return task;
});
}
and following code where I get an error:
Future<void> alertSuccess() async {
return showDialog<void>(
/*this error*/
context: context,
/*------------*/
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Success'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text(
'You success save data.'),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.pop(context);
Navigator.pushReplacement(
context,
new MaterialPageRoute(
builder: (context) => PublicService()));
},
),
],
);
},
);
}
path.dart overwrites the global Context variable of the framework.
:-(
So until the path-package developers fix this, the solution from Günter Zöchbauer in the comments is valid.
Use an alias for the package and access it through the alias.
If you have, like me, other variables called "path", you need to rename them, so e.g.:
import 'package:path/path.dart' as path;
then e.g. use
final imgPath = path.join(
(await _localPath),
'${DateTime.now()}.png',
);
instead of
final path = join(
(await _localPath),
'${DateTime.now()}.png',
);
Every answer on above is right .I also want to answer for details on this question.I faced same issue and all you guys help me .thanks for that.
import 'package:path/path.dart' as path;
Future uploadFile() async {
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
final userId = user.uid;
_imageList.forEach((_image) {
final StorageReference firebaseStorageRef = FirebaseStorage.instance
.ref()
.child('category')
.child('food')
.child('images')
.child(username)
.child(path.basename(_image.path));
final StorageUploadTask task = firebaseStorageRef.putFile(_image);
return task;
});
}
Use following
Future<void> alertSuccess() async { // your code }