i want to get a listview of data in sqflite

Viewed 47

I am new to flutter and i want to create two databases for each. One is a text from dropdown list. I have a problem in listing the data from database and it shows 'data!= null'.

This is my listview code.

    import 'package:flutter/material.dart';
import 'datamodel2.dart';
import 'function2.dart';

class ListStaffWidget extends StatelessWidget {
  const ListStaffWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: stafflistNotifier,
      builder: (BuildContext ctxx,
          List<StaffModel> staffList,
          Widget? child){
        return ListView.separated(
          itemBuilder: (ctxx, indexe) {
            final datas = staffList[indexe];
            // print("data>>> ${data.sname.toString()}");
            // Text(staffList[index]!=null?);
            return ListTile(
              title: Text(datas.sname),
              isThreeLine: true,
              subtitle: Text(datas.sage),
              trailing: IconButton(onPressed: (){
                if (datas.id != null){
                  deleteStaff(datas.id!);
                }else{
                  print("Staff is null, unable to delete");
                }
              },
                icon: Icon(Icons.delete,color: Colors.red,),),
            );
          },
          separatorBuilder: (ctxx, indexe){
            return Divider();
          },
          itemCount: staffList.length,
        );
      },
    );
  }
}   

This is the function

    import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:sqflite/sqflite.dart';
import 'datamodel2.dart';

ValueNotifier<List<StaffModel>> stafflistNotifier = ValueNotifier([]);

 late Database _db;

Future<void> initializeDataBases()async{
  _db = await openDatabase('staff.db',
      version: 1,
      onCreate: (Database db, int version) async{
        await db.execute(
            'CREATE TABLE staff(id INTEGER PRIMARY KEY, sname TEXT, sage TEXT) ');
      });
}

Future<void> addStaff(StaffModel values) async{
  await _db.rawQuery(
      'INSERT INTO staff(sname, sage) VALUES(?,?)',[values.sname, values.sage]);
  getAllStaff();
}

Future<void> getAllStaff() async{
  final _values = await _db.rawQuery('SELECT * FROM staff');
  print(_values);
  stafflistNotifier.value.clear();
  _values.forEach((map){
    final staff = StaffModel.fromMap(map);
    stafflistNotifier.value.add(staff);
    stafflistNotifier.notifyListeners();
  });
}

Future<void> deleteStaff(int id) async{
  await _db.rawDelete('DELETE FROM staff WHERE id = ?', [id]);
  getAllStaff();
}    

This is dropdown code.

   import 'package:dropdownfield2/dropdownfield2.dart';
import 'package:flutter/material.dart';

import 'datamodel3.dart';
import 'function3.dart';

class Subscreen extends StatefulWidget {
 const Subscreen({Key? key}) : super(key: key);

 @override
 State<Subscreen> createState() => _SubscreenState();
}

class _SubscreenState extends State<Subscreen> {
 late String _myActivity;
 late String _myActivityResult;
 final formKey = new GlobalKey<FormState>();
 String itemtitle = '';
 final subjectselected = TextEditingController();

 @override
 void initState() {
   super.initState();
   _myActivity = '';
   _myActivityResult = '';
 }

 _saveForm() {
   var form = formKey.currentState;
   if (form!.validate()) {
     form.save();
     setState(() {
       _myActivityResult = _myActivity;
     });
   }
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: Text("Select Subject"),
       centerTitle: true,
     ),
     body: Container(
       height: MediaQuery.of(context).size.height,
       width: MediaQuery.of(context).size.width,
       padding: EdgeInsets.all(20),
       child: Column(
         mainAxisAlignment: MainAxisAlignment.center,
         crossAxisAlignment: CrossAxisAlignment.stretch,
         children: [
           Text("Select Subject",
           style: TextStyle(
             fontSize: 20,
           ),
           textAlign: TextAlign.center,),
           SizedBox(height: 20,),
           DropDownField(
             controller: subjectselected,
             hintText: "Select Subject",
             enabled: true,
             items: subject,
             itemsVisibleInDropdown: 7,
             onValueChanged: (value){
               setState(() {
                 selectsubject = value;
               });
             },
           ),
           SizedBox(height: 30,),
                 Text(
               selectsubject,
             style: TextStyle(
               fontSize: 20
             ),
             textAlign: TextAlign.center,),
                 // ListSubjectWidget()
                 // Expanded(child: ListSubjectWidget()),
           ]
       ),
     ),
   );

 }
}    


String selectsubject = "";

final subjectselected = TextEditingController();

 List<String> subject = [
   "Maths",
   "Physics",
   "Chemistry",
   "Biology",
   "Electronics",
   "English",
   "Hindi",
   "Social",
   "PT",
   "Computer",
 ];

Future<void> onAddSubjectButtonClicked() async {
 final _sub = subjectselected.text.trim();
 if (_sub.isEmpty) {
   return;
 }
 // print('$_name $_age');

 final _subject = SubjectModel(sub: _sub);
 addSubject(_subject);
}    
  

I need both data from staff and dropdown to be listed in listview.separated.

0 Answers
Related