Flutter passing list of strings in CupertinoPicker widget using loops - flutter

I was trying to pass a list inside CupertinoPicker using loops but I couldn't figure it
this image contains the function I was trying to build
const List<String> currenciesList = [
'AUD',
'BRL',
'CAD',
'CNY',
'EUR',
'GBP',
'HKD',
'IDR',
'ILS',
'INR',
'JPY',
'MXN',
'NOK',
];
Container(
height: 150.0,
alignment: Alignment.center,
padding: EdgeInsets.only(bottom: 30.0),
color: Colors.lightBlue,
child:CupertinoPicker(
backgroundColor: Colors.lightBlue,
itemExtent: 32.0,
onSelectedItemChanged: (selectedIndex){
print(selectedIndex);
}, children:[
Text('USD',style: whiteColor ),
Text('EUR' , style: whiteColor),
Text('GDP', style:whiteColor),
]
),
),

As of Dart 2.3 you can use Collection For:
CupertinoPicker(
children:[
for (String name in currenciesList) Text( name ,style: whiteColor ),
]
)

You should create a Func to get all value in your list.
List<Widget> getPickerItems() {
List<Text> itemsCurrency = [];
for (var currency in currenciesList) {
itemsCurrency.add(Text(currency));
}
return itemsCurrency;
}
and add it in to children of CupertinoPicker:
CupertinoPicker(
children: getPickerItems(),
)

Related

flutter/getx how to initialize nullable obejct observable

let's say I have a controller like this:
class ProfileController extends GetxController {
Rx<UserFacebookInfo?> facebookInfo = null.obs;
void facebookSync() async {
//
// logic to get user info from facebook
//
facebookInfo.value = UserFacebookInfo.fromFacebookApi(userData);
// facebookInfo = UserFacebookInfo.fromFacebookApi(userData).obs; <=== also tried this
update();
}
}
}
and in widget I have something like this:
Widget buildFacebook() => Padding(
padding: const EdgeInsets.only(top: 30.0, right: 20.0, left: 20.0, bottom: 10.0),
child: Obx(() => (_profileController.facebookInfo.value == null) ? Column(
children: [
IconButton(
icon : const Icon(Icons.facebook_outlined, size: 40.0),
onPressed: () => _profileController.facebookSync()
),
const Text(
'Facebook',
style: TextStyle(color: Colors.white),
)
],
) :
Column(
children: [
UserProfileAvatar(
avatarUrl: _profileController.facebookInfo.value!.facebookAvatar,
radius: 40,
),
Text(
_profileController.facebookInfo.value!.name,
style: const TextStyle(color: Colors.white),
)
],
)
));
and because initial value nullable, it's not working and not changing widget on a fly, but only if I update it from android studio. What is the correct way to initialize it??? I had similar case with nullable string observable so I was able to initialize it lie String string (null as String?).obs` Thanks for any advice
You can initialize nullable observables by using Rxn<Type>().
Therefore use this:
final facebookInfo= Rxn<UserFacebookInfo>();

How to randomly position widgets in a layout

Lets say I want to randomly position the widgets in a specific layout, like in the image attached below, how could I achieve it?
I was thinking of using a wrap widget, but that did not quit work, because it is not randomizing the children in a line. My code until now
return Wrap(
spacing: 30,
children: [
buildprofile(),
buildprofile(),
buildprofile(),
buildprofile(),
],
);
buildprofile() {
return Column(
children: [
CircleAvatar(
radius: 64,
backgroundColor: Colors.pink,
child: (CircleAvatar(
radius: 62,
backgroundImage: NetworkImage(profilepic),
)),
),
SizedBox(
height: 10,
),
Text(
"Sivaram",
style: mystyle(16, Colors.black, FontWeight.w700),
)
],
);
}
You could use flutter_staggered_grid_view
StaggeredGridView.count(
crossAxisCount: 4,
children: List.generate(
3,
(index) => Center(
child: CircleAvatar(
radius: 64,
backgroundColor: Colors.pink,
),
)),
staggeredTiles: [
StaggeredTile.count(2, 2), // takes up 2 rows and 2 columns space
StaggeredTile.count(2, 1), // takes up 2 rows and 1 column
StaggeredTile.count(1, 2), // takes up 1 row and 2 column space
], // scatter them randomly
);
You can create class Person, and store profile name and image,
class Person {
String name;
String imageUrl;
}
and in your code can store all your persons in array
List<Person> persons = [Person(), Person(),....]
Wrap(
spacing: 30,
children: _children
);
List<Widget> _children {
List<Widget> _widgets = List<Widget>();
List<Persons> _randomList = persons.shuffle();
_randomList.forEach((person) {
_widgets.add(_buildProfile(person))
});
return _widgets;
}

