Flutter load list with id - flutter

Hey how can i load one of several lists with one id?
my lists look like this
List one = [
{'name': 'USA'},
{'name': 'Germany'},
];
List two = [
{'name': 'BMW'},
{'name': 'Audi'},
];
i need load one of this list like this
body: Column(
children: one.map((info) {
return Container(
child: SizedBox(
children: [
Text(
info['name'],
),
],
),
),
);
}).toList(),
));
all i want is to load one of the two lists depending on the id of my previous page
for example id 1 was passed then two.map should be loaded
I have created a variable on this page that is also passed, I tried to use variable.map but it doesn't work

If you have many lists, put your Lists into a List. With your variable from the previous page you can call the right List out of your data.
data[variable].map(info) { ....... }
Edit:
Step
create List<List> data ; their you can save all your list; when you want your List "one".
const List<List<dynamic>> data = [[{'name': 'USA'},{'name': 'Germany'},],[ {'name': 'BMW'},{'name': 'Audi'},]];
Step
put it into your widget tree and call the right data with your variable(x)(INTEGER) to get the right list and map it as before:
body: Column(
children: data[x].map((info) {
return Container(
child: SizedBox(
children: [
Text(
info['name'],
),
],
),
),
);
}).toList(),
));
If that isn't working you may have another problem in another topic.
Tom

ternary operator helps you
body: Column(
children:Your variable == 1
? one.map((info) {
return Container(
child: SizedBox(
child: Text(
info['name'],
),
),
);
}).toList()
: one.map((info) {
return Container(
child: SizedBox(
child: Text(
info['name'],
),
),
);
}).toList()),
);

Related

How to show phone icon when a phone number text is selected?

I have a SelectableText Widget with a string which is a phone number
Starts with +
Has 12 digits
When the text is selected, the option to call it doesn't appear.
If I open the same text for example in a google search as below, I can see the option to call it. How can I make that in Flutter?
You may use the contextMenuBuilder property for this.
It will help you creating a different context menu depending on the current state of the user's selection:
More info: see contextMenuBuilder property in SelectableText widget doc
SelectableText(
'data to show',
contextMenuBuilder: (_, textState) => Row(
children: [
if (isPhoneNumber(textState.textEditingValue.text))
Container(), //Widget to make the phone call here
],
),
),
bool isPhoneNumber(String selection) {
if (!selection.startsWith('+')) return false;
return RegExp(r'^[0-9]+$').hasMatch(selection.substring(1));
}
I solved it by looking at the example pointed out by #Luis Utrera
Solution:
contextMenuBuilder: (context, EditableTextState editableTextState) {
return AdaptiveTextSelectionToolbar(
anchors: editableTextState.contextMenuAnchors,
children: [
Padding(
padding: const EdgeInsets.all(10),
child: IconButton(
icon: Icon(Icons.call),
onPressed: () {
// TODO: launch call app
},
),
),
...editableTextState.contextMenuButtonItems
.map((ContextMenuButtonItem buttonItem) {
return CupertinoButton(
borderRadius: null,
onPressed: buttonItem.onPressed,
padding: const EdgeInsets.all(10.0),
pressedOpacity: 0.7,
child: Text(
CupertinoTextSelectionToolbarButton.getButtonLabel(
context,
buttonItem,
),
),
);
})
.toList()
.cast(),
],
);
},

Flutter: realtime database querying using orderbychild() and only int value works string data not querying

starCountRef.orderByChild('Series').startAt('sam').endAt('1')
This code only work if I use int values to fetch data; string values are not fetching the data.
DatabaseReference starCountRef =
FirebaseDatabase.instance.ref('/Shop/qw1234/Inventory/');
bool data = false;
Expanded(
child: FirebaseAnimatedList(
query: starCountRef
.orderByChild('Series')
.startAt('sam')
.endAt('1'),
itemBuilder: (context, snapshot, animation, index) {
return ListTile(
onTap: (() {
print(index);
}),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Text('Price: Rs '),
Text(
snapshot.child('Price').value.toString()),
],
),
],
),
subtitle: Padding(
padding: const EdgeInsets.only(top: 10, bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'Model: ',
style: TextStyle(
fontWeight: FontWeight.bold),
),
Text(snapshot
.child('Series')
.value
.toString()),
],
),
],
),
),
);
}),
)
My firebase realtime database I am trying to setup a search box to search product and edit or delete them
Can any one help me? I am developing an inventory app for a shop. I am trying to make a search box so the owners can see their stock limits and item prices.
I rather think the firebase query works in ASCII order. In ASCII order, numbers appear before letters so starting at 'a letter string' and ending at 'a number string' is likely to cause you problems.
I don't see a '1' in your example of 'Series', you aren't trying to reference the '1' child in the 'Inventory' node are you?

