FirebaseImageLoader doesn't download image - firebase-storage

I'm trying to download image from storage inside of ViewHolder, but it doesn't work:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageReference = storage.getReference();
StorageReference imgRef = storageReference.child("11325404_436219506581300_875224883_a.jpg");
Glide.with(context)
.using(new FirebaseImageLoader())
.load(imgRef)
.into(imageView);
When I use uri instead of FirebaseImageLoader everything works fine:
Glide.with(context)
.load(uri)
.centerCrop()
.into(imageView)
What could be a reason for that?
Update: I've tried to add this code and it shows me right links to images in storage
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.v(TAG, String.valueOf(uri));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});

Related

Flutter - Firebase Dynamic Link not Working while app is in kill mode

I have integrated Firebase Dynamic link in my Flutter application to open and navigate application users to specific screen in app.
For that first of all I have added below plugin in pubspec.yaml file:
firebase_dynamic_links: ^5.0.5
Then, I have created a separate class to handle related stuffs as below:
class DynamicLinkService {
late BuildContext context;
FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;
Future<void> initDynamicLinks(BuildContext context) async {
this.context = context;
dynamicLinks.onLink.listen((dynamicLinkData) {
var dynamicLink=dynamicLinkData.link.toString();
if (dynamicLink.isNotEmpty &&
dynamicLink.startsWith(ApiConstants.baseUrl) &&
dynamicLink.contains("?")) {
//Getting data here and navigating...
...
...
...
}
}).onError((error) {
print("This is error >>> "+error.message);
});
}
}
Now, I am initialising Deep-link as below in my home_screen:
final DynamicLinkService _dynamicLinkService = DynamicLinkService();
and then calling below method in initState()
#override
void initState() {
SchedulerBinding.instance.addPostFrameCallback((_) async {
await _dynamicLinkService.initDynamicLinks(context);
});
}
This is working like a charm! when my application is in recent mode or in background mode.
But the issue is when the application is closed/Killed, clicking on dynamic link just open the app but could not navigate.
What might be the issue? Thanks in advance.
Let me answer my own question, It might be useful for someone!
So, In above code I forgot to add code to handle dynamic link while the app is in closed/kill mode.
We need to add this code separately:
//this is when the app is in closed/kill mode
final PendingDynamicLinkData? initialLink = await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
handleDynamicLink(initialLink);
}
So, final code looks like as below:
//this is when the app is in closed/kill mode
final PendingDynamicLinkData? initialLink = await FirebaseDynamicLinks.instance.getInitialLink();
if (initialLink != null) {
handleDynamicLink(initialLink);
}
//this is when the app is in recent/background mode
dynamicLinks.onLink.listen((dynamicLinkData) {
handleDynamicLink(dynamicLinkData);
}).onError((error) {
print("This is error >>> "+error.message);
});
Its working like a charm now! That's All.

The static method can't be acessed through an instance. Try using the class 'services' to acess the method

Hi can anyone help me with this problem I'm facing when calling API's in flutter, this is the code for fetching the data
class _InvestPageState extends State<InvestPage> {
late Future<Markets> _Markets;
#override
void initState() {
_Markets = Services().getMarkets(); //error here
super.initState();
}
This is the code in my API manager file
import 'package:gem_portal_new/Login/newsinfo.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class Services {
static const String url = 'https://ctrade.co.zw/mobileapi/MarketWatch';
static Future<List<Markets>> getMarkets() async {
try {
final response = await http.get(Uri.parse(url));
if (200 == response.statusCode) {
final List<Markets> markets = marketsFromJson(response.body);
return markets;
} else {
return <Markets>[];
}
} catch (e) {
return <Markets>[];
}
}
}
You are trying to access a static method using a object instance,
Change this
_Markets = Services().getMarkets();
to
_Markets = Services.getMarkets();
Try this
class _InvestPageState extends State<InvestPage> {
late Future<Markets> _Markets;
#override
void initState() {
Services().getMarkets().then((value) {
_Markets = value;
});
super.initState();
}
}
You are used future return type, so you cannot be access through instance.

can't initialized Shared Pref using GetIt in flutter

