I have a form page with some choice fields in it. On my local machine with python 3.4.3, the choice fields are working very well. On python 3.6.3, the choice fields are listing the choices but;
1. the choices are listed horizontally
2. the choices are not select-able.
3. the choices are not displayed in a field bar.
kindly see below picture copy of the output display.
choices error output
form.py
from django import forms
from django.forms import Textarea, TextInput, Select, FileInput
class PostGraduateForm(forms.ModelForm):
class Meta:
model = PostGraduate
fields = '__all__'
exclude = ['is_visible']
widgets = {
'surname': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'firstname': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'middle_name': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'email_address': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'phone_number': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'contact_address': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'course': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'nationality': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'gender': Select(attrs={'style': 'height: 30px; width: 220px;'}),
'faculty': Select(attrs={'style': 'height: 30px; width: 220px;'}),
'form_number': TextInput(attrs={'size': '27', 'style': 'height: 30px;', 'placeholder': ' E.g. PGXXXXXXXXX'}),
'department': Select(attrs={'style': 'height: 30px; width: 220px;'}),
'programme': Select(attrs={'style': 'height: 30px; width: 220px;'}),
'academic_session': TextInput(attrs={'size': '27', 'style': 'height: 30px;'}),
'passport': FileInput(attrs={'style': 'height: 30px; width: 220px;'}),
'project_proposal': FileInput(attrs={'style': 'height: 30px; width: 220px;'}),
'project_title': Textarea(attrs={'cols': 75, 'rows': 20, 'style': 'height: 110px;'}),
}
model.html
class PostGraduate(models.Model):
surname = models.CharField(max_length = 50)
firstname = models.CharField(max_length = 50)
middle_name = models.CharField(max_length = 50, blank = True)
pg_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email_address = models.EmailField(unique = True, max_length = 50)
phone_number = models.CharField(max_length = 15)
identification = models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4().hex[:6].upper(), editable=False)
FEMALE = 'FEMALE'
MALE = 'MALE'
GENDER_CHOICES = ((MALE, 'MALE'), (FEMALE, 'FEMALE'))
gender = models.CharField(max_length = 10, choices=GENDER_CHOICES, default=None)
#password = models.CharField(max_length = 50)
nationality = models.CharField(max_length = 50)
PHARMACEUTICAL_SCIENCES = 'PHARMACEUTICAL SCIENCES'
NATURAL_SCIENCE = 'NATURAL SCIENCE'
MEDICAL_LABOURATORY = 'MEDICAL LABOURATORY'
FACULTY_CHOICES = ((PHARMACEUTICAL_SCIENCES, 'PHARMACEUTICAL SCIENCES'), (NATURAL_SCIENCE, 'NATURAL SCIENCE'), (MEDICAL_LABOURATORY, 'MEDICAL LABOURATORY'))
faculty = models.CharField(max_length = 50, choices=FACULTY_CHOICES, default=None)
form_number = models.CharField(unique = True, max_length = 50)
PHARMACEUTICAL_CHEMISTRY = 'PHARMACEUTICAL CHEMISTRY'
CLINICAL_PHARMACY = 'CLINICAL PHARMACY'
PHARMACOGNOSY = 'PHARMACOGNOSY'
PHARMACEUTICAL_TECHNOLOGY = 'PHARMACEUTICAL TECHNOLOGY'
PLANT_SCIENCE = 'PLANT SCIENCE AND TECHNOLOGY'
CHEMISTRY = 'CHEMISTRY'
BIOCHEMISTRY = 'BIOCHEMISTRY'
DEPARTMENT_CHOICES = (
(PHARMACEUTICAL_CHEMISTRY, 'PHARMACEUTICAL CHEMISTRY'), (CLINICAL_PHARMACY, 'CLINICAL PHARMACY'),
(PHARMACOGNOSY, 'PHARMACOGNOSY'), (PHARMACEUTICAL_TECHNOLOGY, 'PHARMACEUTICAL TECHNOLOGY'),
(PLANT_SCIENCE, 'PLANT SCIENCE AND TECHNOLOGY'), (CHEMISTRY, 'CHEMISTRY'), (BIOCHEMISTRY, 'BIOCHEMISTRY')
)
department = models.CharField(max_length = 500, choices=DEPARTMENT_CHOICES, default=None)
MSc = 'MASTERS (MSc)'
PhD = 'DOCTOR OF PHILOSOPHY (PhD)'
PROGRAMME_CHOICES = ((MSc, 'MASTERS (MSc)'), (PhD, 'DOCTOR OF PHILOSOPHY (PhD)'))
programme = models.CharField(max_length = 500, choices=PROGRAMME_CHOICES, default=None)
academic_session = models.CharField(max_length = 500)
contact_address = models.CharField(max_length = 500)
course = models.CharField(max_length = 500)
project_title = models.TextField(blank = False)
project_proposal = models.FileField(upload_to='Post Graduate/proposal/%d-%m-%Y/', blank = False,)
passport = models.ImageField(upload_to='Post Graduate/passport/%d-%m-%Y/', blank = False,)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
is_visible = models.BooleanField(default = False)
def get_absolute_url(self):
return reverse('peruse:post_detail', kwargs={'pk': self.pg_id})
def __str__(self):
return self.surname + ' - ' + self.firstname
def id(self):
return self.id
Related
SizedBox(
// height: MediaQuery.of(context).size.height * 0.06,
width: MediaQuery.of(context).size.width * 0.4,
child: TextFormField(
// autovalidateMode: AutovalidateMode.onUserInteraction,
//FilteringTextInputFormatter.allow(RegExp("[- 0-9]")),
// inputFormatters: [
// FilteringTextInputFormatter.allow(
// RegExp("[- 0-9]")),
// LengthLimitingTextInputFormatter(10)
// ],
controller: startdatecntr,
keyboardType: TextInputType.datetime,
decoration: const InputDecoration(
errorStyle: const TextStyle(fontSize: 0.05),
prefixIcon: Icon(Icons.calendar_month),
border: OutlineInputBorder(),
hintStyle: TextStyle(fontSize: 12),
labelStyle: TextStyle(
fontSize: 12,
),
labelText: 'Start Date',
hintText: 'yyyy-MM-dd',
),
onTap: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(
1991), //DateTime.now() - not to allow to choose before today.
lastDate: DateTime(2101),
// onConfirm:widget.onChanged,
).then((pickedDate) {
if (pickedDate != null) {
// print(
// pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
String formattedDate =
DateFormat('yyyy-MM-dd')
.format(pickedDate);
print(formattedDate);
setState(() {
startdatecntr.text = formattedDate;
//set output date to TextField value.
});
print(startdatecntr.text);
} else {
print("Date is not selected");
}
});
},
validator: MultiValidator([
RequiredValidator(errorText: 'Required*')
]),
),
),
SizedBox(
width: 13,
),
SizedBox(
// height: MediaQuery.of(context).size.height * 0.06,
width: MediaQuery.of(context).size.width * 0.5,
child: TextFormField(
// maxLength: 8,
// autovalidateMode: AutovalidateMode.onUserInteraction,
autofocus: false,
controller: enddatecntr,
// inputFormatters: [
// FilteringTextInputFormatter.allow(
// RegExp("[- 0-9]")),
// LengthLimitingTextInputFormatter(10)
// ],
keyboardType: TextInputType.datetime,
decoration: const InputDecoration(
errorStyle: const TextStyle(fontSize: 0.05),
prefixIcon: Icon(Icons.calendar_month),
counterText: "",
border: OutlineInputBorder(),
hintStyle: TextStyle(fontSize: 12),
labelStyle: TextStyle(
fontSize: 12,
),
labelText: 'End Date',
hintText: ' yyyy-MM-dd'),
onTap: () async {
DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(
1991), //DateTime.now() - not to allow to choose before today.
lastDate: DateTime(2101),
// onConfirm:widget.onChanged,
).then((pickedDate) {
if (pickedDate != null) {
// print(
// pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
String formattedDate =
DateFormat('yyyy-MM-dd')
.format(pickedDate);
print(formattedDate);
setState(() {
enddatecntr.text = formattedDate;
//set output date to TextField value.
});
print(enddatecntr.text);
} else {
print("Date is not selected");
}
});
},
This may help :
return Text(
DateTime.now().toString(),
);
I use firestore to save the data. So, I use 'set'method. but It can't save the data. I get the error cannot get a field on a DocumentSnapshotPlatform which does not exist. How can I solve this error?
this my code. first code is input the title and content code. '''
class WritePage extends StatefulWidget {
#override
_WritePageState createState() => _WritePageState();
}
class _WritePageState extends State<WritePage> {
DataBase dataBase = new DataBase();
String title = ' '; //제목
String content = ' '; //내용
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("글쓰기"),
),
body: Center(
child: ListView(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.fromLTRB(20, 20, 20, 5),
child: TextField(
onChanged: (String text) {
if(text != null) {
title = text;
}else{title = 'null';}
},
keyboardType: TextInputType.multiline,
decoration: InputDecoration(
hintText: '제목을 적어주세요',
border: OutlineInputBorder(),
labelText: "제목을 입력하세요.",
),
),
),
Padding(
padding: EdgeInsets.fromLTRB(20, 20, 20, 5),
child: TextField(
onChanged: (String text) {
if(text != null) {
content = text;
}else{content = 'null';}
},
keyboardType: TextInputType.multiline,
maxLines: 20,
decoration: InputDecoration(
hintText: '내용을 적어주세요',
border: OutlineInputBorder(),
labelText: "내용을 입력하세요.",
),
),
),
Padding(
padding: EdgeInsets.fromLTRB(20, 5, 20, 5),
child: SizedBox(
height: 50,
width: 400,
child: TextButton(
onPressed: () async {
DataBase dataBase = new DataBase();
var now = DateTime.now();
await dataBase.add(title, content, '$now');
Navigator.pop(context);
},
child: Text(
'글쓰기',
style: TextStyle(color: Colors.black),
),
style: TextButton.styleFrom(primary: Colors.blue),
),
),
),
],
)
],
),
),
);
}
}
''''
this is my code2. this code is to save the data in firestore.
but it does not work.
class DataBase {
FirebaseFirestore firestore = FirebaseFirestore.instance;
String collection = '게시판';
add(String title, String content, String date_time) {
firestore
.collection('카운트')
.doc('카운트')
.get().then((DocumentSnapshot ds) {
firestore.collection(collection).doc('${ds['카운트']!}').set(
{'제목': title, '내용': content,
'날짜': date_time, 'id': ds['카운트']!});
int id = ds['카운트']! + 1;
cntupdate(id);
});
}
void cntupdate(int _id) {
firestore.collection('카운트').doc('카운트').update({'id': _id,
'카운트': _id});
}
I am very new to Dart, and coding in general. I have produced this code after watching tutorials on YouTube. For the most part, I have been able to troubleshoot most of my problems on my own, yet I cannot figure out my most recent errors. I was successful to create record in firestorm but I am unable to update it because I am not able to get Doc ID.
Here is my code:-
import 'package:flutter/material.dart';
import 'package:lms_definer/controllers/profileController.dart';
import 'package:lms_definer/controllers/textController.dart';
import 'package:get/get.dart';
import 'package:lms_definer/model/profileModel.dart';
import 'package:lms_definer/constants/constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../helper/firestore_db.dart';
class EditProfile extends StatelessWidget {
const EditProfile({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
var _textController = ProfileEdit();
return Scaffold(
body: GetX<ProfileController>(
init: Get.put<ProfileController>(ProfileController()),
builder: (ProfileController profileController) {
return Container(
child: ListView.builder(
itemCount: profileController.profiles.length,
itemBuilder: (BuildContext context, int i) {
final _profileModel = profileController.profiles[i];
setTextEditControllerValue(_textController, _profileModel);
return SafeArea(
child: Container(
padding: EdgeInsets.all(20),
child: Form(
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.fNameController
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.lNameController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Address',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.adressController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Phone Numbaer',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.phoneController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'School Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.sclNameController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Student Class',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.stdClassController,
),
SizedBox(
height: 10,
),
ElevatedButton(onPressed: () async {
ProfileModel profileModel = profileModelVal(_textController);
//await FirestoreDb.updateProfile(profileModel, documentId);
}, child: Text('Update'))
],
),
),
),
);
}),
);
},
));
}
ProfileModel profileModelVal(ProfileEdit _textController) {
final profileModel = ProfileModel(
firstName:
_textController.fNameController.text.trim(),
lastName:
_textController.lNameController.text.trim(),
parentName: _textController
.fatherNameController.text
.trim(),
phoneNumber:
_textController.phoneController.text.trim(),
address:
_textController.adressController.text.trim(),
schoolName:
_textController.sclNameController.text.trim(),
stdClass: _textController.stdClassController.text
.trim());
return profileModel;
}
void setTextEditControllerValue(ProfileEdit _textController,
ProfileModel _profileModel) {
_textController.fNameController.value =
TextEditingValue(text: _profileModel.firstName);
_textController.lNameController.value =
TextEditingValue(text: _profileModel.lastName);
_textController.fatherNameController.value =
TextEditingValue(text: _profileModel.parentName);
_textController.adressController.value =
TextEditingValue(text: _profileModel.address);
_textController.phoneController.value =
TextEditingValue(text: _profileModel.phoneNumber);
_textController.sclNameController.value =
TextEditingValue(text: _profileModel.schoolName);
_textController.stdClassController.value =
TextEditingValue(text: _profileModel.stdClass);
}
void clearTextController(ProfileEdit _textController) {
_textController.fNameController.clear();
_textController.lNameController.clear();
_textController.fatherNameController.clear();
_textController.adressController.clear();
_textController.phoneController.clear();
_textController.sclNameController.clear();
_textController.stdClassController.clear();
}
}
MY Database file:-
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:lms_definer/constants/constants.dart';
import 'package:lms_definer/model/profileModel.dart';
class FirestoreDb {
static createProfile(ProfileModel profilemodel) async {
await firebaseFirestore.collection('users').doc(auth.currentUser!.uid)
.collection('profile')
.add({
'firstName': profilemodel.firstName,
'lastName': profilemodel.lastName,
'parentName': profilemodel.parentName,
'phoneNumber': profilemodel.phoneNumber,
'address': profilemodel.address,
'schoolName': profilemodel.schoolName,
'stdClass': profilemodel.stdClass,
'createdOn': Timestamp.now(),
'isDone': true
});
}
static Stream<List<ProfileModel>> profileStream() {
return firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.snapshots()
.map((QuerySnapshot query) {
List<ProfileModel> profiles = [];
for (var profile in query.docs) {
final profileModel =
ProfileModel.fromDocmentSnapshot(documentSnapshot: profile);
profiles.add(profileModel);
}
return profiles;
});
}
static updateProfile(ProfileModel profilemodel, documentId ) {
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.doc(documentId)
.update(
{
'firstName': profilemodel.firstName,
'lastName': profilemodel.lastName,
'parentName': profilemodel.parentName,
'phoneNumber': profilemodel.phoneNumber,
'address': profilemodel.address,
'schoolName': profilemodel.schoolName,
'stdClass': profilemodel.stdClass,
'createdOn': Timestamp.now(),
}
);
}
static deleteProfile(String documentID) {
firebaseFirestore.collection('users').doc(auth.currentUser!.uid).collection(
'profile').doc(documentID).delete();
}}
I need doc Id to update the file. Please help. Thank you
static updateProfile(ProfileModel profilemodel, documentId ) {
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.get()
.then((QuerySnapshot querySnapshot) {
final docId = queryShapchot.docs.first.id;
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.doc(docId)
.update({
// Add data here
})
});
}
This should do the trick for you.
Once the user is logged in (I'm assuming the EditProfile page is only visible to logged in users) you should store the userId somewhere. This can be done using flutter_secure_storage or using an auth library like FirebaseAuth.
Then when you want to update the doc of the user, you can get the userId which was stored before to update the doc.
bi
I making database with sqlite
I was building a database and I had a problem.
That my screen full code:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math';
import 'package:socialapp/model/todo.dart';
import 'package:socialapp/widgets/database_create.dart';
class writeprofile2 extends StatefulWidget {
writeprofile2({Key key}) : super(key : key);
#override
_writeprofile2State createState() => _writeprofile2State();
}
class _writeprofile2State extends State<writeprofile2> {
final _formKey = GlobalKey<FormState>();
String _name, _age, _intro;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Builder(
builder: (context) => Center(
child: Container(
child: Container(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 70),
child: Text(
'프로필 작성',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w500,
),
),
),
Padding(
padding: EdgeInsets.only(top: 10, bottom: 50),
child: Container(
height: 1,
width: MediaQuery.of(context).size.width / 1.4,
color: Colors.black26,
),
),
Padding(
padding: EdgeInsets.only(top: 10),
child: Container(
//이름입력
width: MediaQuery.of(context).size.width / 2,
height: MediaQuery.of(context).size.height / 20,
alignment: FractionalOffset.center,
decoration: BoxDecoration(
color: Colors.black12,
borderRadius:
BorderRadius.all(const Radius.circular(20)),
),
child: TextFormField(
decoration: InputDecoration(
hintStyle: TextStyle(
fontSize: 20,
),
border: InputBorder.none,
hintText: '이름',
prefixIcon: Icon(
Icons.person_outline,
color: Colors.black,
),
),
validator: (input) {
if (input.isEmpty) {
return '이름을 입력해주세요';
}
},
onSaved: (value)=> _name = value,
),
),
),
Padding(
padding: EdgeInsets.only(top: 10),
child: Container(
width: MediaQuery.of(context).size.width / 2,
height: MediaQuery.of(context).size.height / 20,
alignment: FractionalOffset.center,
decoration: BoxDecoration(
color: Colors.black12,
borderRadius:
BorderRadius.all(const Radius.circular(20)),
),
child: TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [
WhitelistingTextInputFormatter.digitsOnly
],
decoration: InputDecoration(
hintStyle: TextStyle(
fontSize: 20,
),
border: InputBorder.none,
hintText: '나이',
prefixIcon: Icon(
Icons.label_outline,
color: Colors.black,
),
),
validator: (val) {
if (!isNumber(val)) {
return "나이를 입력해주세요";
};
},
onSaved: (value)=> _age = value,
),
),
),
Padding(
padding: EdgeInsets.only(top: 10),
child: Container(
//이름입력
width: MediaQuery.of(context).size.width / 2,
height: MediaQuery.of(context).size.height / 20,
alignment: FractionalOffset.center,
decoration: BoxDecoration(
color: Colors.black12,
borderRadius:
BorderRadius.all(const Radius.circular(20)),
),
child: TextFormField(
decoration: InputDecoration(
hintStyle: TextStyle(
fontSize: 20,
),
border: InputBorder.none,
hintText: '소개',
prefixIcon: Icon(
Icons.person_outline,
color: Colors.black,
),
),
validator: (input) {
if (input.isEmpty) {
return '자기소개';
}
},
onSaved: (value)=> _intro = value,
),
),
),
InkWell(
onTap: (){
Todo newtodo = Todo(name: _name, age: _age, intro: _intro);
DBHelper().createData(newtodo);
setState(() {
});
},
child: Padding(
padding: EdgeInsets.only(top: 50),
child: Container(
width: MediaQuery.of(context).size.width / 3,
height: MediaQuery.of(context).size.height / 20,
alignment: FractionalOffset.center,
decoration: BoxDecoration(
color: const Color.fromRGBO(250, 80, 100, 1),
borderRadius:
BorderRadius.all(const Radius.circular(30)),
),
child: Text(
"Next",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500,
letterSpacing: 0.3,
),
),
),
),
),
],
),
),
),
),
),
),
);
}
String randomTodo(){
final randomNumber = Random().nextInt(4);
String todo;
switch(randomNumber){
case 1:
todo = 'hello1';
break;
case 1:
todo = 'hello2';
break;
case 1:
todo = 'hello3';
break;
default:
todo = 'default';
break;
}
return todo;
}
}
bool isNumber(String valueNumber) {
if (valueNumber == null) {
return true;
}
final n = num.tryParse(valueNumber);
return n != null;
}
That my todo Code :
class Todo {
int id;
String name;
String intro;
String age;
Todo({
this.id,
this.name,
this.intro,
this.age,});
factory Todo.fromJson(Map<String, dynamic> json) => Todo(
id: json["id"],
intro: json["intro"],
name: json["name"],
age: json["age"],
);
Map<String, dynamic> toJson() =>
{
'id' :id,
'name': name,
'age': age,
'intro' : intro,
};
}
That database create code:
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:socialapp/model/todo.dart';
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
final String tableName = 'person';
class DBHelper{
DBHelper._();
static final DBHelper _db = DBHelper._();
factory DBHelper() => _db;
//해당 변수에 데이터베이스 정보 저장
static Database _database;
Future<Database> get database async{
if(_database != null)return _database;
_database = await initDB();
return _database;
}
initDB() async{
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'PersonProfile.db');
return await openDatabase(
path,
version: 1,
onOpen: (db) {},
onCreate: (Database db, int version) async{
await db.execute('''
CREATE TABLE $tableName
id INTEGER PRIMARY KEY,
name TEXT,
intro TEXT,
age TEXT ''');
},
);
}
createData(Todo todo)async{
final db = await database;
var res = await db.insert(tableName, todo.toJson());
return res;
}
//read
getTodo(int id) async{
final db = await database;
var res = await db.query(tableName, where: 'id = ?', whereArgs: [id]);
return res.isNotEmpty ? Todo.fromJson(res.first) : Null;
}
// getAllTodos() async{
// final db = await database;
// var res = await db.query(tableNam
// }
updateTodo(Todo todo) async{
final db = await database;
var res = await db.update(tableName, todo.toJson(),
where: 'id =?' , whereArgs: [todo.id]);
return res;
}
//Delete
deleteTodo(int id) async{
final db = await database;
db.delete(tableName, where: 'id =?', whereArgs: [id]);
}
deleteAllTodos() async{
final db =await database;
db.rawDelete("Delete * from $tableName");
}
}
error code :
>
>
> id INTEGER PRIMARY KEY,
> name TEXT,
> intro TEXT,
> age TEXT flutter: error DatabaseException(Error Domain=FMDatabase Code=1 "near "id": syntax error"
> UserInfo={NSLocalizedDescription=near "id": syntax error}) sql '
> CREATE TABLE person
> id INTEGER PRIMARY KEY,
> name TEXT,
> intro TEXT,
> age TEXT ' args []} during open, closing... [VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception:
> DatabaseException(Error Domain=FMDatabase Code=1 "near "id": syntax
> error" UserInfo={NSLocalizedDescription=near "id": syntax error}) sql
> ' CREATE TABLE person
> id INTEGER PRIMARY KEY,
> name TEXT,
> intro TEXT,
> age TEXT ' args []}
> #0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7) <asynchronous
> suspension>
> #1 SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:29:7)
> #2 SqfliteDatabaseMixin.safeInvokeMethod (package:sqflite/src/database_mixin.dart:184:15)
> #3 SqfliteDatabaseMixin.invokeExecute (package:sqflite/src/database_mixin.dart:342:12)
> #4 SqfliteDatabaseMixin.txnExecute.<anonymous closure> (package:sqflite/src/database_mixin.dart:334:14)
> #5 SqfliteDatabaseMixin.txnSynchronized (package:sqflite/src/database_mixin.dart:285:26) <asynchronous
> suspension>
> #6 SqfliteDatabaseMixin.txnWriteSynchronized (package:sqflite/src/da<…>
How can i fix this ?
You need to add parenthesis after the tableName:
CREATE TABLE $tableName(
id INTEGER PRIMARY KEY,
name TEXT,
intro TEXT,
age TEXT)
Check here:
http://www.mysqltutorial.org/mysql-create-table/
Also check the example in the sqflite plugin:
await db.execute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});
In one of my application, have seen browser gets hanging and crashing because of binding 500 000 records in the Kendo Ui-grid.
The grid contains total 20 columns and all the data return from webapi via angular in kendo grid.
it's working fine for 3 columns, when changed to 15 columns it gets a problem for above 100k records.
So I need to test how much columns and records can be hold on kendo grid. I have found there is some options available in kendo called as virtualisation to load the bulk records.
Demo Site is: http://dojo.telerik.com/#sahir/OSeRo
So in the people js have the data, I have tried to add two more columns inside that file I am getting object object in the column.
The problem occurs above 100k record binding without pagination in kendo grid. I have attached a demo project screenshot below for testing the grid.
The code is below:
<!DOCTYPE html>
<html>
<head>
<base href="">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.1.118/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.1.118/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.1.118/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.1.118/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.1.118/js/kendo.all.min.js"></script>
<script src="people.js" ></script>
</head>
<body>
<!--<script src="../content/shared/js/people.js"></script>-->
<div id="example">
<div id="message" class="box wide"></div>
<div id="grid"></div>
<script>
$(function() {
var count = 500000;
if (kendo.support.browser.msie) {
if (kendo.support.browser.version < 10) {
count = 100000;
} else {
count = 200000;
}
}
$("#message").text(kendo.format("Generating {0} items", count));
generatePeople(count, function(data) {
var initStart;
var renderStart;
$("#message").text("");
setTimeout(function() {
initStart = new Date();
$("#grid").kendoGrid({
dataSource: {
data: data,
pageSize: 20
},
height: 543,
scrollable: {
virtual: true
},
pageable: {
numeric: false,
previousNext: false,
messages: {
display: "Showing {2} data items"
}
},
columns: [
{ field: "Id", title: "ID", width: "110px" },
{ field: "FirstName", title: "First Name", width: "130px" },
{ field: "LastName", title: "Last Name", width: "130px" },
{ field: "City", title: "City", width: "130px" },
{ field: "CashId", title: "Cash ID", width: "130px" },
{ field: "Title" },
{ field: "productName"},
]
});
initEnd = new Date();
$("#message").text(kendo.format("Kendo UI Grid bound to {0} items in {1} milliseconds", count, initEnd - initStart));
});
});
});
</script>
</div>
</body>
</html>
custom people.js
var firstNames = ["Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Laura", "Anne", "Nige"],
lastNames = ["Davolio", "Fuller", "Leverling", "Peacock", "Buchanan", "Suyama", "King", "Callahan", "Dodsworth", "White"],
cities = ["Seattle", "Tacoma", "Kirkland", "Redmond", "London", "Philadelphia", "New York", "Seattle", "London", "Boston"],
titles = ["Accountant", "Vice President, Sales", "Sales Representative", "Technical Support", "Sales Manager", "Web Designer",
"Software Developer", "Inside Sales Coordinator", "Chief Techical Officer", "Chief Execute Officer"],
productNames =["Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Laura", "Anne", "Nige"]
birthDates = [new Date("1948/12/08"), new Date("1952/02/19"), new Date("1963/08/30"), new Date("1937/09/19"), new Date("1955/03/04"), new Date("1963/07/02"), new Date("1960/05/29"), new Date("1958/01/09"), new Date("1966/01/27"), new Date("1966/03/27")],
cashId= ["Accountant", "Vice President, Sales", "Sales Representative", "Technical Support", "Sales Manager", "Web Designer",
"Software Developer", "Inside Sales Coordinator", "Chief Techical Officer", "Chief Execute Officer"];
function createRandomData(count) {
var data = [],
now = new Date();
for (var i = 0; i < count; i++) {
var firstName = firstNames[Math.floor(Math.random() * firstNames.length)],
lastName = lastNames[Math.floor(Math.random() * lastNames.length)],
city = cities[Math.floor(Math.random() * cities.length)],
title = titles[Math.floor(Math.random() * titles.length)],
birthDate = birthDates[Math.floor(Math.random() * birthDates.length)],
CashId = cashId[Math.floor(Math.random() * cashId.length)],
age = now.getFullYear() - birthDate.getFullYear(),
productName = productNames[Math.floor(Math.random() * productNames.length)];
data.push({
Id: i + 1,
FirstName: firstName,
LastName: lastName,
City: city,
Title: title,
BirthDate: birthDate,
CashId:cashId,
Age: age,
productName:productNames
});
}
console.log(data);
return data;
}
function generatePeople(itemCount, callback) {
var data = [],
delay = 25,
interval = 500,
starttime;
var now = new Date();
setTimeout(function() {
starttime = +new Date();
do {
var firstName = firstNames[Math.floor(Math.random() * firstNames.length)],
lastName = lastNames[Math.floor(Math.random() * lastNames.length)],
city = cities[Math.floor(Math.random() * cities.length)],
title = titles[Math.floor(Math.random() * titles.length)],
birthDate = birthDates[Math.floor(Math.random() * birthDates.length)],
CashId= cashId[Math.floor(Math.random() * cashId.length)],
age = now.getFullYear() - birthDate.getFullYear(),
productName = productNames[Math.floor(Math.random() * productNames.length)];
data.push({
Id: data.length + 1,
FirstName: firstName,
LastName: lastName,
City: city,
Title: title,
BirthDate: birthDate,
CashId:cashId,
Age: age,
productName:productNames
});
} while(data.length < itemCount && +new Date() - starttime < interval);
if (data.length < itemCount) {
setTimeout(arguments.callee, delay);
} else {
callback(data);
}
}, delay);
}
Update people.js on line 68 (cashId to CashId) and 70 (productNames to productName)
data.push({
Id: data.length + 1,
FirstName: firstName,
LastName: lastName,
City: city,
Title: title,
BirthDate: birthDate,
CashId:CashId,
Age: age,
productName:productName
});