Flutter save data by id using Shared Preferences - android

I have a listView, in which I have some products. I wanted a rating system on each product details page so I go through this answer How to save User rating in flutter rating bar?. Now the problem is that I am getting my star rating the same on each product detail page. Now please suggest to me, to save the value of the star with respect to product id in my shared preferences.
Or anyone has another solution please share it with me.
Rating Controller
class RatingController extends GetxController {
int currentRating = 0;
final box = GetStorage();
late SharedPreferences prefs;
#override
void onInit() { // called whenever we initialize the controller
super.onInit();
currentRating = box.read('rating') ?? 0; // initializing current rating from storage or 0 if storage is null
}
void updateAndStoreRating(int rating) {
currentRating = rating;
prefs.setInt('rating', rating); //SharedPreferences way
update(); // triggers a rebuild of the GetBuilder Widget
}
Future<void> initSp() async {
prefs = await SharedPreferences.getInstance();
currentRating = prefs.getInt('rating') ?? 0;
}
Widget buildRatingStar(int index) {
if (index < currentRating) {
return Icon(
Icons.star,
color: Colors.yellow,
);
} else {
return Icon(
Icons.star,
color: Colors.white,
);
}
}
}
Rating Widget
SharedPreferences? _prefs;
final controller = Get.find<RatingController>();
Widget _buildBody() {
final stars = List<Widget>.generate(5, (index) {
return GetBuilder<RatingController>( // rebuilds when update() is called from GetX class
builder: (controller) => Expanded(
child: GestureDetector(
child: controller.buildRatingStar(index),
onTap: () {
controller.updateAndStoreRating(index + 1);
print(index + 1);// +1 because index starts at 0 otherwise the star rating is offset by one
},
),
),
);
});
return Row(
children: [
Expanded(
child: Row(
children: stars,
),
),
Expanded(
child: TextButton(
onPressed: () {
controller.updateAndStoreRating(0);
},
child: Text(
"Clear",
style: TextStyle(color: Colors.white),
),
),
),
],
);
}
This working and saving star values but I am getting this value in all my list data's detail page. so please suggest me to save using particular index.

GetStorage cant save Map based data type and in your case it's better to use Hive :
First, add hive to your dependencies:
hive: ^2.0.4
hive_flutter: ^1.1.0
Then initialize it at the beginning of the application:
await Hive.initFlutter();
And use it like this:
var box = await Hive.openBox('myBox');
var person = Person()
..name = 'Dave'
..age = 22;
box.add(person);
print(box.getAt(0)); // Dave - 22
person.age = 30;
person.save();
print(box.getAt(0)) // Dave - 30
You can see more examples about using hive in this link.

Related

Is there a way to use the same globalkey in multiple widgets?? in flutter

