首页 > 解决方案 > 颤振 | 重定向到屏幕时如何显示当前数据表中的记录

问题描述

我试图在默认情况下在下拉列表中显示当前月份(默认这个词我的意思是当用户重定向到屏幕下拉菜单将显示当前月份并且表格将显示当前月份记录。)所以,我正在显示当前月,但我的数据表没有显示记录。

我在我的 api 正文中传递月份(数字),当用户选择月份时,我定义了一个包含月份列表的列表,然后我得到它的索引并将其递增 1,因为我的列表索引从 0 开始,然后传递那个数字,这是我的 api 月份。

这是代码


String _selectedMonth;
int monthIndex;
int month;

var monthsList=<String>[
      'January',
      'Febuary',
      'March',
      'April',
      'May',
      'June',
      'July',
      'Augest',
      'September',
      'October',
      'November',
      'December'
  ];

  String getdate="";
    void _getDate() {
    final String formattedDateTime =
        DateFormat('MM').format(DateTime.now()).toString();
    _selectedMonth=DateFormat('MMMM').format(DateTime.now());
    setState(() {
      getdate = formattedDateTime;
      print(currentmonth);
     print("date  "+getdate);
    });
  }
   void initState() {
      _userDetails();
      _getDate();
      _getRecord(); 
  }

 Future<List<History>> _getRecord() async{
   Dio dio=new Dio();
   var data={
     'username':getName,
     'month':month,
     'token':getaccesstoken
   };
   return dio
    .post(localhostUrlAttendanceHistory,data: json.encode(data))
      .then((onResponse) async {
        Map<String, dynamic> map=onResponse.data;     
        List<dynamic> data = map['data'];
 
        for (var h in data) {
          History history = History(
            h["_id"],
            h["Date"], 
            h["TimeIn"], 
            h["TimeOut"],
          );
          historyList.add(history);
          id=history.id.toString();
          print("id is ");
          print(id);
        }
        return historyList;
      })
      .catchError((onerror){
        print(onerror.toString());
       
    });
  }

