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
Related
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
I want to convert this ListView into ListView.builder, but somehow I could not figure out how I could do it. Any help would be greatly appreciated.
ListView(
children: snapshot.data!.docs.map((doc) {
final dynamic data = doc.data();
return Visibility(
child:
ContactListTileField(
text: data['contactName'].toString(),
iconData: Icons.delete,
function: () async {
DialogBox.dialogBox(
"Do you really want to delete ${data['contactName'].toString().capitalize}? "
, context
, (){
deleteContact(,context);
});
})
);
}).toList(),
)
ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
final doc = snapshot.data!.docs[index];
final dynamic data = doc.data();
return Visibility(
child: ContactListTileField(
text: data['contactName'].toString(),
iconData: Icons.delete,
function: () async {
DialogBox.dialogBox(
"Do you really want to delete ${data['contactName'].toString().capitalize}? "
, context
, (){
deleteContact(,context);
});
})
);}
)
Try this...
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.
I created a map called "records", the keys of this map are taken from the user when presed on 'save' botton, and the values are from the time counter that I have in my code.
But the problem is when I create a ListView.builder to export this map indexes to cards, it gave me Null values in each card index !!!
How can I show the real value instead of Null ?!!
Here is my code:
var _item;
List listCount = [];
Map<String, dynamic> records = {};
String name;
createAlertDialog(buildContext, context) {
TextEditingController controller;
return showDialog(
context: context,
// barrierDismissible: false,
builder: (context) {
return AlertDialog(
title: Text(
'Type record name',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18.0),
),
content: TextField(
controller: controller,
onChanged: (value) {
name = value;
}),
actions: [
MaterialButton(
elevation: 5.0,
child: Text('Save'),
onPressed: () {
listCount.add(_item);
print(_item);
records[name] = _item;
print(records);
Navigator.pop(context);
},
),
MaterialButton(
elevation: 5.0,
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
}
The variable _item is taking it's value from another site, see this:
StreamBuilder<int>(
stream: _stopWatchTimer2.rawTime,
initialData: 0,
builder: (context, snap) {
final value = snap.data;
final displayTime = StopWatchTimer.getDisplayTime(
value,
hours: _isHours2);
_item = displayTime;
return Padding(
padding: EdgeInsets.all(5.0),
child: Text(displayTime,
style: TextStyle(
fontSize: 30.0, color: Colors.white)),
);
},
),
And here where I create the ListView.builder:
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: records.length,
itemBuilder: (context, index) {
return MyCard(
colour: Colors.cyanAccent,
maker: Container(
width: 250.0,
height: 75.0,
child: Text(
'${records[index]}',
style: TextStyle(fontSize: 25.0),
textAlign: TextAlign.center,
),
),
);
},
),
The image in the link is a screen shot from my app.
Image
Looking at the _item variable which is initially null. You are not assigning any value to it. Please check your code. You are assigning a null value to your records because _item has not been given any value.
onChanged: (value){
_item = value;
}
you are not giving any value to the _item variable, I'm assuming you wanted to assign the value in the onChanged event like this:
onChanged: (value) {
_item = value;
}
or maybe you wanted to add the name to the list instead?
If I am understanding correctly, you have stored the item values into the records based on name variable in Save button onPressed event. But you are getting the record through the ListView index values. So, there is no record found in the records collection based on that index. So it returns null value.
Provide the index to store the item in the Save button instead of name. Or check the record based on name inside the ListView builder instead of index.
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.