flutter日期选择国际化支持

发布于:2025-09-13 ⋅ 阅读:(18) ⋅ 点赞:(0)

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

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations: # 添加这个
    sdk: flutter # 添加这个
  intl: ^0.20.2 # 添加这个

main.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});

  
  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});

  
  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;
      });
    }
  }

  
  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('选择日期'),
            ),
          ],
        ),
      ),
    );
  }
}

网站公告

今日签到

点亮在社区的每一天
去签到