ImagePicker.platform shows warning - Flutter - flutter

I am using the following code to pick an image from user's gallery.
Future getImageFromGallery(BuildContext context) async {
await ImagePicker.platform()
.pickImage(source: ImageSource.gallery)
.then((image) {
if (image != null) {
_cropImage(image, context);
}
});
}
I am getting the following warning.
The member 'platform' can only be used within 'package:image_picker/image_picker.dart' or a test.
I'm not sure what the warning means. I tried looking it up but couldn't figure out the solution to resolve this warning.

Try below code hope its help to you
Declare File type form dart.io package
File? imagePicked;
Create Function for pick up the image
void gallaryImage() async {
final picker = ImagePicker();
final pickedImage = await picker.pickImage(
source: ImageSource.gallery,
);
final pickedImageFile = File(pickedImage!.path);
setState(() {
imagePicked = pickedImageFile;
});
}
Create your Widget
TextButton(
onPressed: gallaryImage,
child: Text(
'Gallery',
style: TextStyle(
color: Colors.black,
),
),
),

You can just change the code
ImagePicker.platform().pickImage(...)
to
ImagePicker().pickImage(...)
so
Future getImageFromGallery(BuildContext context) async {
await ImagePicker()
.pickImage(source: ImageSource.gallery)
.then((image) {
if (image != null) {
_cropImage(image, context);
}
});
}

Related

How to set a Sub-Collection as DateTime.Now()?

I have an app where users, every day can take photos of their day and then display them in a Carsoule for that day. For instance, if he takes 10 photos today, all of them go to one subcollection and then display them on one page of the carousel. I tried this solution but didn't work out, Really appreciate the help
class Cam extends StatefulWidget {
const Cam({super.key});
#override
State<Cam> createState() => _CamState();
}
class _CamState extends State<Cam> {
File? image;
final db = FirebaseFirestore.instance;
final storageRef = FirebaseStorage.instance;
final ImagePicker _picker = ImagePicker();
Future cam() async {
final image = await _picker.pickImage(source: ImageSource.camera);
if (image == null) return;
final temImage = File(image.path);
final fileName = basename(temImage.path);
final destination = 'files/$fileName';
try {
UploadTask uploadTask = storageRef.ref(destination).putFile(temImage);
String urlRef = await (await uploadTask).ref.getDownloadURL();
final photo = PhotoModel(ImgUrl: urlRef, dateCreation: DateTime.now());
final photoToDb = db
.collection('photos')
.doc()
.collection('${DateTime.now()}')
.withConverter(
fromFirestore: PhotoModel.fromFirestore,
toFirestore: ((PhotoModel photoModel, options) =>
photoModel.toFirestore()),
);
photoToDb.add(photo);
} catch (e) {
print('errro');
}
}
#override
Widget build(BuildContext context) {
return Center(
child: IconButton(
onPressed: () {
cam();
},
icon: Icon(
Icons.camera,
size: 40,
color: Colors.red,
),
),
);
}
}
Since you're addressing the doc with .collection('${DateTime.now()}'), the collection name is based on the timestamp (including the exact time). So that will always be unique.
If you want a single collection per day, you should generate a string with just the date portion of that timestamp. Something like:
.collection(DateFormat('yyyy-MM-dd').format(DateTime.now()))
Also see: How do I format a date with Dart?

Flutter how to handle time based events?

