程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在颤振中构建排序的列表视图(按日期排序)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何在颤振中构建排序的列表视图(按日期排序)?

开发过程中遇到如何在颤振中构建排序的列表视图(按日期排序)的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在颤振中构建排序的列表视图(按日期排序)的解决方法建议,希望对你解决如何在颤振中构建排序的列表视图(按日期排序)有所启发或帮助;

我想显示数据库中的列表视图。存储在“note”表中的笔记成功显示。我想按日期显示它。即最近的顶部和后面的(未来的)。如果日期是明天,那么它应该在顶部,后天应该在它下面。如果日期相同,我想按优先级对它们进行排序。谁能帮帮我吗。 (如果您使用任何其他可以同时接受日期和时间的日期和时间选择器也会有所帮助)。在我的情况下,表日历只接受日期。我将日期存储为文本(我不知道它是否正确) new_note.dart// 这是我向数据库添加新笔记的地方。

import 'package:Flutter/material.dart';
import 'package:Flutter/painTing.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:Flutter_speed_dial/Flutter_speed_dial.dart';
import 'package:smooth_star_raTing/smooth_star_raTing.dart';
import 'package:intl/intl.dart';
import 'package:vers2cts/models/color_dropdown.dart';
import 'package:vers2cts/models/customer_model.dart';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/services/db_service.dart';
import 'package:vers2cts/utils/form_Helper.dart';

class NewNote extends StatefulWidget{
  final NoteModel note;
  final CustomerModel customer;
  NewNote(this.customer,this. notE);
  @overrIDe
  State<StatefulWidget> createState() {
    return New_NoteState(this.customer,this.notE);
  }

}
class New_NoteState extends State<NewNote> with SingleTickerProvIDerStatemixin{
  New_NoteState(this.customer,this.notE);
  NoteModel note=new NoteModel();
  CustomerModel customer=new CustomerModel();
  TextEdiTingController NoteController=TextEdiTingController();
  TextEdiTingController custfnameController = TextEdiTingController();
  datetiR_318_11845@e _reminderDate = datetiR_318_11845@e.Now();
  datetiR_318_11845@e _@R_673_10288@ctedDay = datetiR_318_11845@e.Now();
  DBservice dbservice=new DBservice();
  double _height;
  double _wIDth;
  dynamic currentTime = DateFormat.jm().format(datetiR_318_11845@e.Now());

  String _setTime,_setDate;

  String _hour,_minute,_time;

  String datetiR_318_11845@e;

  datetiR_318_11845@e @R_673_10288@ctedDate = datetiR_318_11845@e.Now();

  TimeOfDay @R_673_10288@ctedTime = TimeOfDay(hour: 00,minute: 00);

