【问题标题】:Flutter | How to display records in datatable of the current when redirected to the screen颤振 |重定向到屏幕时如何在当前的数据表中显示记录
【发布时间】:2021-06-30 07:41:14
【问题描述】:

我试图在默认情况下在下拉列表中显示当前月份(默认一词是指当用户重定向到屏幕下拉菜单时将显示当前月份,而表将显示当前月份记录。)所以,我显示当前月份,但我的数据表未显示记录。

我在我的 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);

}

输出:

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

图 1:

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

图 2:

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

如果有人知道怎么做,请帮忙。

【问题讨论】:

  • 你的意思是进入页面的时候不显示表格的行,但是因为其他原因重建之后才显示?我不太明白这个问题
  • 是的,当我进入页面行时不显示,当我从下拉列表中选择月份时,我的数据表显示记录。
  • 我用输出更新了我的问题,请检查一下。

标签: flutter datatable dropdown


【解决方案1】:

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

您可以在需要时使用 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"

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 2021-10-20
    • 2018-12-23
    • 2011-03-05
    相关资源
    最近更新 更多