I want to implement a session management system using Shared Preference in my flutter app. For Dependency injection, I use GetIt library. But when I run the app, it says 'flutter: Error while creating Session'
'The following ArgumentError was thrown building Builder(dirty):
Invalid argument (Object of type SharedPreferences is not registered inside GetIt.
Did you forget to pass an instance name?
(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;)): SharedPreferences'
Session.dart
abstract class Session {
void storeLoginInfo(String accessToken);
bool isUserLoggedIn();
String getAccessToken();
void deleteLoginInfo();
}
SessionImpl.dart
class SessionImpl extends Session {
SharedPreferences sharedPref;
SessionImpl(SharedPreferences sharedPref) {
this.sharedPref = sharedPref;
}
#override
void storeLoginInfo(String accessToken) {
sharedPref.setBool('login_status', true);
sharedPref.setString('access_token', accessToken);
}
#override
bool isUserLoggedIn() {
final isLoggedIn = sharedPref.getBool('login_status') ?? false;
return isLoggedIn;
}
#override
String getAccessToken() {
return sharedPref.getString('access_token') ?? "";
}
#override
void deleteLoginInfo() {
if (sharedPref.containsKey('login_status')) sharedPref.remove('login_status');
if (sharedPref.containsKey('access_token')) sharedPref.remove('access_token');
}
}
ServiceLocator.dart
final serviceLocator = GetIt.instance;
Future<void> initDependencies() async {
_initSharedPref();
_initSession();
}
Future<void> _initSharedPref() async {
SharedPreferences sharedPref = await SharedPreferences.getInstance();
serviceLocator.registerSingleton<SharedPreferences>(sharedPref);
}
void _initSession() {
serviceLocator.registerLazySingleton<Session>(() => SessionImpl(serviceLocator()));
}
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown],
);
await initDependencies();
runApp(MyApp());
}
It seems the only thing you are missing is to await the _initSharedPref function in the initDependencies function. Like follows:
Future<void> initDependencies() async {
await _initSharedPref();
_initSession();
}
After that the object should be registering without problems.

Flutter user data taking up a lot of space

My flutter app user data takes up a lot of space. I'm currently using the following code to save the user data
class FileUtil {
static Future<String> get getFilePath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
static Future<File> get getFile async {
final path = await getFilePath;
return File('$path/user.txt');
}
static Future<File> saveToFile(String data) async {
final file = await getFile;
return file.writeAsString(data);
}
static Future readFromFile() async {
try {
final file = await getFile;
String fileContents = await file.readAsString();
log(fileContents);
return json.decode(fileContents);
} catch (e) {
return "";
}
}
String formatData() {
String formattedString;
Map x = {};
x['a'] = a;
// other variables
formattedString = json.encode(x);
return formattedString;
}
void saveData() async {
try {
await saveToFile(formatData());
//print('DATA SAVED');
} catch (e) {
//print('Could not save data due to: $e');
}
}
}
Whenever the user interacts with something in the app that needs to be saved, I run saveData(). This happens quite often in my app. However, after using the app for a while, the user data can jump to a few hundred MB. I've used a JSON calculator to estimate the space of the formatData() output string and it's much less than 1MB. What should I do to minimise user data?

Platform specific code error: MissingPluginException

I want to send an Notification in Flutter, so I set up my platform specific code (only Android) but I get the following error back:
Unhandled Exception: MissingPluginException(No implementation found for method send_notification on channel reminderChannel)
I already cleaned the project but still not working.
Future to invoke method:
const platform = const MethodChannel("reminderChannel");
Future<void> invokeMethod() async {
try {
//FIXME Missing plugin
int testValue = await platform.invokeMethod("send_notification");
} on PlatformException catch (e) {}
}
invokeMethod();
mainActivity:
private static final String notificationChannel = "reminderChannel";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), notificationChannel).setMethodCallHandler(
new MethodCallHandler() {
#Override
public void onMethodCall(MethodCall methodCall, Result result) {
if (methodCall.method.equals("send_notification")) {
System.out.print("Android Method called");
result.success(5);
} else {
result.notImplemented();
}
}
}
);
}
I want that the testValue variable in invokeMethod equals 5.
Thanks for helping.
I suspect your channel is deallocated at the end of the method.
So keep a reference to the MethodChannel in your acivity:
private static final String notificationChannel = "reminderChannel";
private MethodChannel mainChannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
reminderChannel = new MethodChannel(getFlutterView(), notificationChannel)
reminderChannel.setMethodCallHandler(
new MethodCallHandler() {
#Override
public void onMethodCall(MethodCall methodCall, Result result) {
if (methodCall.method.equals("send_notification")) {
System.out.print("Android Method called");
result.success(5);
} else {
result.notImplemented();
}
}
}
);
}