flutter3.0学习笔记

日期选择器国际化

Preview
  • 第一步安装依赖flutter_localization
  • 第二步:在入口文件main.dart中引用
  • 第三步MaterialApp 的配置
  • ios风格的国际化

第一步安装依赖flutter_localization

dependencies:
  flutter_localizations:
    sdk: flutter
flutter pub get

第二步:在入口文件main.dart中引用

import 'package:flutter_localization/flutter_localization.dart';

第三步MaterialApp 的配置

在 MaterialApp 的构造方法中给 localizationsDelegatessupportedLocales 两个可选参数赋值:

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,//指定本地化的字符串和一些其他的值
          GlobalWidgetsLocalizations.delegate,//定义 widget 默认的文本方向,从左到右或从右到左。
          GlobalCupertinoLocalizations.delegate,//对应的 Cupertino 风格(Cupertino 风格组件即 iOS 风格组件)
        ],
        supportedLocales: [
          const Locale('zh', 'CH'),
          const Locale('en', 'US'),
        ],
      ....
   .....
}
void _showDatePicker() async{
    var result = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2021),
      lastDate: DateTime(2030),
      initialEntryMode: DatePickerEntryMode.calendarOnly,
      locale:const Locale('zh'),//设置语言
      initialDatePickerMode: DatePickerMode.day,
      builder: (context, Widget? child){
        return Theme(
          data: ThemeData(
            textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(
                foregroundColor: Colors.red
              )
            ),
            colorScheme: const ColorScheme.light(
              primary: Colors.red,
              onPrimary: Colors.white
            ),

          ),
          child: child!,
        );
      }
    );
    setState(() {
      _selectDateTime = result;
      print(_selectDateTime);
    });
  }

Simulator Screen Shot - iPhone 14 Pro - 2022-11-29 at 23.42.09.png

ios风格的国际化

包裹一层Localizations

SizedBox(
  height: 400,
  child: Localizations(
    locale:const Locale('zh'),
    delegates:const [
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      GlobalCupertinoLocalizations.delegate,
    ],
    child: CupertinoTimerPicker(
      mode: CupertinoTimerPickerMode.hms,
      initialTimerDuration: Duration(hours: now.hour,minutes: now.minute,seconds: now.second),
      minuteInterval: 1,
      secondInterval: 1,
      alignment: Alignment.center,
      backgroundColor: Colors.white,
      onTimerDurationChanged: (Duration duration){
        _selectTime = duration;
        // print(duration);
        print(_selectTime);
     },
    ),
  ),
),
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
class DatePickerPage extends StatefulWidget {
  const DatePickerPage({Key? key}) : super(key: key);

  @override
  State<DatePickerPage> createState() => _DatePickerPageState();
}

class _DatePickerPageState extends State<DatePickerPage> {
  DateTime? _selectDateTime;
  Duration? _selectTime;
  var now = DateTime.now();
  void _showDatePicker(context){
    showCupertinoModalPopup(
      context: context,
      builder: (_) => Container(
        height: 500,
        color: const Color.fromARGB(255, 255, 255, 255),
        child: Column(
          children: [
            SizedBox(
              height: 400,
              child: Localizations(
                locale: const Locale('zh'),
                delegates:const [
                  GlobalMaterialLocalizations.delegate,
                  GlobalWidgetsLocalizations.delegate,
                  GlobalCupertinoLocalizations.delegate,
                ],
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.dateAndTime,
                  use24hFormat: true,
                  dateOrder: DatePickerDateOrder.dmy,
                  minimumDate: DateTime(2021, 10, 10),
                  maximumDate: DateTime(2023, 12, 22),
                  minimumYear: 2020,
                  maximumYear: 2025,
                  initialDateTime: DateTime.now(),
                  onDateTimeChanged: (val){
                    setState(() {
                      _selectDateTime = val;
                    });
                  },
                ),
              ),
            ),
            TextButton(
              child: const Text('确定'),
              onPressed: (){
                Navigator.of(context).pop();
              }
            )
          ],
        ),
      )
    );

  }

  void _showDatePicker2(context){
    showCupertinoModalPopup(
      context: context,
      builder: (_) => Container(
        height: 500,
        color: const Color.fromARGB(255, 255, 255, 255),
        child: Column(
          children: [
            SizedBox(
              height: 400,
              child: Localizations(
                locale:const Locale('zh'),
                delegates:const [
                  GlobalMaterialLocalizations.delegate,
                  GlobalWidgetsLocalizations.delegate,
                  GlobalCupertinoLocalizations.delegate,
                ],
                child: CupertinoTimerPicker(
                  mode: CupertinoTimerPickerMode.hms,
                  initialTimerDuration: Duration(hours: now.hour,minutes: now.minute,seconds: now.second),
                  minuteInterval: 1,
                  secondInterval: 1,
                  alignment: Alignment.center,
                  backgroundColor: Colors.white,
                  onTimerDurationChanged: (Duration duration){
                    _selectTime = duration;
                    // print(duration);
                    print(_selectTime);
                 },
                ),
              ),
            ),
            CupertinoButton(
              child: const Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
                setState(() {
                  _selectTime = _selectTime;
                });
              },
            )
          ],
        ),
      )
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('日历'),),
      body: SafeArea(
        child: Center(
          child: Column(
            children: [
              Container(
                padding:const EdgeInsets.all(30),
                child: Text(_selectDateTime != null?_selectDateTime.toString():'未选择时间'),
              ),
              ElevatedButton(
                onPressed: (){
                  _showDatePicker(context);
                },
                child: const Text('CupertinoDatePicker')
              ),
              Container(
                padding:const EdgeInsets.all(30),
                child: Text(_selectTime != null ? _selectTime.toString():'未选择时间'),
              ),
              ElevatedButton(
                  onPressed: (){
                    _showDatePicker2(context);
                  },
                  child: const Text('CupertinoTimePicker')
              )

            ],
          ),
        ),
      ),
    );
  }
}

效果:

Simulator Screen Shot - iPhone 14 Pro - 2022-11-29 at 23.57.48.png

Simulator Screen Shot - iPhone 14 Pro - 2022-11-29 at 23.55.12.png