So I'm relatively new to flutter and I've been trying to dynamically add Sections(TextFormFields) that are represented in a form that has Form.Helper as its child and in the process to get the saveAndValidate method to work i had to use a GlobalKey to be able to access the currentState of its so i can validate and save user input and such, but whenever i try add another Section to the screen it display this error massage
════════ Exception caught by widgets library ═══════════════════════════════════
Multiple widgets used the same GlobalKey.
════════════════════════════════════════════════════════════════════════════════
here is the code I wrote and I'd appreciate any help in solving this error please.
#1- the code for the model I used:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class AddCourse with ChangeNotifier {
String? sectionName;
List<String>? sections;
List<dynamic>? addVids;
AddCourse({this.sectionName, this.sections, this.addVids});
/*where we save our values later to push them to firbase/database*/
Map<String, dynamic> toJson() {
final Map<String, dynamic> sectionData = <String, dynamic>{};
sectionData['Section #'] =
sections; // where current section number is saved and is stored dynamicly and updates as user adds more or less sections.
sectionData['Section Name'] =
sectionName; // where the input of the textformfield is saved and to be later pushed to the database and also is stored in a list so it can hold multiple section names as such.
return sectionData;
}
/* this is another model data for a functionality thats not implemented yet*/
Map<dynamic, dynamic> toJson2() {
final Map<dynamic, dynamic> vidData = <dynamic, dynamic>{};
vidData['Videos #'] = addVids;
return vidData;
}
}
#2 this the code for the form I created
import 'package:flutter/material.dart';
import 'package:snippet_coder_utils/FormHelper.dart';
import '../provider/course_add_model.dart';
class CourseCardBody extends StatefulWidget {
const CourseCardBody({
Key? key,
}) : super(key: key);
#override
State<CourseCardBody> createState() => _CourseCardBodyState();
}
class _CourseCardBodyState extends State<CourseCardBody> {
/* this is where i set up my global key that has the type of GlobalKey<FormState>*/
/*State associated with a [Form] widget. such as textformfields/forms/textfields..etc// the use of the (FormState) is to be able to Access the Functions "save"/"validate"/"reset" as to use them with forms/textformfields that you want to validate thier input or save it*/
GlobalKey<FormState> globalkey = GlobalKey();
AddCourse coursesModel = AddCourse();
#override
void initState() {
super.initState();
coursesModel.sections = List<String>.empty(growable: true);
coursesModel.sections?.add("");
// adds empty sections to the list of sections when the add button is used
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add Courses'),
centerTitle: true,
),
body: ListView.separated(
shrinkWrap: true,
physics: const ScrollPhysics(),
itemBuilder: ((context, index) => Column(
children: [
_uiWidget(index),
Center(
// the submit button here needs some work to only be show once but for now sorry for this annoying button.
child: FormHelper.submitButton('Save', () {
if (validateAndSave()) {
print(coursesModel.toJson());
}
}),
),
],
)),
separatorBuilder: ((context, index) => const Divider()),
itemCount: coursesModel.sections!.length,
),
);
}
Widget _uiWidget(index) {
/* this form here is the parent of form fields/Formhelper widgets as seen below*/
return Form(
/* -- note here--
if we use a UniqueKey()
instead of our globalkey
here and comment the ValidateAndSave() function here
the form will work in terms of adding and removing sections
but we won't be able to either
save content/input of the user in the fields or
either validate
them so that sucks. */
/*this form is where global key is first used*/
key: globalkey,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_sectionsContainer(index),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Flexible(
flex: 1,
fit: FlexFit.loose,
child: FormHelper.inputFieldWidgetWithLabel(
context,
'Add Section$index',
'',
'Section Title',
(onValidate) {
if (onValidate.isEmpty) {
return 'section ${index + 1} name cant be empty';
}
return null;
},
(onSavedVal) {
coursesModel.sections![index++] = index.toString();
onSavedVal = index;
},
onChange: (onChangedval) {
coursesModel.sectionName = onChangedval;
},
initialValue: coursesModel.sectionName ?? "",
borderColor: Colors.black,
borderFocusColor: Colors.black,
fontSize: 14,
labelFontSize: 14,
validationColor: Colors.redAccent,
),
),
Visibility(
visible: index == coursesModel.sections!.length - 1,
child: IconButton(
onPressed: () {
addEmailControl();
},
icon: const Icon(
Icons.add_circle,
color: Colors.greenAccent,
),
),
),
Visibility(
visible: index > 0,
child: SizedBox(
width: 35,
child: IconButton(
onPressed: () {
removeEmailControl(index);
},
icon: const Icon(
Icons.remove_circle,
color: Colors.redAccent,
),
),
),
),
],
),
],
),
),
);
}
Widget _sectionsContainer(index) {
/* the widget used to create the current section displayed on the top left of each textformfields*/
return Column(
children: [
Padding(
padding: const EdgeInsets.all(10),
child: Text(
'Section ${index + 1}',
textAlign: TextAlign.left,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
),
],
);
}
void addEmailControl() {
setState(() {
coursesModel.sections!.add('');
});
}
void removeEmailControl(index) {
setState(() {
if (coursesModel.sections!.length > 1) {
coursesModel.sections!.removeAt(index);
}
});
}
bool validateAndSave() {
/* we're especially using the <FormState> that is provided by the Globalkey to be able access the currentState of widget/form that has the global key in order to either validate or save the textformfields input or both in the same time*/
// validate each form
if (globalkey.currentState!.validate()) {
// If all data are correct then save data to out variables
// save each form
globalkey.currentState!.save();
return true;
} else {
return false;
}
}
}
I'm trying my best to figure it out on my own as I want to know how to solve this problem properly and where did I go wrong, and any help is very much appreciated thank you!
I suggest to create List<GlobalKey> variable. When you dynamically add or delete sub forms, you add or remove list items accordingly. It is impossible to use same GlobalKey for multiple widgets. So you need to create separate GlobalKeys for each form.
You may create a file of Global variables that may be shared across multiple files to ensure you are using a single instance.
Example globals.dart file
GlobalKey<SomeState> myGlobalKey = GlobalKey<SomeState>();
Example of implementation inside main.dart (or whatever file)
import './[path-to-globals]/globals.dart' // enter the appropriate path for your project
... // some code
Form(
key: myGlobalKey,
... // code
)
... // maybe more code