I am having a widget in the flutter which can be dismissed by watching a rewarded video. But I don't want the widget to be completely dismissed. Say for 3 days.
So if the user clicks on the specific widget then the ads will be disabled for 3 days. Is it possible to do? Could someone help me with references or ideas to get this done?
Please help
First, Get shared preferences Package to make local storage to track the Date shared_preferences: ^2.0.5
Make A Local Storage like this -
import 'package:shared_preferences/shared_preferences.dart';
class SetUserLocalStorage {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
void date(String valueOfDate) async {
final SharedPreferences prefs = await _prefs;
prefs.setString(UserStorageKey().valueOfDate, valueOfDate);
}
void clear() async { // For Your Further Operation, If needed
final SharedPreferences prefs = await _prefs;
prefs.clear();
}
}
class GetUserLocalStorage {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<String> date() async {
final SharedPreferences prefs = await _prefs;
return prefs.getString(UserStorageKey().valueOfDate);
}
}
class UserStorageKey {
String get valueOfDate => "valueOfDate";
}
Now, in your page / Screen, Define Variable -
bool _showTheAd = false;
DateTime _now = DateTime.now();
DateTime _date = DateTime.now();
and In InitState, Start Checking the Condition on the base of Time,I am making it in three part for better understanding
#override
void initState() {
super.initState();
_initialPoint();
}
in _initialPoint() -
void _initialPoint() async {
await GetUserLocalStorage().date().then((value) {
setState(() {
_date = DateTime.parse(value);
});
}).then((value) {
_conditionCheck();
});
}
In _conditionCheck -
void _conditionCheck() {
if (_date == null) {
setState(() {
_showTheAd = true;
});
} else {
setState(() {
_now = DateTime.now();
});
if (_now.isAfter(_date)) {
setState(() {
_showTheAd = true;
});
}
}
}
I know that,these are like "dirty code", but I think that will help you understand the scenario.
in body, show the add based on the _showTheAd condition, and use some interceptor / listener of kind to sense when the video is end,I am using an inkwell, and execute the code in onTap(), full scenario -
Container(
child: Column(
children: [
if (_showTheAd)
InkWell(
onTap: () {
setState(
() {
_date = _now.add(
Duration(seconds: 5),
); // to add Date _now.add(Duration(days:3));
},
);
SetUserLocalStorage().date(_date.toIso8601String());
},
child: Center(
child: Container(
height: 120,
width: 120,
color: Colors.red,
child: Text("the ad"),
),
),
)
],
),
),

Maximum Duration of picked video using image picker plugin in Flutter

I'm using image picker plugin to pick videos from gallery in my flutter app. I want to set the maximum duration of the picked video to 30 seconds. The below code doesn't work even after setting the max duration. Is there any way to display an error or automatically trim the first 30secs if users pick a bigger video.
pickVideo(ImageSource src) async {
Navigator.pop(context);
final video = await ImagePicker().getVideo(
source: src,
maxDuration: Duration(seconds: 30),
);
I made a work around for this by throwing an error when a video longer than x seconds is selected. It looks as follows:
Future<void> pickVideo() async {
try {
final picker = ImagePicker();
var pickedFile = await picker.pickVideo(source: ImageSource.gallery, maxDuration: Duration(seconds: maxSeconds));
if (pickedFile == null) {
return;
}
VideoPlayerController testLengthController = new VideoPlayerController.file(File(pickedFile.path));//Your file here
await testLengthController.initialize();
if (testLengthController.value.duration.inSeconds > 60) {
pickedFile = null;
throw('we only allow videos that are shorter than 1 minute!');
} else {
setState(() {
videoFile = XFile(pickedFile.path);
_startVideoPlayer();
});
}
testLengthController.dispose();
} catch (e) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Container(
child: Text(e.toString()),
),
);
});
return;
}
}

Can layout and logic separated in flutter?

I understand presence Bloc and Scoped Model in flutter.
But that isn't separate like a layout file in java's SpringBoot.
You can actually separate layout and logic in flutter. I have an example.
In my LoginForm I have a function
_attemptLogin() {
BlocProvider.of<LoginBloc>(context).add(
LoginButtonPressed(
context: context,
email: _tecEmail.text,
password: _tecPassword.text,
),
);
}
called by
RaisedButton(
color: Colors.blue,
child: const Text(
'Login',
style: TextStyle(
color: Colors.white,
),
),
onPressed: (state is LoginProcessing)
? null
: _attemptLogin,
),
and in my LoginBloc, I have the ff code inside mapEventToState
#override
Stream<LoginState> mapEventToState(LoginEvent event) async* {
if (event is LoginButtonPressed) {
yield LoginProcessing();
await Future.delayed(const Duration(milliseconds: 250));
try {
var loginResponse =
await _attemptLogin(userRepository, event.email, event.password);
/// Get Firebase Token
final firebaseToken =
await Provider.of<FirebaseMessagingProvider>(context).getToken();
if (loginResponse['data'] != null && firebaseToken != null) {
User user =
_setUserFromJsonMap(context, loginResponse['data']['user']);
IdentityToken identityToken = _setIdentityTokenFromJsonMap(
context, loginResponse['data']['token']);
/// Request Firebase Token Update
var jsonCreateUserFirebaseTokenResponse =
await _attemptFirebaseTokenUpdate(context, firebaseToken);
if (jsonCreateUserFirebaseTokenResponse != null) {
authBloc.add(LoggedIn(identityToken: identityToken));
yield LoginInitial();
}
} else {
yield LoginFailure(message: 'Login failed.');
}
} catch (error, stackTrace) {
print(error);
print(stackTrace);
await Future.delayed(const Duration(seconds: 1));
yield LoginFailure(
message: 'Login failed. Please check your internet connection.');
}
}
}
I didn't include all the other functions/classes as I have already deleted several lines of code to make it look readable, since it contains a ton of code already; which is unnecessary for only trying to prove a point that you can actually separate code for your view and logic.

