flutter中如何使用日期选择DatePicker控件?

码云
2020-11-13 09:41

flutter中的日期选择控件DatePicker的示例代码如下:

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  DateTime selectedDate = DateTime.now();

  Future<void> _selectDate(BuildContext context) async {
    //初始化日期选择控件
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate, //默认日期
        firstDate: DateTime(2015, 8), //起始日期
        lastDate: DateTime(2101)); //最大日期
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked; //改变选择的日期值
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("${selectedDate.toLocal()}".split(' ')[0]),//显示日期选择结果
            SizedBox(height: 20.0,),
            RaisedButton(
              onPressed: () => _selectDate(context),//点击触发日期选择
              child: Text('Select date'),
            ),
          ],
        ),
      ),
    );
  }
}

 

全部评论

相关文章