Flutter: Is there a way to change the contents of a card from another button?

I am currently developing a manpower app which displays a few groups of people and their details. I have a row of buttons at the top of the card which display the groups of people available. Below the row of buttons is a card which displays the details of each individual in rows.
However, I am unable to change the bottom card even when pressing the top button corresponding to the card. I have tried using setState(), and even navigating out and back into the page (to refresh the build). However, the bottom card remains the same, and always displays section 1, which is the initial value given to the card. How am I able to change the bottom card, after pressing the top row button corresponding to the card?
The code is below-
int section = 4;
int currentSectionSelected = 1;
#override
void initState() {
loadSectionDetails();
super.initState();
}
void loadSectionDetails() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
section = (prefs.getInt('sectionCounter') ?? 4);
currentSectionSelected = (prefs.getInt('currentSectionSelected') ?? 1);
});
}
void currentSectionSelection(int sectionSelected) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('currentSectionSelected', sectionSelected);
setState(() {
currentSectionSelected = sectionSelected;
});
}
#override
Widget build(BuildContext context) {
List<Widget> sectionList = List.generate(section, (int i) =>
TextButton(
child: Text("Section "+(i+1).toString()),
onPressed: () {
currentSectionSelection(i+1);
},
)
);
return Card (
child: Column(
children: <Widget>[
Row(
children: sectionList
),
Card(
child: PersonnelSection(sectionNumber: currentSectionSelected)
)
]
)
);
PersonnelSection() is the name of another widget.
The image is here
Thanks all!
If PersonnelSection is a StatefulWidget, pass the key to it like this
Card(
child: PersonnelSection(
sectionNumber: currentSectionSelected,
key: ValueKey(currentSectionSelected),
),
);

Adding phone number to contact in flutter/dart

I'm building a selectable checkbox contact list in flutter but if a contact has only an email and no number, an error is thrown. I want to create a loop to add a number of '99999' to the contacts phone number if they don't have one. Please can someone guide me with an explanation of what I should change to make this work? I have had a go, but I am quite new to flutter so I'm not completely certain on syntax etc...
Here is the part of the code that I am trying to put the function into.
setMissingNo()async {
Iterable<Contact> contactsToLoop = (await ContactsService.getContacts()).toList();
contactsToLoop.forEach((Contact) { contactsToLoop = []..add(Item.fromMap({'label': 'work', 'value': 99999})); });
}
//fetch contacts from setMissingNo
getAllContacts() async{
Iterable<Contact> _contacts = (await ContactsService.getContacts()).toList();
setState(() {
contacts = _contacts;
}
);
}
Here is my whole code
import 'package:flutter/material.dart';
// TODO: make it ask for permissions otherwise the app crashes
import 'package:contacts_service/contacts_service.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<Contact> contacts = [];
List<Contact> contactsFiltered = [];
TextEditingController searchController = new TextEditingController();
#override
void initState() {
super.initState();
getAllContacts();
searchController.addListener(() => filterContacts());
}
//remove the +'s and spaces from a phone number before its searched
String flattenPhoneNumber(String phoneStr) {
return phoneStr.replaceAllMapped(RegExp(r'^(\+)|\D'), (Match m) {
return m[0] == "+" ? "+" : "";
});
}
//loop and set all contacts without numbers to 99999, pass new list to getAllContacts
setMissingNo()async {
Iterable<Contact> contactsToLoop = (await ContactsService.getContacts()).toList();
contactsToLoop.forEach((Contact) { contactsToLoop = []..add(Item.fromMap({'label': 'work', 'value': 99999})); });
}
//fetch contacts from setMissingNo
getAllContacts() async{
Iterable<Contact> _contacts = (await ContactsService.getContacts()).toList();
setState(() {
contacts = _contacts;
}
);
}
//filtering contacts function to match search term
filterContacts() {
List<Contact> _contacts = [];
_contacts.addAll(contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere((contact) {
String searchTerm = searchController.text.toLowerCase();
String searchTermFlatten = flattenPhoneNumber(searchTerm);
String contactName = contact.displayName.toLowerCase();
bool nameMatches = contactName.contains(searchTerm);
if (nameMatches == true) {
return true;
}
if (searchTermFlatten.isEmpty) {
return false;
}
var phone = contact.phones.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn.value);
return phnFlattened.contains(searchTermFlatten);
}, orElse: () => null);
return phone != null;
});
setState(() {
contactsFiltered = _contacts;
});
}
}
final selectedContacts = Set<Contact>();
#override
Widget build(BuildContext context) {
bool isSearching = searchController.text.isNotEmpty;
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
AppBar(
title: Text('Create Group'),
),
Container(
child: TextField(
controller: searchController,
decoration: InputDecoration(
labelText: 'Search Contacts',
border: OutlineInputBorder(
borderSide: new BorderSide(
color: Theme.of(context).primaryColor
)
),
prefixIcon: Icon(
Icons.search,
color: Theme.of(context).primaryColor
)
),
),
),
Expanded( child: ListView.builder(
shrinkWrap: true,
itemCount: isSearching == true ? contactsFiltered.length : contacts.length,
itemBuilder: (context, index) {
Contact contact = isSearching == true ? contactsFiltered[index] : contacts[index];
//TODO: make it so when you clear your search, all items appear again & when you search words it works
return CheckboxListTile(
title: Text(contact.displayName),
subtitle: Text(
contact.phones.elementAt(0).value
),
value: selectedContacts.contains(contact),
onChanged: (bool value) {
if (value) {
selectedContacts.add(contact);
} else {
selectedContacts.remove(contact);
}
setState((){});
// TODO: add in function to add contact ID to a list
});
},
),
/*new Expanded(
child: Align(
alignment: Alignment.bottomLeft,
child: BottomNavigationBar(
currentIndex: _currentIndex,
items: const <BottomNavigationBarItem>[
//TODO: create new contact functionality to add someone by name + email
BottomNavigationBarItem(
icon: Icon(Icons.add),
title: Text('Add Contact'),
),
BottomNavigationBarItem(
icon: Icon(Icons.create),
title: Text('Create Group'),
),
],
onTap: (index) {
setState(() {
_currentIndex = index;
});
}
)
)
)*/
)
],
)
),
);
}
}
Updating all contacts listed on the device might take a long time depending on the size of the device's contact list. Add that the task is being done on the UI thread. You may want to consider using Isolate for the task to move away the load from the UI thread. If you can also provide the errors that you're getting, it'll help us get a picture of the issue.
Another thing is, the way you're approaching the issue might be impractical. Is it really necessary to write a placeholder phone number to the contacts? The issue likely stems from trying to fetch the number from a contact but the Object returns null. Perhaps you may want to consider only updating the phone number when the contact is selected.

