如何使用颤振中的复选框更新数据库

问题描述

我想根据复选框简单地更新数据库中的表,但它太困难了。找不到一个答案。关于颤振的可用材料非常少。我在 listview 中有一个笔记列表,这是我从数据库中的笔记表中获取的。列表视图包含复选框。当我点击保存按钮时,我想将该特定笔记的笔记表中的状态列更新为“已完成”。谁能告诉我该怎么做。我已经发布了同样的问题,但我无法在 stackoverflow 上找到我自己的问题。

note_info.dart

import 'dart:io';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/screens/people_list.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/db_helper.dart';
import 'package:Flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:vers2cts/utils/form_helper.dart';

import 'new_note.dart';


class Note_Info extends StatefulWidget{
  final String appBarTitle;
  final CustomerModel customer;


  //Note_Info();
  Note_Info(this. customer,this.appBarTitle);

  @override
  State<StatefulWidget> createState() {
    //return Note_InfoState();
   return Note_InfoState(this. customer,this.appBarTitle);
  }

}

class Note_InfoState extends State<Note_Info> {
  DBService dbService = DBService();
  List<NoteModel> noteList;
  int count = 0;
  int nid;
  String status;
  static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<
      ScaffoldState>();
  NoteModel note = NoteModel();
  String appBarTitle;
  CustomerModel customer = new CustomerModel();

  Note_InfoState(this.customer,this.appBarTitle);

  // Note_InfoState();

  bool rememberMe = false;
  DateTime _date = DateTime.Now();
  TextEditingController custfNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    updateListView();
    if (noteList == null) {
      noteList = List<NoteModel>();
      updateListView();
    }

    TextStyle titleStyle = Theme
        .of(context)
        .textTheme
        .subhead;
    var height = MediaQuery
        .of(context)
        .size
        .height;
    var name = customer.first_name + " " + customer.last_name;
    custfNameController.text = name;

