【问题标题】:trying to print the date尝试打印日期
【发布时间】:2023-01-20 00:25:40
【问题描述】:

我试图在选择按钮后在按钮内打印日期,但每次我将 DatatTime 名称放入 onpressed 方法时都会给我一个错误。所以我想如果我点击按钮选择一个日期之后它会在按钮中可见。通过使用扑动:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class MyAppThree extends StatefulWidget {
  const MyAppThree({super.key});

  @override
  State<StatefulWidget> createState() => _MyAppThreeState();
}
class _MyAppThreeState extends State<StatefulWidget> {
  // ignore: unused_field
  late DateTime _selectedDate;
  void _dataPicker() {
    showDateRangePicker(
            context: context,
            firstDate: DateTime(2022),
            lastDate: DateTime.now())
        .then((value) {
      if (value == null) {
        return;
      }
      setState(() {
        _selectedDate = value as DateTime;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: const Text(''),
      ),
      body: Container(
          color: Colors.black,
          height: double.infinity,
          child: Column(
            children: <Widget>[
 child: Text(
                  "${DateFormat.yMMMd().format(_selectedDate)}",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                ),
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(
                      Color.fromARGB(255, 55, 55, 55)),
                ),
              )
            ],
          )),
    );
  }
}

【问题讨论】:

  • 什么错误

标签: flutter dart


【解决方案1】:

您需要将按钮的 onPressed 属性设置为 _dataPicker 函数。此外,您需要使用默认值初始化 _selectedDate 变量,否则,在应用程序首次启动时它将为空,并且在尝试格式化时会出现错误。

 class _MyAppThreeState extends State<StatefulWidget> {
  DateTime _selectedDate = DateTime.now(); // initialize with current date

  void _dataPicker() {
    showDateRangePicker(
            context: context,
            firstDate: DateTime(2022),
            lastDate: DateTime.now())
        .then((value) {
      if (value == null) {
        return;
      }
      setState(() {
        _selectedDate = value as DateTime;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: const Text(''),
      ),
      body: Container(
          color: Colors.black,
          height: double.infinity,
          child: Column(
            children: <Widget>[
              FlatButton(
                onPressed: _dataPicker, // set onPressed property
                child: Text(
                  "${DateFormat.yMM

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2013-12-16
    • 2012-12-18
    相关资源
    最近更新 更多