Add the quantity of items (e-commerce/shop app)

i'm currently developing an e-commerce app,
i'm trying to increase the quantity of items the user are trying to shop and then show them in the "items Cart" but instead, i get multiple times the same item.
cart_Items_Screen
here's the code i'm using for it:
FlatButton(
onPressed: () {
_addToCart(context, this.widget.product);
},
textColor: Colors.redAccent,
child: Row(
children: [
Text('Add to Cart'),
IconButton(
icon: Icon(Icons.shopping_cart), onPressed: () {}),
],
),
),
_addToCart(BuildContext context, Product product) async {
var result = await _cartService.addToCart(product);
if (result > 0) {
print(result);
_showSnackMessage(Text(
'Item added to cart successfully!',
style: TextStyle(color: Colors.green),
));
} else {
_showSnackMessage(Text(
'Failed to add to cart!',
style: TextStyle(color: Colors.red),
));
}
}
addToCart(Product product) async {
List<Map> items =
await _repository.getLocalByCondition('carts', 'productId', product.id);
if (items.length > 0) {
product.quantity = items.first['productQuantity'] + 1;
return await _repository.updateLocal(
'carts', 'productId', product.toMap());
}
print(items);
product.quantity = 1;
return await _repository.saveLocal('carts', product.toMap());
}
Have anyone has experience something like this?
Can anyone help me?
What are you using to keep your items? Local database or just a list? In any case you need to check your items contains first, then if it is you need update only quantity if it is not you need to add as a new element. I mean as I understand you check this with items.length > 0 and it looks too general, items.contains('productId') would be more specific to use.

Im having trouble populating ListTile in ListView.builder from database