//datatable code

 Widget attendanceHistory(List<History> 
    historyList)=> 
   Center(
     child:Padding(padding: EdgeInsets.fromLTRB(0, 0, 18, 0),
      child:SingleChildScrollView(
         scrollDirection: Axis.vertical,
        child: SingleChildScrollView(
           scrollDirection: Axis.horizontal,          
           child:DataTable(
          decoration: BoxDecoration(border: Border.all(color: Colors.blue[500], width: 2)),
          headingRowColor: MaterialStateColor.resolveWith((states) => Colors.blue[500]),
          headingTextStyle: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
          showBottomBorder: true,
          headingRowHeight: 60,
          horizontalMargin: 7,
          columnSpacing: 15,      
          dataRowColor: MaterialStateColor.resolveWith((states) => Colors.blue[50]),
          dividerThickness: 4,        
          columns: <DataColumn>[
        DataColumn(label: Text("Date")),
        DataColumn(label: Text("Time in")),
        DataColumn(label: Text("Time out"),numeric: true),
        DataColumn(label: Text("   Edit")),
    ],
    rows:     
    historyList
      ?.map((element)=>DataRow(
        selected: true ,
      cells: <DataCell>[
      DataCell(Text(element?.date),),
      DataCell(Text(element?.timeIn)),
      DataCell(Text(element?.timeOut,)),
      DataCell(IconButton(icon:Icon(Icons.edit,color: Colors.blue,),onPressed: (){
        _getSelectedRowInfo(element?.id,element?.date,element?.timeIn,element?.timeOut);
      })


void _getSelectedRowInfo(dynamic id,dynamic date,dynamic timein,dynamic timeout) {
  
    AlertDialog alert = AlertDialog(  
    scrollable: true, 
    insetPadding: EdgeInsets.symmetric(vertical: 50),
    title: Text("Request to change time",style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue[500])),  
    
    content:Container(child: SingleChildScrollView( 
      scrollDirection: Axis.vertical,
    child:Column(children:<Widget> [     
      TextField(
        decoration: InputDecoration(labelText: date,hintText: "Date"),
        controller:dateController ,
        
      ),
      TextField(
        decoration: InputDecoration(labelText: timein,hintText: "Time in",icon: Icon(Icons.timer)),
        controller:timeinController ,
        readOnly:true,
        onTap: () async {
                  TimeOfDay pickedTime =  await showTimePicker(
                          initialTime: TimeOfDay.now(),
                          context: context,
                      );
        if(pickedTime != null ){
                      print(pickedTime.format(context));   //output 10:51 PM
                      DateTime parsedTime = DateFormat.jm().parse(pickedTime.format(context).toString());
                      //converting to DateTime so that we can further format on different pattern.
                      print(parsedTime); //output 1970-01-01 22:53:00.000
                      String formattedTime = DateFormat('HH:mm:ss').format(parsedTime);
                      print(formattedTime); //output 14:59:00
                      //DateFormat() is from intl package, you can format the time on any pattern you need.

                      setState(() {
                        timeinController.text = formattedTime; //set the value of text field. 
                      });
                  }else{
                      print("Time is not selected");
                  }
                },
      ),
      TextField(
        decoration: InputDecoration(labelText:timeout,hintText: "Time out",icon: Icon(Icons.timer_off)),
        controller:timeoutController ,
        readOnly:true,
        onTap: () async {
                  TimeOfDay pickedTime =  await showTimePicker(
                          initialTime: TimeOfDay.now(),
                          context: context,
                      );
        if(pickedTime != null ){
                      print(pickedTime.format(context));   //output 10:51 PM
                      DateTime parsedTime = DateFormat.jm().parse(pickedTime.format(context).toString());
                      //converting to DateTime so that we can further format on different pattern.
                      print(parsedTime); //output 1970-01-01 22:53:00.000
                      String formattedTime = DateFormat('HH:mm:ss').format(parsedTime);
                      print(formattedTime); //output 14:59:00
                      //DateFormat() is from intl package, you can format the time on any pattern you need.

                      setState(() {
                        timeoutController.text = formattedTime; //set the value of text field. 
                      });
                  }else{
                      print("Time is not selected");
                  }
                },
      ),
      
     ]), 
  )
  
  ),

  actions: [  
      FlatButton(  
    child: Text("Submit",style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue[500],fontSize: 20),),  
    onPressed: () { 

    getupdatedTime();
    Dio dio=new Dio();
        var data={
          'id': id,
          'token':getaccesstoken,
          'TimeIn': timeinText,
          'TimeOut':timeoutText,
          
        };
        print("token is "+getaccesstoken);
        print("submit id is  "+id);
        print(data);
        dio
        .put(localhostUrlMarkCorrection, data: json.encode(data))
          .then((onResponse) async {
            Navigator.of(context, rootNavigator: true).pop('dialog');
            dialoguebox();

            print("mark correction");
            print(onResponse.data);
            print(onResponse.statusCode);
            
            
          }).catchError((onerror){
            print(onerror.toString());
        });
      }
      
    )],  
  );  
      showDialog(  
      context: context,  
      builder: (BuildContext context) {  
        return alert;  
      },  
    );  
      
}


Widget build(BuildContext context) {
    return Scaffold(
      appBar: new MyAppBar(title: Text("My Attendance"),onpressed: (){
       Navigator.push(context, MaterialPageRoute(builder: (context)=>Profile()));
   }),
    
    drawer:Emp_DrawerCode(),
   
    body:Stack(children: <Widget>[
//here is my dropdown code
        Container(
        padding: EdgeInsets.fromLTRB(45, 80, 10, 0),
        child:
        DropdownButton<String>(
        value: _selectedMonth==null?null:monthsList[monthIndex],    
        items: 
          monthsList   
          .map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value)
            );
          }).toList(),
          hint:Text(
            "Please choose a month",
          ),
          onChanged: (String value) {
            setState(() {
              _selectedMonth=value;  //i am getting month here 
              monthIndex = monthsList.indexOf(value);  //then getting its index, so that i can find month in number
              month=monthIndex+1;  //and as index start from 0 so i increment it by 1
              print(month);
              print(_selectedMonth);
            });
          },
        ),
      ),

class History {
  final String id;
  final String date;
  final String timeIn;
  final String timeOut;
  

  History(this.id,this.date, this.timeIn, this.timeOut);

}

输出:

当我进入屏幕时,它看起来像这样

图一: 在此处输入图像描述

当我从下拉列表中选择月份时,它正在显示记录。

图二: 在此处输入图像描述

当我重定向/进入屏幕时,我想要像图 2 这样的输出,然后用户还可以从下拉列表中选择月份,表格行将根据选择月份进行修改。

如果有人知道如何做到这一点,请提供帮助。

标签: flutterdatatabledropdown

解决方案


您的代码中有一些奇怪的东西。但主要问题是那个月是空的。

您可以在需要时使用 getter 进行计算(删除旧变量)。

  int get monthIndex => return monthsList.indexOf(_selectedMonth);

  int get month => monthIndex + 1;

您也可以在执行操作之前尝试在 initState 再次计算它,这两种方式都应该修复您的错误。

我可以看到一些奇怪的行为_selectedMonth是写在 _getDate 和 initState 处。

我看不到在哪里historyList创建,但也许你需要在_getRecord.

这 if 将永远是错误if(monthsList.contains("element"))的,因为没有调用月份"element"


推荐阅读