In Flutter, I can't center cards in containers

return Scaffold(
body: Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
color: Colors.red,
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Center(
child: SelectGroupCard(context, titles: titles, ids: ids,
onTap: (title, id) {
setState(() {
cardGroupResult = title + " " + id;
});
}),
),
),
],
),
There are several cards as seen in the picture. I want to get these right out. I even want to be able to show these cards in the middle of the page, in 3 columns, 4 rows.
Use widget GridView, it allows you to select the desired number of columns and rows. Also, it is possible to install paddings.
you can use GridView
GridView(
gridDelegate:const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, // you can change this
),
children :[...] // put your cards here !
)
you can remove the width property of SelectGroupCard. for example, if SelectGroupCard is a row widget, the following code like this:
Row(
mainAxisSize: MainAxisSize.min,
children: [],
)

Building widgets with Hive box data

I was building my Widgets from a list that was predefined in a file of MyClass I created. This worked but I wanted to be able to store persisted data for adding a Boolean favorite field.
I created the Hive Types/Fields for my class, generated the type adapters, and successfully loaded the Hive box on first run of the app, and I can print values to the console, so I know the data is all there and correct.
In the class I have, name, image url path to asset image and a favorite field.
Before when I was using the list to get my data I was able to get the image URL like this:
Expanded(child: Image.asset(widget.MyClass.imageURL)),
Now I want to get this from the Hive box
Box<MyClass> box = Hive.box<MyClass>('myClassBox');
//This is where I am stuck
Expanded(child: Image.asset(box.???)),
I tried box.values.where and box.get() to then get to imageURL field. But get requires a key, which I don't have to pass it from
Widget build(BuildContext context)
And I then have the same issue when trying to access the favorite field, which I am using the Favorite Button package (favorite_button 0.0.4). And I will then update the true/false value based on the button being tapped.
If someone can point me in the right direction that would be great.
Thanks.
Edit:
Here is the Widget:
Widget build(BuildContext context) => GestureDetector(
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => TaskPage(job: widget.job), //Need to get data from Hive now
)),
child: Container(
padding: const EdgeInsets.all(16),
height: 100,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: [
Expanded(flex: 3, child: buildText()),
Expanded(child: Image.asset(widget.job.imageUrl)),//Need to get data from Hive now
GestureDetector(
child: Icon(
widget.job.fav ? Icons.favorite : Icons.favorite_border, //Need to get data from Hive now
),
onTap: () {
// add/remove from favorites list
}
),
],
),
),
);
Second Edit: Here is the same code after implementing the suggestion given
Widget build(BuildContext context) => GestureDetector(
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => TaskPage(job: Hive.box<Job>('jobBox').get(context)), //This bit is still broken so I need to look at this
)),
child: Column(
children:
Hive.box<Job>('jobBox').values.toList().map(
(elementList) => Container(
padding: const EdgeInsets.all(16),
height: 100,
decoration: BoxDecoration(
color: white,
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: [
Expanded(flex: 3, child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
elementList.name,
style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20),
),
SizedBox(height: 10),
//Text('Num tasks in job'),
],
)),
Expanded(child: Image.asset(elementList.imageURL)),
GestureDetector(
child: Icon(
elementList.fav
? Icons.favorite
: Icons.favorite_border,
color: elementList.fav ? Colors.red.shade200 : Colors.grey,
),
onTap: () {
//To do
}
// )
),
],
),
),
)
.toList(),
),
);
Assuming that you have only 1 data in the box, you can access that stored data like this.
Box<MyClass> box = Hive.box<MyClass>('myClassBox');
if(box.isNotEmpty) {
final data = box.values.first;
// use data
} else {
// empty state
}
Hive values could have keys, depending on how you use it. If you used box.put(key, value), you can use box.get(key) to work with keys and values.
If you used box.add(value), it stores the data with auto assigned indexes starting from 0. So you can usebox.getAt(index) to get a data with index.

How can i build conditions through widgets when streaming data?

I'm streaming a collection as snapshot from a firestore to my flutter project. How can i write inside a text widget e.g. 'empty' when the variable im looping doesn't exist in the collection?
child: Column(
children: <Widget>[
if (title != null)
{
Text(
title,
),
),
}
else {
Text('empty'),
You can use like below code:-
String title = '';
return Container(
child: Column(
children: <Widget>[
Text(title.isNotEmpty ? title : 'empty')
],
),
);