Share url+image+text with Twitter/Facebook/Instagram

Is there any lib/package that will help in both platform iOS and Android to share image+text+url on FB, Twitter And Insta? I have been searing for 4 hours but didn't find any result. https://pub.dev/packages/flutter_share_me
this package is only for android so. If you have any solution for it please guide me.
~ PS : I don't want to use Share package, I have buttons of FB, Insta and Twitter. When user will click on any one of the button then data should be share on any of the social media and I need call back of failure or success.
Edit
package social_share_plugin
https://github.com/romatroskin/social_share_plugin
provide share function and have call back
description page forget to mention twitter already include
full social_share_plugin example code
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:social_share_plugin/social_share_plugin.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
#override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await SocialSharePlugin.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Center(
child: Text('Running on: $_platformVersion\n'),
),
RaisedButton(
child: Text('Share to Instagram'),
onPressed: () async {
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
await SocialSharePlugin.shareToFeedInstagram("image/*", file.path);
},
),
RaisedButton(
child: Text('Share to Facebook'),
onPressed: () async {
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
await SocialSharePlugin.shareToFeedFacebook('test', file.path);
},
),
RaisedButton(
child: Text('Share to Facebook Link'),
onPressed: () async {
String url = 'https://flutter.dev/';
final quote =
'Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.';
final result = await SocialSharePlugin.shareToFeedFacebookLink(
quote: quote,
url: url,
onSuccess: (postId) {
print('FACEBOOK SUCCESS $postId');
return;
},
onCancel: () {
print('FACEBOOK CANCELLED');
return;
},
onError: (error) {
print('FACEBOOK ERROR $error');
return;
},
);
print(result);
},
),
RaisedButton(
child: Text('Share to Twitter'),
onPressed: () async {
String url = 'https://flutter.dev/';
final text =
'Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.';
final result = await SocialSharePlugin.shareToTwitter(
text: text,
url: url,
onSuccess: (_) {
print('TWITTER SUCCESS');
return;
},
onCancel: () {
print('TWITTER CANCELLED');
return;
});
print(result);
},
),
],
),
),
);
}
}
You can use package https://pub.dev/packages/esys_flutter_share
github https://github.com/esysberlin/esys-flutter-share
iOS need special action, you can see IMPORTANT Note for iOS
Share text:
Share.text('my text title', 'This is my text to share with other applications.', 'text/plain');
Share file:
final ByteData bytes = await rootBundle.load('assets/image1.png');
await Share.file('esys image', 'esys.png', bytes.buffer.asUint8List(), 'image/png', text: 'My optional text.');
Share files:
final ByteData bytes1 = await rootBundle.load('assets/image1.png');
final ByteData bytes2 = await rootBundle.load('assets/image2.png');
final ByteData bytes3 = await rootBundle.load('assets/addresses.csv');
await Share.files(
'esys images',
{
'esys.png': bytes1.buffer.asUint8List(),
'bluedan.png': bytes2.buffer.asUint8List(),
'addresses.csv': bytes3.buffer.asUint8List(),
},
'*/*',
text: 'My optional text.');
Share file from url:
var request = await HttpClient().getUrl(Uri.parse('https://shop.esys.eu/media/image/6f/8f/af/amlog_transport-berwachung.jpg'));
var response = await request.close();
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
await Share.file('ESYS AMLOG', 'amlog.jpg', bytes, 'image/jpg');
official demo
Allowing users to choose their social platform within your apps UI is not really viable anymore. Better to allow the user to enable their platforms in the OS and then let the Share API or Activity view in iOS do the rest. Just provide the correctly structured URLs with tags etc. This is a great resource: https://github.com/bradvin/social-share-urls