Flutter 自带日期组件

Posted 飞翔的熊blabla

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter 自带日期组件相关的知识,希望对你有一定的参考价值。

main.dart

import 'package:flutter/material.dart';
 
import 'package:flutter_localizations/flutter_localizations.dart';
 
import 'package:date_format/date_format.dart';
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
 
    
      //配置如下两个国际化的参数
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
    
      home: Scaffold(
        //标题栏
        appBar: AppBar(
          title: Text("Flutter Demo"),
        ),
        //内容区域
        body: DatePickerPubPage(),
      ),
      //主题
      theme: ThemeData(primarySwatch: Colors.red),
    );
  }
}
 
class DatePickerPubPage extends StatefulWidget {
  @override
  _DatePickerPubPageState createState() => _DatePickerPubPageState();
}
 
class _DatePickerPubPageState extends State<DatePickerPubPage> {
  DateTime _selectedDateTime = DateTime.now(); //获取当前日期
 
  var nowTime = DateTime.now(); //获取当前时间
 
  DateTime _selectedDate = DateTime.now(); //当前选中的日期
  TimeOfDay _selectedTime = TimeOfDay.now(); //当前选中的时间
 
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print(nowTime); //2020-02-11 08:51:14.165032
 
    //当前时间转换为时间戳
    var a = nowTime.millisecondsSinceEpoch; //13位时间戳
    print(a); //1581382274165
 
    //将时间戳转换成时间
    var aTime = DateTime.fromMillisecondsSinceEpoch(a);
    print(aTime); //2020-02-11 08:51:14.165
 
    //Flutter的第三方库 date_format 的使用
    //2020-02-11 08:51:14.165 时间转换为  2020-02-11
 
    print(formatDate(DateTime.now(), [yyyy, "-", mm, "-", dd]));
 
    //2020-02-11 08:51:14.165 时间转换为 2020年02月11日
    print(formatDate(DateTime.now(), [yyyy, "年", mm, "月", dd, "日"]));
  }
 
  //调起日期选择器
  void _showDatePicker() {
    //获取异步方法里面的值的第一种方式:then
    showDatePicker(
      //如下四个参数为必填参数
      context: context,
      initialDate: _selectedDate, //选中的日期
      firstDate: DateTime(1980), //日期选择器上可选择的最早日期
      lastDate: DateTime(2100), //日期选择器上可选择的最晚日期
    ).then((selectedValue) {
      setState(() {
        //将选中的值传递出来
        this._selectedDate = selectedValue;
      });
    }).catchError((err) {
      print(err);
    });
  }
 
  //调起时间选择器
  void _showTimePicker() async {
    // 获取异步方法里面的值的第二种方式:async+await
    //await的作用是等待异步方法showDatePicker执行完毕之后获取返回值
    var result = await showTimePicker(
      context: context,
      initialTime: _selectedTime, //选中的时间
    );
 
    //将选中的值传递出来
    setState(() {
      this._selectedTime = result;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //可以通过在外面包裹一层InkWell来让某组件可以响应用户事件
            InkWell(
              onTap: () {
                //调起日期选择器
                _showDatePicker();
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(formatDate(
                      this._selectedDate, [yyyy, "-", mm, "-", "dd"])),
                  Icon(Icons.arrow_drop_down)
                ],
              ),
            ),
 
            InkWell(
              onTap: () {
                //调起时间选择器
                _showTimePicker();
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text("${this._selectedTime.format(context)}"),
                  Icon(Icons.arrow_drop_down)
                ],
              ),
            )
          ],
        )
      ],
    );
  }
}
 

pubspec.yaml

name: flutter_app
description: A new Flutter application.
 
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In ios, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
 
environment:
  sdk: ">=2.1.0 <3.0.0"
 
dependencies:
  flutter:
    sdk: flutter
 
 
  flutter_localizations: 
    sdk: flutter
  
  date_format: ^1.0.6
  flutter_cupertino_date_picker: ^1.0.2
 
 
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
 
dev_dependencies:
  flutter_test:
    sdk: flutter
  intl: ^0.15.8
 
 
 
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
 
# The following section is specific to Flutter.
flutter:
 
  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true
 
  assets:
    - images/2.0x/demo.jpeg
    - images/3.0x/demo.jpeg
    - images/4.0x/demo.jpeg
    - images/demo.jpeg
 
  # To add assets to your application, add an assets section, like this:
  # assets:
  #  - images/a_dot_burr.jpeg
  #  - images/a_dot_ham.jpeg
 
  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.
 
  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages
 
  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages
 

显示效果:

 

 


————————————————
版权声明:本文为CSDN博主「蓝枫amy」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u014005316/article/details/104258791

以上是关于Flutter 自带日期组件的主要内容,如果未能解决你的问题,请参考以下文章

InkWell容器 和 官方自带日期组件 和第三方 日期组件 和 自带日期组件和时间组 件改为中文

一切皆组件的Flutter,安能辨我是雄雌

一切皆组件的Flutter,安能辨我是雄雌

一切皆组件的Flutter,安能辨我是雄雌

flutter icon和image

Flutter隐藏控件方法介绍