我想获得 sqflite 中数据的列表视图

发布于 2025-01-15 20:27:08 字数 5398 浏览 1 评论 0原文

我是颤振新手,我想为每个数据库创建两个数据库。一种是下拉列表中的文本。我在列出数据库中的数据时遇到问题,它显示“data!= null”。

这是我的列表视图代码。

    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,
        );
      },
    );
  }
}   

这是函数

    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();
}    

这是下拉代码。

   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);
}    
  

我需要将员工数据和下拉列表都列在 listview.separated 中。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文