Searchable SliverGrid Rendering Wrong Items

I have a SliverGrid. I have a search field. In my search field onChange event I have a function that searches my local sqlite db based on the keyword entered by the user returns the results and reassigns to a variable and calls notifyListeners(). Now my problem is for some weird reason whenever I search for an item the wrong item is rendered.
I checked the results from my functions by iterating over the list and logging the title and the overall count as well and the results were correct however my view always rendered the wrong items. Not sure how this is possible.
I also noticed something strange, whenever it rendered the wrong item and I went back to my code and hit save, triggering live reload, when I switched back to my emulator it now displayed the right item.
I have tried the release build on an actual phone and it's the same behaviour. Another weird thing is sometimes certain items will duplicate and show twice in my list while the user is typing.
This is my function that searches my sqlite db:
Future<List<Book>> searchBookshelf(String keyword) async {
try {
Database db = await _storageService.database;
final List<Map<String, dynamic>> rows = await db
.rawQuery("SELECT * FROM bookshelf WHERE title LIKE '%$keyword%'; ");
return rows.map((i) => Book.fromJson(i)).toList();
} catch (e) {
print(e);
return null;
}
}
This is my function that calls the above function from my viewmodel:
Future<void> getBooksByKeyword(String keyword) async {
books = await _bookService.searchBookshelf(keyword);
notifyListeners();
}
This is my actual view where i have the SliverGrid:
class BooksView extends ViewModelBuilderWidget<BooksViewModel> {
#override
bool get reactive => true;
#override
bool get createNewModelOnInsert => true;
#override
bool get disposeViewModel => true;
#override
void onViewModelReady(BooksViewModel vm) {
vm.initialise();
super.onViewModelReady(vm);
}
#override
Widget builder(BuildContext context, vm, Widget child) {
var size = MediaQuery.of(context).size;
final double itemHeight = (size.height) / 4.3;
final double itemWidth = size.width / 3;
var heading = Container(
margin: EdgeInsets.only(top: 35),
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Align(
alignment: Alignment.centerLeft,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Books',
textAlign: TextAlign.left,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.w900),
),
Text(
'Lorem ipsum dolor sit amet.',
textAlign: TextAlign.left,
style: TextStyle(fontSize: 14),
),
],
),
),
);
var searchField = Container(
margin: EdgeInsets.only(top: 5, left: 15, bottom: 15, right: 15),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(15)),
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 1.0,
spreadRadius: 0.0,
offset: Offset(2.0, 1.0), // shadow direction: bottom right
),
],
),
child: TextFormField(
decoration: InputDecoration(
border: InputBorder.none,
prefixIcon: Icon(
FlutterIcons.search_faw,
size: 18,
),
suffixIcon: Icon(
FlutterIcons.filter_fou,
size: 18,
),
hintText: 'Search...',
),
onChanged: (keyword) async {
await vm.getBooksByKeyword(keyword);
},
onFieldSubmitted: (keyword) async {},
),
);
return Scaffold(
body: SafeArea(
child: Container(
padding: EdgeInsets.only(left: 1, right: 1),
child: LiquidPullToRefresh(
color: Colors.amber,
key: vm.refreshIndicatorKey, // key if you want to add
onRefresh: vm.refresh,
showChildOpacityTransition: true,
child: CustomScrollView(
slivers: [
SliverToBoxAdapter(
child: Column(
children: [
heading,
searchField,
],
),
),
SliverToBoxAdapter(
child: SpaceY(15),
),
SliverToBoxAdapter(
child: vm.books.length == 0
? Column(
children: [
Image.asset(
Images.manReading,
width: 250,
height: 250,
fit: BoxFit.contain,
),
Text('No books in your bookshelf,'),
Text('Grab a book from our bookstore.')
],
)
: SizedBox(),
),
SliverPadding(
padding: EdgeInsets.only(bottom: 35),
sliver: SliverGrid.count(
childAspectRatio: (itemWidth / itemHeight),
mainAxisSpacing: 20.0,
crossAxisCount: 3,
children: vm.books
.map((book) => BookTile(book: book))
.toList(),
),
)
],
),
))));
}
#override
BooksViewModel viewModelBuilder(BuildContext context) =>
BooksViewModel();
}
Now the reason I am even using SliverGrid in the first place is because I have a search field and a title above the grid and I want all items to scroll along with the page, I didn't want just the list to be scrollable.
I believe this odd behavior can be attributed to you calling vm.getBooksByKeyword() in onChanged. As this is an async method, there is no guarantee that the last result returned will be the result for the final text in the TextFormField. The reason you see the correct results after a live reload is because the method is being called again with the full text currently in the TextFormField.
The quickest way to verify this is to move the function call to onFieldSubmitted or onEditingComplete and see if it behaves correctly.
If you require calling the function with every change to the text, you will need to add a listener to the controller and be sure to only make the call after input has stopped for a specified amount of time, using a Timer, like so:
final _controller = TextEditingController();
Timer _timer;
...
_controller.addListener(() {
_timer?.cancel();
if(_controller.text.isNotEmpty) {
// only call the search method if keyword text does not change for 300 ms
_timer = Timer(Duration(milliseconds: 300),
() => vm.getBooksByKeyword(_controller.text));
}
});
...
#override
void dispose() {
// DON'T FORGET TO DISPOSE OF THE TextEditingController
_controller.dispose();
super.dispose();
}
...
TextFormField(
controller: controller,
...
);
So I found the problem and the solution:
The widget tree is remembering the list items place and providing the
same viewmodel as it had originally. Not only that it also takes every
item that goes into index 0 and provides it with the same data that
was enclosed on the Construction of the object.
Taken from here.
So basically the solution was to add and set a key property for each list item generated:
SliverPadding(
padding: EdgeInsets.only(bottom: 35),
sliver: SliverGrid(
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: (itemWidth / itemHeight),
mainAxisSpacing: 20.0,
),
delegate: SliverChildListDelegate(vm.books
.map((book) => BookTile(
key: Key(book.id.toString()), book: book))
.toList()),
),
)
And also here:
const BookTile({Key key, this.book}) : super(key: key, reactive: false);
My search works perfectly now. :)

