How to make DropdownButtonFormField data from sqflite? - flutter

class SQLHelper
Future<List<Map<String, dynamic>>> selectAllServer() async {
final db = await init();
return db.query('server', orderBy: "ip");
}
class ModalDialog
List<Map<String, dynamic>> _server = [];
void getDataDB() async {
final data = await db.selectAllServer();
setState(() {
_server = data;
});
}
DropdownButtonFormField(
onChanged: (val) {},
items: _server.map((ip) {
return DropdownMenuItem(
value: ip['ip'],
child: Text(ip['ket']),
);
}).toList(),
)
Why Value and Child DropdownMenuItem now show?
I want to make Dropdown, value and title get from sqflite.

Related

How to retrieve particular data from id on flutter

How to retrieve particular data from id on flutter and want to show data inside list view. I have created view, insert, delete and update operations.i used sqflite
my code is below.
main.dart file
class _SqliteAppState extends State<SqliteApp> {
int? selectedId;
final textController = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: TextField(
controller: textController,
),
),
body: Center(
child: FutureBuilder<List<Grocery>>(
future: DatabaseHelper.instance.getGroceries(),
builder: (BuildContext context,
AsyncSnapshot<List<Grocery>> snapshot) {
if (!snapshot.hasData) {
return Center(child: Text('Loading...'));
}
return snapshot.data!.isEmpty
? Center(child: Text('No Groceries in List.'))
: ListView(
children: snapshot.data!.map((grocery) {
return Center(
child: Card(
color: selectedId == grocery.id
? Colors.white70
: Colors.white,
child: ListTile(
title: Text(grocery.name),
onTap: () {
setState(() {
if (selectedId == null) {
textController.text = grocery.name;
selectedId = grocery.id;
} else {
textController.text = '';
selectedId = null;
}
});
},
onLongPress: () {
setState(() {
DatabaseHelper.instance.remove(grocery.id!);
});
},
),
),
);
}).toList(),
);
}),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.save),
onPressed: () async {
selectedId != null
? await DatabaseHelper.instance.update(
Grocery(id: selectedId, name: textController.text),
)
: await DatabaseHelper.instance.add(
Grocery(name: textController.text),
);
setState(() {
textController.clear();
selectedId = null;
});
},
),
),
);
}
The model class code is below
Grocery({this.id, required this.name});
factory Grocery.fromMap(Map<String, dynamic> json) => new Grocery(
id: json['id'],
name: json['name'],
);
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
}; } }
This is my db_helper class code. I have created view, insert, delete and update operations.
class DatabaseHelper {
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
Future<Database> _initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'groceries.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE groceries(
id INTEGER PRIMARY KEY,
name TEXT
)
''');
}
Future<List<Grocery>> getGroceries() async {
Database db = await instance.database;
var groceries = await db.query('groceries', orderBy: 'name');
List<Grocery> groceryList = groceries.isNotEmpty
? groceries.map((c) => Grocery.fromMap(c)).toList()
: [];
return groceryList;
}
Future<int> add(Grocery grocery) async {
Database db = await instance.database;
return await db.insert('groceries', grocery.toMap());
}
Future<int> remove(int id) async {
Database db = await instance.database;
return await db.delete('groceries', where: 'id = ?', whereArgs: [id]);
}
Future<int> update(Grocery grocery) async {
Database db = await instance.database;
return await db.update('groceries', grocery.toMap(),
where: "id = ?", whereArgs: [grocery.id]);
}
}
You can use this function to get the data by id:
Future<List<Grocery>> getGrocerieById(int id) async {
Database db = await instance.database;
var groceries =
await db.query('groceries', where: 'id = ?', whereArgs: [id]);
List<Grocery> groceryList = groceries.isNotEmpty
? groceries.map((c) => Grocery.fromMap(c)).toList()
: [];
return groceryList;
}

Searchable Dropdown with Flutter, Mobx and Sqlite

I am tryng implement a Searchable Dropdown package:
https://github.com/salim-lachdhaf/searchable_dropdown
I am using mobx and Sqlite
See Widget Code:
DropdownSearch<TarefaModel>(
label: 'BUSCAR TAREFAS',
onFind: (String filter) =>
controller.filtrarTarefas(filter),
onChanged: (TarefaModel data) {
print(data);
},
dropdownBuilder: _customDropDownExample,
),
My Mobx action:
Controller action:
#observable
ObservableList<TarefaModel> tarefas = new ObservableList<TarefaModel>();
#action
filtrarTarefas(termo) async {
final repository = new TarefaRepository();
tarefas = new ObservableList<TarefaModel>();
var data = await repository.search(termo);
tarefas.addAll(data);
return tarefas;
}
Custom DropDown:
Widget _customDropDownExample(
BuildContext context, TarefaModel item, String itemDesignation) {
return Container(
child: Observer(
builder: (_) => ListView.builder(
itemCount: controller.tarefas.length,
itemBuilder: (context, i) {
return ListTile(
title: Text(item.descricao),
subtitle: Text(item.label),
);
})),
);
}
My Model:
class TarefaModel{
int id;
String descricao;
TarefaModel({this.id, this.descricao});
Map<String, dynamic> toMap() {
return {'id': id,'descricao': descricao};
}
}
But this erros is show:
Any idea? Thanks
My repository:
Future<List<TarefaModel>> search(String term) async {
try {
final Database db = await _getDatabase();
final List<Map<String, dynamic>> maps = await db.query(
TAREFAS_TABLE,
where: "descricao LIKE ?",
whereArgs: [
'%$term%',
],
);
return List.generate(
maps.length,
(i) {
return TarefaModel(
id: maps[i]['id'],
descricao: maps[i]['descricao'],
);
},
);
} catch (ex) {
print(ex);
return new List<TarefaModel>();
}
}

Flutter How to populate data from sqflite to dropdown list

I have seen the questions in stackoverflow which are quite similar to my question, but those question and answer dint work for me. So here is my question how to populate data from sqflite to dropdown list. Below are the dart files which I have written.Please help me with the question
dbhelper.dart
import 'package:abc/model/manage_categories.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static DatabaseHelper _databaseHelper; // Singleton DatabaseHelper
static Database _database; // Singleton Database
String categoriesTable = 'categories_table';
String colId = 'id';
String colTitle = 'title';
String colDate = 'date';
DatabaseHelper._createInstance(); // Named constructor to create instance of DatabaseHelper
factory DatabaseHelper() {
if (_databaseHelper == null) {
_databaseHelper = DatabaseHelper._createInstance(); // This is executed only once, singleton object
}
return _databaseHelper;
}
Future<Database> get database async {
if (_database == null) {
_database = await initializeDatabase();
}
return _database;
}
Future<Database> initializeDatabase() async {
// Get the directory path for both Android and iOS to categories database.
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'categoriess.db';
// Open/create the database at a given path
var categoriessDatabase = await openDatabase(path, version: 1, onCreate: _createDb);
return categoriessDatabase;
}
void _createDb(Database db, int newVersion) async {
await db.execute('CREATE TABLE $categoriesTable($colId INTEGER PRIMARY KEY AUTOINCREMENT, $colTitle TEXT, '
'$colDate TEXT)');
}
// Fetch Operation: Get all categories objects from database
Future<List<Map<String, dynamic>>> getCategoriesMapList() async {
Database db = await this.database;
// var result = await db.rawQuery('SELECT * FROM $categoriesTable order by $colTitle ASC');
var result = await db.query(categoriesTable, orderBy: '$colTitle ASC');
return result;
}
// Insert Operation: Insert a categories object to database
Future<int> insertCategories(Categories categories) async {
Database db = await this.database;
var result = await db.insert(categoriesTable, categories.toMap());
return result;
}
// Update Operation: Update a categories object and save it to database
Future<int> updateCategories(Categories categories) async {
var db = await this.database;
var result = await db.update(categoriesTable, categories.toMap(), where: '$colId = ?', whereArgs: [categories.id]);
return result;
}
Future<int> updateCategoriesCompleted(Categories categories) async {
var db = await this.database;
var result = await db.update(categoriesTable, categories.toMap(), where: '$colId = ?', whereArgs: [categories.id]);
return result;
}
// Delete Operation: Delete a categories object from database
Future<int> deleteCategories(int id) async {
var db = await this.database;
int result = await db.rawDelete('DELETE FROM $categoriesTable WHERE $colId = $id');
return result;
}
// Get number of categories objects in database
Future<int> getCount() async {
Database db = await this.database;
List<Map<String, dynamic>> x = await db.rawQuery('SELECT COUNT (*) from $categoriesTable');
int result = Sqflite.firstIntValue(x);
return result;
}
// Get the 'Map List' [ List<Map> ] and convert it to 'categories List' [ List<Categories> ]
Future<List<Categories>> getCategoriesList() async {
var categoriesMapList = await getCategoriesMapList(); // Get 'Map List' from database
int count = categoriesMapList.length; // Count the number of map entries in db table
List<Categories> categoriesList = List<Categories>();
// For loop to create a 'categories List' from a 'Map List'
for (int i = 0; i < count; i++) {
categoriesList.add(Categories.fromMapObject(categoriesMapList[i]));
}
return categoriesList;
}
}
Add_store_item.dart
import 'package:flutter/material.dart';
import 'package:abc/database/dbhelper_categories.dart';
import 'package:abc/database/dbhelper_manage_inventory.dart';
import 'package:abc/model/Manageinventory_class.dart';
import 'package:abc/model/manage_categories.dart';
class AddStoreItem extends StatefulWidget {
final Inventory inventory;
AddStoreItem(this.inventory);
#override
State<StatefulWidget> createState() => new AddStoreItemState();
}
class AddStoreItemState extends State<AddStoreItem> {
DatabaseHelper databaseHelper = DatabaseHelper();
List<Categories> categoriesList = <Categories>[];
int count = 0;
DBProvider _db = DBProvider();
TextEditingController _itemController;
TextEditingController _quantityController;
TextEditingController _categoryController;
TextEditingController _unitController;
TextEditingController _locationController;
#override
void initState() {
super.initState();
_loadCategorieslist();
_itemController = new TextEditingController(text: widget.inventory.item);
_quantityController = new TextEditingController(text: widget.inventory.quantity);
_categoryController = new TextEditingController(text: widget.inventory.category);
_unitController = new TextEditingController(text: widget.inventory.unit);
_locationController = new TextEditingController(text: widget.inventory.location);
}
_loadCategorieslist()async{
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add Inventory')
),
body: SingleChildScrollView(
child: Container(
margin: EdgeInsets.all(15.0),
alignment: Alignment.center,
child: Column(
children: <Widget>[
SizedBox(height: 10),
TextField(
controller: _itemController,
decoration: InputDecoration(labelText: 'Item'),
),
SizedBox(height: 10),
TextField(
controller: _quantityController,
decoration: InputDecoration(labelText: 'Quantity'),
),
SizedBox(height: 10),
DropdownButton<String>(
value: categoriesList,
items: categoriesList.map((String){
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}),
isExpanded: true,
onChanged: (value) {
print("value: $value");
},
hint: Text(
"Units",
style: TextStyle(
// color: Colors.black,
),
),
),
DropdownButton<String>(
items: [
DropdownMenuItem<String>(
value: "1",
child: Text(
"First",
),
),
DropdownMenuItem<String>(
value: "2",
child: Text(
"Second",
),
),
],
isExpanded: true,
onChanged: (value) {
print("value: $value");
},
hint: Text(
"Location",
style: TextStyle(
// color: Colors.black,
),
),
),
SizedBox(height: 10),
RaisedButton(
child: (widget.inventory.id != null) ? Text('Update') : Text('Add Inventory'),
onPressed: () {
_addInventory();
},
),
],
),
),
),
);
}
void _addInventory() {
if (widget.inventory.id != null) {
_db
.updateNote(Inventory.withId(
widget.inventory.id,
_itemController.text,
_quantityController.text,
_categoryController.text,
_unitController.text,
_locationController.text,
))
.then((_) => Navigator.pop(context, 'update'));
} else {
_db
.saveNote(Inventory(
_itemController.text,
_quantityController.text,
_categoryController.text,
_unitController.text,
_locationController.text,
))
.then((_) => Navigator.pop(context, 'save'));
}
}
}
This how I managed to populate the list of data from sqflite to drop down
Declared list from sqflite to AddStoreItemState as below
DatabaseHelper databaseHelper = DatabaseHelper();
List<Categories> categoriesList ;
Categories _category;
Now wrap the drop down button as below
Center(
child: DropdownButtonFormField<Categories>(
hint: Text('Categories'),
value: _category,
onChanged: (Categories value){
setState(() {
_category = value;
});
},
items: categoriesList.map((user) => DropdownMenuItem<Categories>(
child: Text(user.cname),
value: user,
)
).toList(),
),
),
In AddStoreItemState change your _loadCategorieslist()async method to:
Future<List<Categories>> _loadCategorieslist() async => databaseHelper.getCategoriesMapList();
And wrap your DropdownButton with a FutureBuilder
This is how I read data from SqfLite to use it in a drop-down or data table, in this case barcode records.
Here is the model, which includes a fromJson() function like below:
class Barcode {
String code;
String itemNo;
Barcode({
this.code,
this.itemNo,
});
Map<String, dynamic> toMap() => {
'code': code,
'itemNo': itemNo,
};
factory Barcode.fromJson(Map<String, dynamic> parsedJson) {
return Barcode(
code: parsedJson['code'],
itemNo: parsedJson['itemNo'],
);
}
}
Here is how I read barcodes (all) from SqfLite:
static Future<List<Barcode>> getAll() async {
final db = await DbUtil.database;
var response = await db.query(tableName);
List<Barcode> list = response.map((c) => Barcode.fromJson(c)).toList();
return list;
}
Here is for reading just one barcode:
static Future<Barcode> get(String barcode) async {
final db = await DbUtil.database;
var response = await db.query(tableName, where: "$pkName = ?", whereArgs: ['$barcode']);
return response.isNotEmpty ? Barcode.fromJson(response.first) : null;
}
Then to call it:
var barcode = await BarcodeDb.get(scanText);
Try this out, it should work for you.

Flutter DropdownButton get value from SharedPreferences

So I making an app in which I have DropdownButton. I want to get the value parameter from SharedPreferences. But SharedPreferences.getInstance returns Future, not String. How could I return a String instead of Future?
This is a function for reading from SharedPreferences
_read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'cur_r';
final value = prefs.getString(key) ?? "";
print('read: $value');
return value;
}
Here is the dropdown Button code:
body: Center(
child: DropdownButton<String>(
value: __read(),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
_save(newValue);
_read();
});
},
items: ['one', 'two', 'three']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
This is a better approach of doing it.
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// make all of them instance variable
String dropdownValue;
SharedPreferences prefs;
final _key = 'cur_r';
#override
void initState() {
super.initState();
_read(); // read in initState
}
_read() async {
prefs = await SharedPreferences.getInstance();
setState(() {
dropdownValue = prefs.getString(_key) ?? "one"; // get the value
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("")),
body: Center(
child: DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
prefs.setString(_key, dropdownValue); // save value to SharedPreference
},
items: ['one', 'two', 'three'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
}
}

Flutter SQFlite populate a dropdown list from the database

I am trying to read the list part of a dropdown list from my SQFlite database, and can't work out how.
Query from database_helper
Future<List<Map>> getFieldData(String animal, String fieldName)
var dbClient = await db;
return await dbClient.rawQuery('SELECT lbOption FROM jkAssessData Where lbAnimal = \'${animal}\' AND lbField = \'${fieldName}\'');
}
I can get it to work with a static list of values
final List<String> _animals = <String>['CATTLE', 'SHEEP', 'GOAT'];
to populate this dropdown list
FormField<String>(
builder: (FormFieldState<String> state) {
return InputDecorator(
decoration: InputDecoration(
labelText: 'Animal Type',
errorText: state.hasError ? state.errorText : null,
),
isEmpty: _animal == '',
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: _animal,
isDense: true,
onChanged: (String newValue) {
setState(() {
assessHed.asAnimal = newValue;
_animal = newValue;
state.didChange(newValue);
});
},
items: _animals.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
},
validator: (val) {
//return val != 'SUMMARY' ? 'DETAIL' : 'Please select Type';
return null;
},
),
It's part of several fields on a Form
Start by using the call in the initState or in a onPressed of a RaisedButton.
Place this initState and _loadAnimals method in your State Widget.
List<String> _animals = <String>[];
#override
initState() {
super.initState();
// when loading your widget for the first time, loads animals from sqflite
_loadAnimals();
}
_loadAnimals() async {
// gets data from sqflite
final loadedAnimals = await getFieldData('CATTLE','Breed1');
setState(() {
// converts sqflite row data to List<String>, updating state
_animals = loadedAnimals.map((Map<dynamic, dynamic> row) => row["lbOption"] as String).toList();
});
}
Or you could change the getFieldData to return a List<String> instead of a List<Map>:
Future<List<String>> getFieldDataAsString(String animal, String fieldName) async {
var dbClient = await db;
var results = await dbClient.rawQuery('SELECT lbOption FROM jkAssessData Where lbAnimal = \'$animal\' AND lbField = \'$fieldName\'');
return results.map((Map<String, dynamic> row) {
return row["lbOption"] as String;
}).toList();
}