首页 > 解决方案 > Flutter DateTime , 打开关闭 if

问题描述

我想在上午 09:00 - 下午 20:00 之间显示小部件,其他时间显示另一个小部件,例如现在 13:00 我的商店开张我想显示我的商店开张。

谢谢

openSaat() {
  return Container(
    width: 170,
    height: 40,
    decoration: BoxDecoration(color: Colors.black),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        CircleAvatar(
          backgroundColor: Colors.green,
          radius: 12,
        ),
        SizedBox(width: 5,),
        Text("Open Now",style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.white),)
      ],
    ),
  );
}

closeSaat() {
  return Container(
    width: 170,
    height: 40,
    decoration: BoxDecoration(color: Colors.black),
    child: Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircleAvatar(
            backgroundColor: Colors.red,
            radius: 12,
          ),
          SizedBox(width: 5,),
          Text("Close Now",style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.white),)
        ],
      ),
    ),
  );
}

标签: datetimeflutter

解决方案


@override
  Widget build(BuildContext context) {
    return new Scaffold(
    body: currentWidget()
    );
  }
  static DateTime now = DateTime.now();

   Widget currentWidget() {
    var hours = now.hour;

    if (hours >= 09 && hours < 21) {
      return _openSaat();
    } else
      return _closeSaat();
  }



Widget _openSaat() {
  return Container(
    width: 170,
    height: 40,
    decoration: BoxDecoration(color: Colors.black),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CircleAvatar(
          backgroundColor: Colors.green,
          radius: 12,
        ),
        SizedBox(
          width: 5,
        ),
        Text(
          "Open Now",
          style: TextStyle(
              fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
        )
      ],
    ),
  );
}

Widget _closeSaat() {
  return Container(
    width: 170,
    height: 40,
    decoration: BoxDecoration(color: Colors.black),
    child: Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircleAvatar(
            backgroundColor: Colors.red,
            radius: 12,
          ),
          SizedBox(
            width: 5,
          ),
          Text(
            "Close Now",
            style: TextStyle(
                fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
          )
        ],
      ),
    ),
  );
}

推荐阅读