  TextEdiTingController _dateController = TextEdiTingController();
  TextEdiTingController _timeController = TextEdiTingController();
  SpeedDial _speedDial(){
    return SpeedDial(
      animateDicon: AnimateDicons.add_event,animateDicontheme: IconthemeData(size: 24.0),BACkgroundcolor: colors.yellow,curve: Curves.easeInCirc,children: [
        SpeedDialChild(
          child: Icon(Icons.LOCATIOn_on,color: colors.yellow,),label: 'Add LOCATIOn',SpeedDialChild(
          child: Icon(Icons.keyboard_voicE),label: 'Add voice',SpeedDialChild(
          child: Icon(Icons.attachment_outlined,color :colors.redAccent),label: 'Add file',SpeedDialChild(
          child: Icon(Icons.image,color: colors.lightBlue,label: 'Add Image',],);
  }
  //for Switch
  bool isSwitched = false;
  var textValue = 'Switch is OFF';

  voID toggleSwitch(bool value) {

    if(isSwitched == falsE)
    {
      setState(() {
        isSwitched = true;
        note.rmnd_ind=1;
      });
    }
    else
    {
      setState(() {
        isSwitched = false;
        note.rmnd_ind=0;
      });
    }
  }
  Future<Null> _@R_673_10288@ctTime(BuildContext context) async {
    final TimeOfDay picked = await showTimePicker(
      context: context,initialTime: @R_673_10288@ctedTime,);
    if (picked != null)
      setState(() {
        @R_673_10288@ctedTime = picked;
        _hour = @R_673_10288@ctedTime.hour.toString();
        _minute = @R_673_10288@ctedTime.minute.toString();
        _time = _hour + ' : ' + _minute;
        _timeController.text = _time;
      });
  }
  @overrIDe
  voID initState() {
    _timeController.text=currentTime;
    super.initState();
  }

  @overrIDe
  Widget build(BuildContext context) {
    var height = Mediaquery.of(context).size.height;
    var wIDth = Mediaquery.of(context).size.wIDth;
    var name=customer.first_name+" "+customer.last_name;
    custfnameController.text = name;
    String _chosenValue;
    return WillPopScope(

        onWillPop: () {navigationbar
          movetoLastScreen();
        },child: Scaffold(
          appbar:Appbar(),body:ListVIEw(
            children: <Widget>[
              SizedBox(
                height: 2.0,TextFIEld(controller: custfnameController,style: TextStyle(
                      FontSize: 20.0,FontWeight: FontWeight.bold),textAlign: TextAlign.center),Align(
                alignment: Alignment.centerleft,child: Text("Add New",textAlign: TextAlign.left,style: TextStyle(FontSize: 22,SizedBox(
                height: 2.0,divIDer(),padding(
                padding: const EdgeInsets.all(8.0),child: TextFIEld(
                  controller: NoteController,decoration: inputdecoration(
                      border: Outlineinputborder(
                        bordersIDe: const bordersIDe(wIDth: 2.0),)),keyboardType: TexTinputType.multiline,minlines: 5,//normal texTinputFIEld will be displayed
                  maxlines: 5,// when user presses enter it will adapt to it
                  onChanged: (value) {
                    this.note.note = value;
                  },padding(
                padding: const EdgeInsets.all(10.0),child: tableCalendar(
                  @R_673_10288@ctedDayPreDicate: (day) {
                    return isSameDay(_@R_673_10288@ctedDay,day);
                  },onDay@R_673_10288@cted: (SELEctedDay,focusedDay) {
                    setState(() {
                      _@R_673_10288@ctedDay=@R_673_10288@ctedDay;
                      String _reminderDate = DateFormat('dd-MM-yyyy').format(_@R_673_10288@ctedDay);
                      note.actn_on=_reminderDate.toString();

                    });
                  },// Set initial date

                  focusedDay: datetiR_318_11845@e.Now(),firstDay: datetiR_318_11845@e.utc(2010,10,16),lastDay: datetiR_318_11845@e.utc(2030,3,14),Row(
                children: <Widget>[
                  Expanded(child: padding(
                    padding: const EdgeInsets.all(10.0),child: Text("Set time",style: TextStyle(FontSize: 20),Expanded(
                    child: padding(
                      padding: const EdgeInsets.all(10.0),child: InkWell(
                      onTap: () {
                        _@R_673_10288@ctTime(context);
                      },child: TextFormFIEld(
                          style: TextStyle(FontSize: 30),textAlign: TextAlign.center,onSaved: (String val) {
                            _setTime = val;
                          },enabled: false,keyboardType: TexTinputType.text,controller: _timeController,]
              ),SizedBox(
                height: height*0.03,child: Row(
                  children: <Widget>[
                    Text("Remind me",padding(
                      padding: const EdgeInsets.only(left:80.0),child: Container(
                        child: Switch(
                          onChanged: toggleSwitch,value: isSwitched,child: Row(mainAxisAlignment: MainAxisAlignment.start,children:<Widget>[
                      Text("Priority",style: TextStyle(FontSize: 20.0),padding(
                        padding: const EdgeInsets.only(left:20.0),child: Container(
                          child: SmoothStarraTing(
                            size: height=50.0,allowHalfraTing: false,onRated: (value) {
                              this.note.prty=value;
                              print("raTing value -> $value");

                            },)]),SizedBox(
                height: height*0.08,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,on@R_403_4848@: (){
                      setState(() {
                        _save();
                      });
                    },floaTingActionbutton:_speedDial(),));

  }
  voID movetoLastScreen() {
    Navigator.pop(context,truE);
  }

  voID _save() async {
    movetoLastScreen();
    note.cust_ID=customer.cust_ID;
    print(customer.cust_ID);
    print(note.cust_ID);
    int result;
    if (note.note_ID != null) {  // Case 1: update operation
      result = await dbservice.updateNote(notE);
    } else { 
      result = await dbservice.insertNote(notE);
    }

    if (result != 0) { 
      FormHelper.showAlertDialog(context,'Status','Note Saved successfully');
    } else {
      FormHelper.showAlertDialog(context,'Problem Saving Note');
    }
  }
}

note_info.dart // 这是显示列表视图的屏幕

import 'dart:io';
import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/models/customer_model.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(this. customer,this.appbartitlE);

  @overrIDe
  State<StatefulWidget> createState() {
   return Note_InfoState(this. customer,this.appbartitlE);
  }

}

class Note_InfoState extends State<Note_Info> {
  DBservice dbservice = DBservice();
  List<NoteModel> noteList;
  int count = 0;

  static final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
  NoteModel note=NoteModel();
  String appbartitle;
  CustomerModel customer=new CustomerModel();
  Note_InfoState(this.customer,this.appbartitlE);

  bool rememberMe = false;
  datetiR_318_11845@e _date = datetiR_318_11845@e.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,on@R_403_4848@: () {
                    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,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,on@R_403_4848@: () {

                            },SizedBox(
                      height: 50,child: Appbar(
                        bottom: Tabbar(
                          tabs: [
                            Tab(
                              text: "All",Tab(
                              text: "Pending",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,child: Raisedbutton(
                          elevation: 2,shape: RoundedRectangleborder(
                              borderRadius: borderRadius.circular(20)),color: theme
                              .of(context)
                              .priMarycolorDark,on@R_403_4848@: () {
                            setState(() {
                              //_reset();
                            });
                          },)
        ));
  }

  Widget ImageProfile(String fileName) {
    return Center(
      child: CircleAvatar(
          radius: 80.0,BACkgroundImage:  filename == null
              ?Assetimage('images/person_icon.jpg')
              :fileImage(file(customer.cust_photo))),);

  }


  ListVIEw getNoteListVIEw() {

    TextStyle titleStyle = theme.of(context).texttheme.subhead;

    return ListVIEw.builder(
      itemCount: count,itemBuilder: (BuildContext context,int position) {

        return Card(
          color: colors.white,elevation: 2.0,child: ListTile(
            title: Text(this.noteList[position].note,style: titleStyle,//subtitle: Text(this.customerList[position].datE),Trailing: GestureDetector(
              child: Icon(Icons.delete,color: colors.grey,onTap: () {
                //  _delete(context,customerList[position]);
              },onTap: () {
              //navigatetoDetail(this.customerList[position],'Edit ');

            },);
      },);
  }
  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 @R_673_10288@ctedinDices = [];
  ListVIEw getNotecheckList() {
    return ListVIEw.builder(
        itemCount: count,int position) {
        return Card(
          color: colors.white,child: checkBoxListTile(
            title: Text(this.noteList[position].notE),subtitle: Text(this.noteList[position].actn_on),value: @R_673_10288@ctedinDices.contains(position),onChanged: (_) {
              if (SELEctedinDices.contains(position)) {
                @R_673_10288@ctedinDices.remove(position);// un@R_673_10288@ct
              } else {
                @R_673_10288@ctedinDices.add(position);  // @R_673_10288@ct

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

  }

note_model.dart

import 'model.dart';

class NoteModel extends Model {
  static String table = 'note';
  bool is@R_673_10288@cted=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_service.dart

import 'package:vers2cts/models/note_model.dart';
import 'package:vers2cts/utils/db_Helper.dart';
class DBservice {
  Future<int> insertNote(NoteModel notE) async {
    await DB.init();
    var result = await DB.insert(NoteModel.table,notE);
    return result;
  }

  Future<List<Map<String,dynamic>>> getNoteMapList() async {
    await DB.init();
    var result = await DB.query(NoteModel.tablE);
    return result;
  }

  Future<List<NoteModel>> getCustomerNotes(int customer) async {
    await DB.init();
    var res = await DB.rawquery("note WHERE cust_ID = '$customer'");
    int count = res.length;
    List<NoteModel> noteList = List<NoteModel>();
    for (int i = 0; i < count; i++) {
      noteList.add(NoteModel.fromMap(res[i]));
    }
    return noteList;
  }
}

db_Helper.dart actn_on 保存日期,prty 保存优先级

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<List<Map<String,dynamic>>> rawquery(String table) async =>
      _db.query(tablE);
}

解决方法

谢谢 DarShan 我得到了我的答案,我只需要在查询中使用 ORDER BY

Future<List<NoteModel>> getCustomerNotes(int customer) async {
    await DB.init();
    var res = await DB.rawQuery("note WHERE cust_id = '$customer' ORDER BY actn_on ASC,prty DESc;");
    int count = res.length;
    List<NoteModel> notelist = List<NoteModel>();
    // For loop to create a 'Note List' from a 'Map List'
    for (int i = 0; i < count; i++) {
      notelist.add(NoteModel.fromMap(res[i]));
    }
    return notelist;
  }

大佬总结

以上是大佬教程为你收集整理的如何在颤振中构建排序的列表视图(按日期排序)全部内容,希望文章能够帮你解决如何在颤振中构建排序的列表视图(按日期排序)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。