    return DefaultTabController(
        length: 4,child: Scaffold(
            appBar: AppBar(
              actions: [
                IconButton(
                  icon: Icon(
                    Icons.add,),onpressed: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (BuildContext context) =>
                            NewNote(customer,note)));
                  },)
              ],body: Container(
              child: Column(
                  children: <Widget>[
                    TextField(controller: custfNameController,style: TextStyle(
                            fontSize: 20.0,fontWeight: FontWeight.bold),textAlign: TextAlign.center),Padding(
                      padding: const EdgeInsets.all(15.0),child: Row(children: [
                        ImageProfile(customer.cust_photo),Padding(
                          padding: const EdgeInsets.only(left: 30.0),child: IconButton(
                            icon: Icon(
                              Icons.call,color: Colors.green,size: 45,onpressed: () {

                            },],SizedBox(
                      height: 50,child: AppBar(
                        bottom: TabBar(
                          tabs: [
                            Tab(
                              text: "All",//icon: Icon(Icons.directions_bike),Tab(
                              text: "Pending",// icon: Icon(Icons.directions_car,Tab(
                              text: "Cancelled",Tab(
                              text: "Completed",// create widgets for each tab bar here
                    Expanded(
                      child: TabBarView(
                        children: [
                          // first tab bar view widget
                          Container(
                              child: getNotecheckList()
                          ),// second tab bar viiew widget
                          Container(

                          ),Container(
                            child: Center(
                              child: Text(
                                'Cancelled',Container(

                            child: Center(
                              child: Text(
                                'Completed',Padding(
                      padding: const EdgeInsets.all(8.0),child: Container(
                        height: 55.0,width: 200,child: RaisedButton(
                          elevation: 2,shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20)),color: Theme
                              .of(context)
                              .primaryColorDark,textColor: Colors.white,child: Text('Save',textScaleFactor: 1.5,onpressed: () {
                            setState(() {
                              _save();
                            });
                          },]
              ),)
        ));
  }

  Widget ImageProfile(String fileName) {
    return Center(
      child: CircleAvatar(
          radius: 80.0,backgroundImage: fileName == null
              ? Assetimage('images/person_icon.jpg')
              : FileImage(File(customer.cust_photo))),);
  }


 

  Future<void> updateListView() {
    final Future<Database> dbFuture = DB.init();
    dbFuture.then((database) {
      int cid = customer.cust_id;

      Future<List<NoteModel>> noteListFuture = dbService.getCustomerNotes(cid);
      noteListFuture.then((noteList) {
        setState(() {
          this.noteList = noteList;
          this.count = noteList.length;
        });
      });
    });
  }

  int _isChecked = -1;
  var selectedindices = [];

  ListView getNotecheckList() {
    return ListView.builder(
      itemCount: count,itemBuilder: (BuildContext context,int position) {
        return Card(
          color: Colors.white,elevation: 2.0,child: CheckBoxListTile(
            title: Text(this.noteList[position].note),subtitle: Text(this.noteList[position].actn_on),//secondary: const Icon(Icons.web),value: selectedindices.contains(position),onChanged: (_) {
              if (selectedindices.contains(position)) {
                selectedindices.remove(position); // unselect
              } else {
                selectedindices.add(position); // select
                

              }
            },controlAffinity: ListTileControlAffinity.leading,);
      },);
  }

  void _save() async {
    try {
      int result = await dbService.updateNote(note);
      if (result != 0) {
        FormHelper.showMessage(
          context,"SQFLITE CRUD","Data updated Successfully","Ok",() {
            Navigator.push(
              context,MaterialPageRoute(
                builder: (context) => People_List(),);
          },);
      } else
        FormHelper.showAlertDialog(context,'Status','Problem Saving Note');
    }
    catch(e)
    {
      print('exception');
      print(e);
    }

    /* int result;
    result = await dbService.updateNoteCompl(note,nid);

    if (result != 0) {  // Success
      FormHelper.showAlertDialog(context,'Note Saved Successfully');
    } else {  // Failure
      FormHelper.showAlertDialog(context,'Problem Saving Note');*/
  }


}

note_model.dart

import 'model.dart';

class NoteModel extends Model {
  static String table = 'note';
  bool isSelected=false;
  int note_id;
  int cust_id;
  String note;
  String actn_on;
  int rmnd_ind;
  double prty;
  String colr;
  String sts;

  int id;
  String cre_date;
  String cre_by;
  String mod_date;
  String mod_by;
  int txn_id;
  int delete_ind;

  NoteModel({
    this.note_id,this.cust_id,this.note,this.actn_on,this.rmnd_ind,this.prty,this.colr,this.sts,this.id,this.cre_date,this.cre_by,this.mod_date,this.mod_by,this.txn_id,this.delete_ind
  });

  static NoteModel fromMap(Map<String,dynamic> map) {
    return NoteModel(
      note_id: map["note_id"],cust_id: map['cust_id'],note: map['note'].toString(),actn_on: map['actn_on'].toString(),rmnd_ind: map['rmnd_ind'],prty: map['prty'],colr: map['colr'].toString(),sts: map['sts'].toString(),id: map['id'],cre_date: map['cre_date'].toString(),cre_by: map['cre_by'].toString(),mod_date: map['mod_date'].toString(),mod_by: map['mod_by'].toString(),txn_id: map['txn_id'],delete_ind: map['delete_ind'],);
  }

  Map<String,dynamic> toMap() {
    Map<String,dynamic> map = {
      'note_id': note_id,'cust_id': cust_id,'note':note,'actn_on': actn_on,'rmnd_ind': rmnd_ind,'prty': prty,'colr': colr,'sts':sts,'id': id,'cre_date': cre_date,'cre_by': cre_by,'mod_date':mod_date,'mod_by':mod_by,'txn_id':txn_id,'delete_ind': delete_ind

    };

    if (note_id != null) {
      map['note_id'] = note_id;
    }
    return map;
  }
}

db_helper.dart

import 'dart:async';
import 'package:vers2cts/models/model.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';

abstract class DB {
  static Database _db;

  static int get _version => 1;

  static Future<Database> init() async {
    if (_db != null) {
      return _db;
    }

    try {
      var databasesPath = await getDatabasesPath();
      String _path = p.join(databasesPath,'CTS.db');
      _db = await openDatabase(_path,version: _version,onCreate: onCreate);
      print('db location:'+_path);

    } catch (ex) {
      print(ex);
    }
  }

  static void onCreate(Database db,int version) async {
    
    await db.execute(
        'CREATE TABLE note (note_id INTEGER PRIMARY KEY,cust_id INTEGER,'
            'note TEXT,'
            'actn_on TEXT,rmnd_ind INTEGER,prty REAL,colr TEXT,'
            'sts TEXT,'
            'id INTEGER,cre_date TEXT,cre_by TEXT,mod_date TEXT,mod_by TEXT,txn_id INTEGER,delete_ind INTEGER)');        
  }

  static Future<List<Map<String,dynamic>>> query(String table) async =>
      _db.query(table);

  static Future<int> insert(String table,Model model) async =>
      await _db.insert(table,model.toMap());

  static Future<int> update(String table,Model model) async => await _db
      .update(table,model.toMap(),where: 'id = ?',whereArgs: [model.id]);

  static Future<int> updateNote(String table,where: 'note_id = ?',whereArgs: [model.note_id]);


  static Future<int> delete(String table,Model model) async =>
      await _db.delete(table,whereArgs: [model.id]);

  static Future<int> deleteCustomer(String table,where: 'custId = ?',whereArgs: [model.cust_id]);

  static Future<Batch> batch() async => _db.batch();

  static Future<List<Map<String,dynamic>>> rawQuery(String table) async =>
      _db.query(table);


}

db_service.dart

import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/utils/db_helper.dart';

class DBService {
Future<int> updateNote(NoteModel note) async {
    await DB.init();
    var result = await DB.updateNote(NoteModel.table,note);
    return result;
  }
}

解决方法

您可以使用提供程序包来监听您要在数据库中更新的值的任何更改,如下所示:

创建一个类,您可以在其中操作所需的模型。

class NoteModelData extends ChangeNotifier {

  void updateValueInDB(bool value) {
    value = !value;
    // here you update your database with the new value
    notifyListeners();
  }
}

然后在你的 main.dart 上注册你的模型提供者

runApp(
  ChangeNotifierProvider(
    create: (context) => NoteModelData(),child: MyApp(),),);

在此之后,您可以在复选框的 onPressed 上调用该函数,提供者将告知任何消费者有关更改的信息。

希望能帮到你。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...