AssetsAudioPlayer only plays the audio at last index

I'm using a listview to display images and text in my flutter app. I've stored the asset path and text in a Json file and I convert it to a list. Getting the image asset path and displaying the correct one seems to work with no issues but thats not the case in playing the audio files from their assets.
I'm using this package import 'package:assets_audio_player/assets_audio_player.dart';
declaration final AssetsAudioPlayer playAudio = AssetsAudioPlayer();
and this is main widget
#override
Widget build(BuildContext context) {
Widget _buildRow(int idx) {
for (var translations in widget.category.translations) {
_wordList = widget.category.translations[idx];
return Container(
height: 88.0,
child: Card(
child: ListTile(
onTap: () {
playAudio.open(
Audio(_wordList.audio),
);
// player.play(_wordList.audio);
log(_wordList.audio, name: 'my.other.category');
},
onLongPress: () {},
leading: SizedBox(
width: 50.0,
height: 88.0,
child: Image(
image: AssetImage(_wordList.emoji),
fit: BoxFit.contain,
),
),
title: Text(
_wordList.akan,
style: TextStyle(fontSize: 18),
),
subtitle: Text(
_wordList.english,
style: TextStyle(fontSize: 18, color: Colors.black),
),
trailing: const Icon(Icons.play_arrow, size: 28),
),
),
);
}
}
Since the image assets in the json file have no issues I don't get why the audio does
I've stored them like this,
{
"english": "mother",
"akan": "ɛna",
"emoji": "assets/icons/family_mother.png",
"audio": "assets/audio/family_mother.mp3"
},
Solved it by generating a new listtile widget through iteration and then putting it into a listview

Image not showing in Flutter on pdf creation

I have a problem where image from asset is not rendered in the screen when generating a pdf.
I have pdf and printing package install. The printing package is used to load image from my image folder.
Here is my code
final pdf = pw.Document(deflate: zlib.encode);
writeOnPdf() async {
const imageProvider = const AssetImage('images/sig1.png');
final PdfImage sig1 = await pdfImageFromImageProvider(pdf: pdf.document, image: imageProvider);
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return pw.Column(
children: [
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
children: [
pw.Text("Dexandra Inventory", style: pw.TextStyle(fontSize: 28.0)),
pw.Text("RECEIPT#1", style: pw.TextStyle(fontSize: 28.0))
]
),
pw.SizedBox(
height: 30.0
),
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.start,
children: [
pw.Text("Luqman +60186661360", style: pw.TextStyle(fontSize: 18.0)),
]
),
pw.SizedBox(
height: 30.0
),
pw.Header(
level: 0,
child: pw.Text("1 Item (Qty:2)", style: pw.TextStyle(fontSize: 22.0))
),
pw.SizedBox(
height: 30.0
),
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceEvenly,
children: [
pw.Text("2x", style: pw.TextStyle(fontSize: 16.0)),
pw.Text("Air Feshener", style: pw.TextStyle(fontSize: 16.0)),
pw.Text("RM 10.00", style: pw.TextStyle(fontSize: 16.0, color: PdfColors.grey)),
pw.SizedBox(width: 40.0),
pw.Text("RM 20.00", style: pw.TextStyle(fontSize: 16.0, fontBold: pw.Font.courierBold())),
]
),
pw.SizedBox(
height: 40.0
),
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.end,
children: [
pw.Column(
children: [
pw.Text("Total: RM 20.00", style: pw.TextStyle(fontSize: 20.0, fontBold: pw.Font.courierBold())),
pw.SizedBox(
height: 15.0
),
pw.Text("Cash: RM 20.00", style: pw.TextStyle(fontSize: 16.0)),
]
),
]
),
pw.Header(
level: 0,
child: pw.Text("")
),
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.center,
children: [
pw.Text("March 30, 2020 4:41 PM", style: pw.TextStyle(fontSize: 16.0, color: PdfColors.grey)),
]
),
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceAround,
children: [
pw.Image(sig1),
]
)
]
); // Center
}));
}
Everything works fine until the last widget, which is the Image. It is not displayed in the PDF page.
pubspec.yml
assets:
- images/
And this is what appears in the terminal, when I click a button to generate pdf.
Not sure if it has anything related to the image not being rendered.
I/flutter (13171): Helvetica has no Unicode support see https://github.com/DavBfr/dart_pdf/wiki/Fonts-Management
E/AccessibilityBridge(13171): VirtualView node must not be the root node.
E/AccessibilityBridge(13171): VirtualView node must not be the root node.
I/chatty (13171): uid=10341(com.example.dexandrainventory) identical 2 lines
E/AccessibilityBridge(13171): VirtualView node must not be the root node.
E/AccessibilityBridge(13171): VirtualView node must not be the root node.
I/chatty (13171): uid=10341(com.example.dexandrainventory) identical 5 lines
If you want to display base64 image, need to use MemoryImage along with base64Decode which helps you decode the image and display in the pdf.
Printing.layoutPdf(
onLayout: (pageFormat) async {
final doc = pw.Document();
var imageProvider = MemoryImage(base64Decode("your image"));
final PdfImage image = await pdfImageFromImageProvider(
pdf: doc.document, image: imageProvider);
doc.addPage(pw.Page(build: (pw.Context context) {
return pw.Center(
child: pw.Image(image),
);
}));
return doc.save();
},
);
final profileImage = pw.MemoryImage(
(await rootBundle.load('assetsimage)).buffer.asUint8List(),);
Finally, use it
pw.Image(profileImage),
declare the variable 'pdf' inside the function.
Like this:
writeOnPdf() async {
final pdf = pw.Document(deflate: zlib.encode);