flutter日期选择国际化支持

支持中文的日期选择,来自AI生成。亲测好用。

pubspec.yaml

yaml 复制代码
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations: # 添加这个
    sdk: flutter # 添加这个
  intl: ^0.20.2 # 添加这个

main.dart

dart 复制代码
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; // 导入本地化包

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // 国际化配置
      localizationsDelegates: const [
        // 提供 Material 组件的本地化字符串(如按钮、对话框等)
        GlobalMaterialLocalizations.delegate,
        // 提供 Cupertino 风格组件的本地化字符串
        GlobalCupertinoLocalizations.delegate,
        // 提供通用的文本方向本地化
        GlobalWidgetsLocalizations.delegate,
      ],
      // 声明应用支持的语言
      supportedLocales: const [
        Locale('en', ''), // English
        Locale('zh', 'CN'), // Chinese
      ],
      title: 'Flutter 日期选择器',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> 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(2000),
      lastDate: DateTime(2101),
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('中文日期选择器示例'),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text(
              "您选择的日期是: ${_selectedDate.year}年${_selectedDate.month}月${_selectedDate.day}日",
              style: const TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _selectDate(context),
              child: const Text('选择日期'),
            ),
          ],
        ),
      ),
    );
  }
}
相关推荐
程序喵大人2 小时前
【C++进阶】STL算法与函数对象 - 09 函数对象保存状态并复用规则
开发语言·c++·算法·stl·函数对象
hsjiasb8 小时前
FreeRTOS学习(二十七)——任务栈与栈溢出检测
开发语言·stm32·学习·学习笔记·freertos
丰锋ff8 小时前
3.1 Qt事件之事件处理器
开发语言·qt
多弗朗皮卡丘9 小时前
C语言梦开始的地方7:函数
c语言·开发语言
月华路9 小时前
G1 垃圾回收:脏卡队列、记忆集与并发精化线程机制
java·开发语言
gugucoding9 小时前
47. 【Java】Java内存模型(JMM)与可见性
java·开发语言
m0_3807438710 小时前
从零调用 Claude 教程
开发语言·python·node.js
起床学FPGA10 小时前
AI回答问题之后,会自动跳到最下面的问题
开发语言·javascript·ecmascript
x_x-F11 小时前
网络数据从网卡到用户态:一场基于内存所有权转移的接力赛
开发语言·网络·php
GitLqr11 小时前
Flutter 3.47 与 Dart 3.13:你必须了解的迁移指南
flutter·ios·dart