Im having trouble populating ListTile in ListView.builder from database.
I dont have "model class" since i dont need to update delete data i just need simple query.
I have ExpansionTile with three categories and in each one i need query from db. I dont know hoe to write or what to return from db class for this to work.
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemBuilder: (context, i) => ExpansionTile(
title: new Text(
'${categoryName[i]}',
style: TextStyle(
fontSize: 18,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(49, 85, 158, 1)),
),
children: list //final list = new List.generate(17, (i) => "Item ${i + 1}"); --just to populete with dummy items, instad of this i need db data
.map((val) => ListTile(
// leading: Icon(Icons.add),
title: new Row(
children: <Widget>[
new Checkbox(
value: _isCheck,
onChanged: (bool value) {
onChange(value);
}),
new Expanded(child: new Text(val)),
],
)))
.toList(),
),
itemCount: categoryName.length,
),
),
],
),
From my db class :
Future<List> getAllNotes() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'books.db');
Database database = await openDatabase(path, version: 1);
//var dbClient = await database();
var result = await database.rawQuery('SELECT * FROM $booksTable WHERE $colDescription = ${'Adventure'}');
return result.toList();
}
So how to write simple query to get result in ListView/ListTile?
You really need to provide much more details about your problem. Anyways, ill try to answer with what I have understood.
Let's say you have a table names 'booksTable' with 3 fields:
bookId | bookName | bookCategory
1 Book A Adventure
2 Book B History
3 Book C Adventure
4 Book D History
Make sure you create all these database functions in DatabaseHelper() class, so that you don't have to write logic to db again and again.
Now you query will look something like this:
Future<List<String>> getAllNotes(String category) async {
var dbClient = await database();
List<String> bookNames = List<String();
var result = await dbClient.rawQuery("SELECT bookname FROM booksTable WHERE bookCategory = $category");
result.forEach((item) {
bookNames.add(item["bookname"]);
});
return bookNames;
}
This will work only if you have to deserialise 1 column. If you have multiple columns selected, you have to create a model class.
Now in your front view, you have two options:
1) You can use initState to populate your List with bookNames of category in the parameter
2) You can use FutureBuilder to populate your list as well
(You have to use StatefulWidget for both these options)
I'll show you how to do it using initState here. If you want to know how to do it using FutureBuilder, let me know in comments.
List<String> booksList =List<String>();
var db = DatabaseHelper();
readList() async {
booksList = await db.getAllNotes("Adventure");
}
#override
void initState() {
super.initState();
readList();
}
ListView.builder(
itemBuilder: (context, i) {
Column( crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ExpansionTile(
title: new Text(
"Adventure Category",
style: TextStyle(
fontSize: 18,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(49, 85, 158, 1)),
),
ListTile(
title: new Row(
children: <Widget>[
new Checkbox(
value: _isCheck,
onChanged: (bool value) {
onChange(value);
}),
Expanded(child: new Text("${booksList[i]}")),
],
)))
),])}
itemCount: booksList.length,
),
),
],
)
Note: There might be typos in the code above, since i have typed it on phone, but you get the idea how to do it, right?
So, i have ListView (with 3 expanded groups) im geting them from array: ( List categoryName = ['Part 1: Adventure', 'Part 2: History','Part 3: Horror'];
And passing then here :
child: Column(
children: [
Expanded(
child: ListView.builder(
itemBuilder: (context, i) => ExpansionTile(
title: new Text(
'${categoryName[i]}',
),
That part working fine, i get 3 expandeble titles, now children of that ( ListTile ) need to be populate from db .
With your example :
readList() async {
sinsAgainstGod = await db.getSins("Adventure");
}
I get error: ...near "Adventure": syntax error..
And keep geting 0 lenght on booksList...
Future<List<String>> getNotes(String category) async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'books.db');
Database database = await openDatabase(path, version: 1);
List<String> bookNames = List<String>();
var result = await database.rawQuery("SELECT $colDescription FROM $booksTable WHERE = $category ");
result.forEach((item) {
bookNames.add(item['Category']);
});
return bookNames;
}
What this result.forEach(item) suppose to do?
Thank you for your answer it was helpful.
Can you tell me why im getting 20 same description instead literate through all with this code:
Future<List<String>> getSins(String column) async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'confession.db');
Database database = await openDatabase(path, version: 1);
List<String> bookNames = List<String>();
for (int i = 0; i < 20; i++) {
var result = await database.rawQuery(
'SELECT * FROM $plannerTable WHERE $colCategory= "Adventure');
bookNames.add((result[0][column].toString()));
}
return bookNames;
}
I want to get all decription from adventure category. Tnx

Categories

Resources