I've gat a problem to format the Date of a DayView in the format of Germany. It ist always shown in yyyy-MM-dd, but the format I want tu use is dd.MM.yyyy. I tried a few things, but nothing works I want to.
At first I format the date like this
String datumDesTages = DateFormat.yMd('de_DE').format(DateTime.now());
this works fine, so date is shown as dd.MM.yyyy.
But for the DayTime I need a DateTime, so I try to parse it like shown below:
DateTime datumDesTagesDateTime =
Intl.withLocale('de', () => DateFormat().parse(datumDesTages));
but then I get the error
The following FormatException was thrown building EventSet(dirty, state: _EventSetState#95b2d):
Trying to read . from 12.2.2023 at position 4
the entire code is:
lass _EventSetState extends State<EventSet> {
#override
Widget build(BuildContext context) {
String datumDesTages = DateFormat.yMd('de_DE').format(DateTime.now());
//String datumDesTagesString = datumDesTages.format(DateTime.now());
DateTime datumDesTagesDateTime =
Intl.withLocale('de', () => DateFormat().parse(datumDesTages));
//DateFormat('d.M.y').parse(datumDesTagesString));
return Scaffold(
appBar: AppBar(
title: Text('Termin setzen'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Expanded(
child: Container(
child: DayView(
date: datumDesTagesDateTime,
style: DayViewStyle.fromDate(
date: datumDesTagesDateTime,
headerSize: 20,
),
),
),
),
// EventDetailScreen(),
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(
Icons.add,
color: Colors.blue,
),
backgroundColor: Colors.red[50],
onPressed: () {
Navigator.of(context).pushNamed(EventDetailScreen.routeName);
},
),
);
}
}
I don't know how to solve this problem. Thank you for your help.
kind regards
Patrick
You need to load the appropriate data for your language first.
Take a look at the readme from https://pub.dev/packages/intl
Note that before doing any DateTime formatting for a particular locale, you must load the appropriate data by calling.
import 'package:intl/date_symbol_data_local.dart';
...
initializeDateFormatting('de_DE', null).then(formatDates);
Related
class DetailsScreen extends StatelessWidget {
static String routeName = "/details";
#override
Widget build(BuildContext context) {
final Object? arguments =
ModalRoute.of(context)!.settings.arguments != null;
var product;
return Scaffold(
backgroundColor: Color(0xFFF5F6F9),
appBar:AppBar(
backgroundColor: Colors.transparent,
leading: Padding(
padding: const EdgeInsets.only(left: 20.0,),
child: CircleAvatar(
backgroundColor: kPrimaryColor,
child: IconButton(
icon: Icon(Icons.arrow_back_ios),
color: Colors.white,
onPressed: (){
Navigator.pop(context);
},
),
),
),
leadingWidth: 70.0,
),
**body: Body(product: arguments.product),**
);
}
}
class ProductDetailsArguments {
late final Product product;
ProductDetailsArguments({required this.product});
}
I cant get the product details in the flutter android app and this shows a error in
body: Body(product: arguments.product),
Anyone please help I am stuck in this for a week now. Can't really get a solution ..
i have tried the body: Body(product: arguments?.product), and everything thats in the internet. I am new to flutter and this is far above my knowledge so I dont understand how it works correctly. The far I understand is that it is used to get the product name from the list from the item we touced in that product page.
You can do
final ProductDetailsArguments? arguments =
ModalRoute.of(context)?.settings.arguments as ProductDetailsArguments?;
And use the way you did
Body(product: arguments.product)
But if your Body product doesn't accept nullable data, do a null check and then pass the product
body: arguments?.product!=null ? Body(product: arguments.product) : Text("got null")
I am using a riverpod provider class to handle picking of image from gallery. However, once an image is picked, I get the error: PlatformException(multiple_request, Cancelled by a second request null, null). Not sure where a second request is coming from. More importantly, no image is applied to my placeholder (CircleAvartar) due to this unknown cancellation.
Here are the two dart files in question and thanks for the help.
imageProvider file:
final myImageProvider =
ChangeNotifierProvider<ImageNotifier>((ref) => ImageNotifier());
class ImageNotifier extends ChangeNotifier {
ImageNotifier() : super();
final file = useState<File?>(null);
final imageFile = useState<XFile?>(null);
final imagePicker = ImagePicker();
Future<void> _pickImage(int type) async {
try {
XFile? userImage = await imagePicker.pickImage(
source: type == 1 ? ImageSource.gallery : ImageSource.camera,
imageQuality: 50,
);
imageFile.value = userImage;
// imageFile.value = XFile(userImage!.path);
} catch (e) {
print(e);
}
notifyListeners();
}
void showPicker(context) {
showModalBottomSheet(
backgroundColor: Theme.of(context).primaryColor,
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Wrap(
children: [
ListTile(
leading: const Icon(
Icons.photo_library,
color: Colors.white,
),
title: const Text(
'Photo Gallery',
style: TextStyle(fontSize: 22),
),
onTap: () => _pickImage(1),
),
ListTile(
leading: const Icon(
Icons.photo_camera,
color: Colors.white,
),
title: const Text(
'Camera',
style: TextStyle(fontSize: 22),
),
onTap: () => _pickImage(2),
),
ListTile(
leading: const Icon(
Icons.close,
color: Colors.white,
),
title: const Text(
'Cancel',
style: TextStyle(fontSize: 22),
),
onTap: () {
imageFile.value = null;
Navigator.of(context).pop();
},
),
],
),
);
},
);
notifyListeners();
}
AuthScreen dart file:
Widget build(BuildContext context, WidgetRef ref) {
final _passwordController = useTextEditingController();
final _passwordFocusScope = useFocusNode();
final _emailFocusScope = useFocusNode();
final _phoneFocusScope = useFocusNode();
final _confirmFocusScope = useFocusNode();
final _isVisible = useState<bool>(true);
var _authMode = useState<AuthMode>(AuthMode.login);
final imageProviderState = ref.watch(myImageProvider.notifier);
final deviceSize = MediaQuery.of(context).size;
final authMode = ModalRoute.of(context)?.settings.arguments as String;
switch (authMode) {
case 'login':
_authMode.value = AuthMode.login;
break;
case 'register':
_authMode.value = AuthMode.register;
break;
case 'google':
_authMode.value = AuthMode.google;
break;
case 'guest':
_authMode.value = AuthMode.guest;
break;
}
return Scaffold(
body: Stack(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
const SizedBox(
height: 80,
),
Center(
child: _authMode.value == AuthMode.login
? const Text(
'Access Your Account',
style: TextStyle(
fontSize: 25,
),
)
: Row(
children: [
InkWell(
onTap: () =>
imageProviderState.showPicker(context),
// () => ref
// .read(myImageProvider.notifier)
// .showPicker(context),
child: CircleAvatar(
radius: 50,
backgroundImage:
imageProviderState.imageFile.value !=
null
? FileImage(
// File(ref
// .read(imageProvider.notifier)
// .imageFile
// .value!
// .path),
// )
File(imageProviderState
.imageFile.value!.path),
)
: null,
child: imageProviderState.imageFile.value ==
null
? const Icon(
Icons.camera,
// Icons.add_photo_alternate,
size: 30,
color: Colors.white,
)
: null,
),
),
After testing the code on a real device (iPhone and Android) I was able to select and attach a photo from gallery and camera to my form. The issue is with trying to do this task on a simulator even though one was able to do so once upon a time. Don't even bother anymore until Apple fixes this trouble. My advice is that you debug on a real device to ensure things are working as coded and you can return to the simulator/emulator afterwards. I lost a lot of time trying to make tis work on a simulator to no avail.
I have the latest Flutter 3.3.9 and Xcode 14.1 and this is still a problem. The workaround is very simple though after reading this issue. When using the image_picker, DO NOT pick the first image (with pink flowers):
In addition to my earlier answer and further tweaking with the dev in simulator environment, I just discovered that the uploaded image does show up upon a reload/restart. Weird but works if you must test in simulation mode. Simply restart and the uploaded image will show up. It is still a simulator issue though, IMHO.
It can help to double-click on the image you are selecting from the gallery instead of clicking only once.
For whatever reason, if I clicked only once, it would not show up and the same error as yours appeared.
If I clicked twice there was a short lag, but the image showed up.
Tested on iOS simulator - don't get this issue personally on my Android emulator.
I had this issue picking one of the default album images on my iOS simulator.
I was able to get around this by going to Safari, saving a png to Photos and then selecting that downloaded png in my Flutter app.
Thanks to Marc's post which pointed me in the right direction regarding HEIC support
Hi please have a look at this discussion:
https://github.com/flutter/flutter/issues/70436
on on the image picker package site we can see that it is a well known apple simulator issue. I would say that it should work for you on real devices (or try to test it only with particular pictures from iOS simulator photos)
Make sure ALLOW PHOTO ACCESS permission is set to either Selected Photos or All Photos. In my case, I had denied the permission so there was no error log on the console and the image picker was not opening.
PS I know it's not directly related to the SO's question but might be helpful if someone comes across this.
Don't bother about this issue much. This is just a simulator issue(mostly on iOS). Testing this on a real device is advisable.
I think it because it using 'pickimage' instead of 'pickMultiImage', so u are only allow to pick 1 image at a time, try to make ur 'imageFile' to null first before you pick another image.
I have this snackbar code where I can show a message to the user
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
showSnackBar(String text, Color color) {
final snackBar = new SnackBar(
content: CustomText(
text: text,
color: white,
weight: FontWeight.bold,
size: 17,
),
duration: Duration(seconds: 4),
backgroundColor: color,
);
_scaffoldKey.currentState.showSnackBar(snackBar);
}
and inside my scaffold I added my key as key: _scaffoldKey, And then I can call the snackbar using the code showSnackBar("Some Text", Colors.red) But the problem I have is that I have to add this code in every page/screen that am using
So what I want is to create a separate dart file and add this code then be able to import and use in any page I want. So please how do I do That.
N/B: Please Ignore the CustomText In my code cause that's a model-ish I use
I came up with a simple solution, you can make a static function for snackbar and use it all through the app just by passing a scaffoldkey and the message like following
class MyMessageHandler {
static void showMySnackBar(var _scaffoldKey, String message) {
_scaffoldKey.currentState.showSnackBar(SnackBar(
backgroundColor: Colors.green,
content: Text(message ?? ""),
duration: Duration(seconds: 2),
));
}
}
and then call it with any event triggering widget like following
RaisedButton(
onPressed: () =>
MyMessageHandler.showMySnackBar(_scaffoldKey, "message"),
child: Text("Show my snackbar"),
);
Now you have your custom snackbar, you can modify it according to your design :)
here is snippet extracted from my apps.
step.1: create a dart file called common_dialogs.dart
import 'package:flutter/material.dart';
// ...
theSnackBar(context, String message) {
return SnackBar(
duration: Duration(seconds: 2),
content: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: 260.0,
child: Text(
message,
overflow: TextOverflow.fade,
softWrap: false,
),
),
Icon(Icons.error),
],
),
backgroundColor: Colors.orangeAccent,
);
}
step.2: any widget that needs those widgets, then it must import 'common_dialogs.dart'; first
step.3: now you can call show snack bar like this
_scaffoldKey.currentState
..hideCurrentSnackBar()
..showSnackBar(theSnackBar(context, message));
Here is a clean approach: NOTE: you're going to depend on context
Create my_util.dart and:
extension MyUtils on BuildContext {
void showErrorMessage(String error, {int? duration}) {
ScaffoldMessenger.of(this)
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Row(
children: [
Icon(Icons.warning_rounded, color: Colors.white),
SizedBox(
width: 10,
),
Flexible(
child: Text(
error,
overflow: TextOverflow.clip,
),
),
],
),
dismissDirection: DismissDirection.startToEnd,
behavior: SnackBarBehavior.fixed,
duration: Duration(seconds: duration ?? 2),
),
);
}
}
Import my_util.dart
ElevatedButton(onPressed: () {
context.showErrorMessage('Convert your money to naira to continue');
});
I hope it helps.
I'm trying to create stacks of cards in my Flutter project. Each card contains different data/information and when I try visualize with a dummy data, I have to use a lot of variables which is pretty much repeating variable name for each card. Is there aways to make a reusable card component in flutter so that I can make it clear and simple because when I use real data in the future, I might have more than 2 cards in a group and they will also have different data. Any suggestion will be really appreciated.
class MyConstructor {
MyConstructor({this.jonathan1,this.jonathan2,this.jonathan3});
}
class StackedCardsState extends State<HomePage> {
List<MyConstructor> cards = [
MyConstructor(h1: "Hello", h2: "hello3")
];
/////
Padding(
padding: EdgeInsets.all(15.0),
child: Column(children: [
Text(MyConstructor.hey, style: TextStyle(fontWeight: FontWeight.bold),),
Text(MyConstructor.hey),
Text(MyConstructor.hey, style: TextStyle(color: Colors.red[500]),),
VerticalDivider(color: Colors.blue),
])),
Your problem is first of all rather simple, you are violating the DRY concept (Don't repeat yourself, https://en.wikipedia.org/wiki/Don%27t_repeat_yourself ).
As soon as you start copy pasting code take a moment and think about your code and how you can abstract it into a reusable component.
Another big issue that I think you are lacking is variable naming. It is a very very important part of writing code. Might seem trivial but it will be very hard to understand what a variable named cardOne1 and cardTwo2 actually mean. What is the purpose of that variable? What does it do?
Now with that said I understand your app has something to do with car sales but other than that I'm not really sure what I'm looking at. There for I will have a harder time finding a good variable for this code but here is an example.
So lets break down the contents in the card to a single reusable widget, we can also make a data class (or model) for storing the data that we then give to the widget.
//car_details.dart
class CarDetails {
String title;
String diffNumber;
String diffPercent;
Color colorIndicator;
CarDetails({
this.title,
this.diffNumber,
this.diffPercent,
this.colorIndicator,
});
}
//car_card_details.dart
class CarCardDetails extends StatelessWidget {
final double padding;
final CarDetails carDetails;
CarCardDetails({
this.carDetails,
this.padding = 15,
});
#override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
carDetails.colorIndicator != null
? Container(
color: carDetails.colorIndicator,
height: 60,
width: 2,
)
: Container(),
Padding(
padding: EdgeInsets.all(padding),
child: Column(children: [
Text(carDetails.title),
Text(carDetails.diffNumber),
Text(carDetails.diffPercent),
VerticalDivider(color: Colors.blue),
])),
],
);
}
}
To use this component we make a CarCard Widget that takes a title and a list of CarDetails like so:
// car_card.dart
class CarCard extends StatelessWidget {
final String title;
final List<CarDetails> carDetails;
CarCard({this.title, this.carDetails});
#override
Widget build(BuildContext context) {
List<Widget> detailRow = List();
if (carDetails != null) {
carDetails.forEach((element) {
detailRow.add(CarCardDetails(
top: element.title,
middle: element.diffNumber,
bottom: element.diffPercent,
lineColor: element.colorIndicator,
));
});
}
return Container(
//height: 150, //I would not hardcode the height, let the childrent expand the widget instead
child: SingleChildScrollView(
child: Card(
elevation: 8.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
child: InkWell(
child: Column(children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(children: [
Text(
title,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
Spacer(),
Icon(Icons.favorite)
]),
),
Divider(color: Colors.black),
Row(children: detailRow),
]),
),
),
),
);
}
}
And instead of saving all the variables you had in app we can now make them into a list of CarDetails where each element contains the strings.
// some other widget
...
List<CarDetails> carDetails = [
CarDetails(
title: "2 hrs ago",
diffNumber: "+/ TRACK",
diffPercent: "% to DBJ",
),
CarDetails(
title: "CHEVEROLET",
diffNumber: "-2706",
diffPercent: "42.2%",
colorIndicator: Colors.red,
),
CarDetails(
title: "BUICK",
diffNumber: "+300",
diffPercent: "50%",
colorIndicator: Colors.green,
),
CarDetails(
title: "GMC",
diffNumber: "-712",
diffPercent: "52.1%",
colorIndicator: Colors.black26,
),
];
#override
Widget build(BuildContext context) {
return CarCard(
title: "US Daily Retail Delieveries by Brand",
carDetails: carDetails,
);
}
...
This can of course be abstracted even further with the groups of cards etc, etc. But I hope you get the idea.
This is an example of how you could do it, with that said I do not know what data you are intending to use and how you want to structure it. So consider this a starting point and take it from there. :)
Hope somebody can help - I hit this dead end a few weeks ago and think that I've tried everything within my limited knowledge.
I've set up a database that works OK - that is I can add data on one screen, review the data and edit the data on another screen. Now I want to sum one of the columns (beef) which I've been able to do as proven in the 'debugPrint' to the console. I want to access this variable 'beefTotal' from the 'sumBeef' method and print show this in a text field in the UI. I just can't manage it though. It just returns null.
Thanks in advance for any help.
import 'package:flutter/material.dart';
import 'package:take_note/utils/database_helper.dart';
class Info extends StatefulWidget {
#override
State<StatefulWidget> createState() => _InfoState();
}
DatabaseHelper helper = DatabaseHelper();
var database = DatabaseHelper();
class _InfoState extends State<Info> {
List beefTotal;
#override
Widget build (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Beef Info"),
backgroundColor: Colors.lightBlueAccent,
),
body: Container(
child: Column(
children: <Widget>[
Expanded(
child: Center(
child: RaisedButton(
onPressed: (){
sumBeef();
},
),
),
),
Expanded(
child: Center(
child: Text("Total Beef is: £ $beefTotal", style: TextStyle(
color: Colors.lightBlueAccent,
fontSize: 30.0,
fontWeight: FontWeight.w400
),),
),
),
],
),
)
);
}
void sumBeef () async {
beefTotal = await database.addBeef();
debugPrint("Total beef: $beefTotal");
}
}
The code below is from a class called DatabaseHelper which the method sumBeef() uses
Future<List<Map<String, dynamic>>> addBeef()async{
Database db = await this.database;
var result = await db.rawQuery("SELECT SUM(beef) FROM $table");
return result;
}
```[enter image description here][1]
[1]: https://i.stack.imgur.com/L46Gj.png
Just call
setState({
});
void sumBeef () async {
beefTotal = await database.addBeef();
setState(() {});
debugPrint("Total beef: $beefTotal");
}
and your good! anytime you make a change you have to call setState method to update the ui (rebuild) in flutters case