【Flutter 实战】1.20版本更新及新增组件

移动开发 作者: 2024-08-25 09:05:01
老孟导读:Flutter 1.20 更新了 Slider、RangeSlider、日期选择器组件、时间选择器组件的样式,新增了交换组件:InteractiveViewer,下面详细介绍其用法。 滑块

Slider

class SliderDemo extends StatefulWidget {
  @override
  _SliderDemoState createState() => _SliderDemoState();
}

class _SliderDemoState extends State<SliderDemo> {
  double _sliderValue = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,children: [
            Text('值:$_sliderValue'),Slider(
              value: _sliderValue,onChanged: (v){
                setState(() {
                  _sliderValue = v;
                });
              },)
          ],),);
  }
}
  • value:当前值。
  • onChanged:滑块值改变时回调。
Slider(
  value: _sliderValue,min: 1,max: 100,onChanged: (v){
    setState(() {
      _sliderValue = v;
    });
  },)
Slider(
  value: _sliderValue,min: 0,divisions: 4,)
Slider(
  value: _sliderValue,label: '$_sliderValue',)
  • 1 :轨道(Track),1 和 4 是有区别的,1 指的是底部整个轨道,轨道显示了可供用户选择的范围。对于从左到右(LTR)的语言,最小值出现在轨道的最左端,而最大值出现在最右端。对于从右到左(RTL)的语言,此方向是相反的。
  • 2:滑块(Thumb),位置指示器,可以沿着轨道移动,显示其位置的选定值。
  • 3:标签(label),显示与滑块的位置相对应的特定数字值。
  • 4:刻度指示器(Tick mark),表示用户可以将滑块移动到的预定值。
Slider(
  activeColor: Colors.red,inactiveColor: Colors.blue,value: _sliderValue,)
SliderTheme(
  data: SliderTheme.of(context).copyWith(
      activeTrackColor: Color(0xff404080),thumbColor: Colors.blue,overlayColor: Colors.green,valueIndicatorColor: Colors.purpleAccent),child: Slider(
    value: _sliderValue,onChanged: (v) {
      setState(() {
        _sliderValue = v;
      });
    },)
SliderTheme(
  data: SliderTheme.of(context).copyWith(
    valueIndicatorShape: PaddleSliderValueIndicatorShape(),)

RangeSlider

RangeValues _rangeValues = RangeValues(0,25);

RangeSlider(
  values: _rangeValues,labels: RangeLabels('${_rangeValues.start}','${_rangeValues.end}'),onChanged: (v) {
    setState(() {
      _rangeValues = v;
    });
  },

滑块状态

ios风格的 Slider

double _sliderValue = 0;
CupertinoSlider(
  value: _sliderValue,onChanged: (v) {
    setState(() {
      _sliderValue = v;
    });
  },)

Slider.adaptive(
  value: _sliderValue,)

showDatePicker

结构图

  1. 标题
  2. 选中的日期
  3. 切换到输入模式
  4. 选择菜单
  5. 月份分页
  6. 当前时间
  7. 选中日期
  1. 标题
  2. 选中日期
  3. 切换 日历模式
  4. 输入框

基础用法

 RaisedButton(
          child: Text('弹出日期组件'),onPressed: () async {
            await showDatePicker(
              context: context,initialDate: DateTime.now(),firstDate: DateTime(2010),lastDate: DateTime(2025),);
  • initialDate:初始化时间,通常情况下设置为当前时间。
  • firstDate:表示开始时间,不能选择此时间前面的时间。
  • lastDate:表示结束时间,不能选择此时间之后的时间。
var result = await showDatePicker(
  context: context,initialEntryMode: DatePickerEntryMode.input,);
var result = await showDatePicker(
  context: context,initialDatePickerMode: DatePickerMode.year,);
var result = await showDatePicker(
  context: context,helpText: '选则日期',cancelText: '取消',confirmText: '确定',);
var result = await showDatePicker(
  context: context,errorFormatText: '错误的日期格式',errorInvalidText: '日期格式非法',fieldHintText: '月/日/年',fieldLabelText: '填写日期',);

设置可选日期范围

var result = await showDatePicker(
  context: context,selectableDayPredicate: (date) {
    return date.difference(DateTime.now()).inMilliseconds < 0;
  },);

设置深色主题

var result = await showDatePicker(
  context: context,builder: (context,child){
    return Theme(
      data: ThemeData.dark(),child: child,);
  }
);

获取选中的日期

var result = await showDatePicker(
              context: context,);

print('$result');

CalendarDatePicker

CalendarDatePicker(
  initialDate: DateTime.now(),onDateChanged: (d) {
    print('$d');
  },)

范围日期

RaisedButton(
  child: Text('范围日期'),onPressed: () async {
    var date = showDateRangePicker(context: context,lastDate: DateTime(2025));
  },
  1. 标题
  2. 选定的日期范围
  3. 切换到输入模式
  4. 月和年标签
  5. 当前时间
  6. 开始时间
  7. 选中时间范围
  8. 结束时间

国际化

dependencies:
  flutter_localizations:
    sdk: flutter
MaterialApp(
  title: 'Flutter Demo',localizationsDelegates: [
    GlobalMaterialLocalizations.delegate,GlobalWidgetsLocalizations.delegate,GlobalCupertinoLocalizations.delegate,],supportedLocales: [
    const Locale('zh'),const Locale('en'),...
var result = await showDatePicker(
  context: context,);
var result = await showDatePicker(
  context: context,locale: Locale('zh')
);

基础使用

RaisedButton(
  child: Text('弹出时间选择器'),onPressed: () async {
    var result =
        showTimePicker(context: context,initialTime: TimeOfDay.now());
  },)
var result = showTimePicker(
    context: context,initialTime: TimeOfDay.now(),initialEntryMode: TimePickerEntryMode.input);
var result = showTimePicker(
    context: context,initialEntryMode: TimePickerEntryMode.input,helpText: '选择时间',confirmText: '确定');

24小时 制:

var result = showTimePicker(
  context: context,builder: (BuildContext context,Widget child) {
    return MediaQuery(
      data: MediaQuery.of(context)
          .copyWith(alwaysUse24HourFormat: true),);
  },);

黑暗模式

var result = showTimePicker(
  context: context,Widget child) {
    return Theme(
      data: ThemeData.dark(),);

国际化

dependencies:
  flutter_localizations:
    sdk: flutter
MaterialApp(
  title: 'Flutter Demo',...
RaisedButton(
  child: Text('弹出时间选择器'),)
var result = showTimePicker(
  context: context,Widget child) {
    return Localizations(
      locale: Locale('en'),delegates: [
        GlobalMaterialLocalizations.delegate,);

基础使用

class CupertinoDatePickerDemo extends StatefulWidget {
  @override
  _CupertinoDatePickerDemoState createState() => _CupertinoDatePickerDemoState();
}

class _CupertinoDatePickerDemoState extends State<CupertinoDatePickerDemo> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),body: Center(
        child: Container(
          height: 200,color: Colors.grey.withOpacity(.5),child: CupertinoDatePicker(
            initialDateTime: DateTime.now(),onDateTimeChanged: (date) {
              print('$date');
            },);
  }

}
CupertinoDatePicker(
  initialDateTime: DateTime.now(),minimumDate: DateTime.now().add(Duration(days: -1)),maximumDate: DateTime.now().add(Duration(days: 1)),onDateTimeChanged: (date) {
    print('$date');
  },)
CupertinoDatePicker(
  mode: CupertinoDatePickerMode.time,initialDateTime: DateTime.now(),)
CupertinoDatePicker(
  mode: CupertinoDatePickerMode.date,)
CupertinoDatePicker(
  mode: CupertinoDatePickerMode.dateAndTime,)
  • time:只显示时间,效果:4 | 14 | PM
  • date:只显示日期,效果:July | 13 | 2012
  • dateAndTime:时间和日期都显示,效果: Fri Jul 13 | 4 | 14 | PM
CupertinoDatePicker(
  use24hFormat: true,)

国际化

dependencies:
  flutter_localizations:
    sdk: flutter
MaterialApp(
  title: 'Flutter Demo',...
CupertinoDatePicker(
  initialDateTime: DateTime.now(),)
Localizations(
  locale: Locale('zh'),delegates: [
    GlobalMaterialLocalizations.delegate,child: CupertinoDatePicker(
    initialDateTime: DateTime.now(),onDateTimeChanged: (date) {
      print('$date');
    },)

基础使用

CupertinoTimerPicker(onTimerDurationChanged: (time) {
  print('$time');
})
  • CupertinoTimerPickerMode.hm:显示 小时 | 分钟,英文效果16 hours | 14 min
  • CupertinoTimerPickerMode.ms: 显示 分钟 | 秒,英文效果14 min | 43 sec
  • CupertinoTimerPickerMode.hms:显示 小时 | 分钟 | 秒,英文效果16 hours | 14 min | 43 sec
CupertinoTimerPicker(
    mode: CupertinoTimerPickerMode.hm,onTimerDurationChanged: (time) {
      print('$time');
    })
CupertinoTimerPicker(
    initialTimerDuration: Duration(
        hours: DateTime.now().hour,minutes: DateTime.now().minute,seconds: DateTime.now().second),onTimerDurationChanged: (time) {
      print('$time');
    })
CupertinoTimerPicker(
    minuteInterval: 5,secondInterval: 5,onTimerDurationChanged: (time) {
      print('$time');
    })

国际化

dependencies:
  flutter_localizations:
    sdk: flutter
MaterialApp(
  title: 'Flutter Demo',...
CupertinoTimerPicker(onTimerDurationChanged: (time) {
  print('$time');
})
Localizations(
  locale: Locale('zh'),child: CupertinoTimerPicker(onTimerDurationChanged: (time) {
    print('$time');
  }),)
InteractiveViewer(
  child: Image.asset('assets/images/go_board_09x09.png'),)
InteractiveViewer(
  alignPanAxis: true,child: Image.asset('assets/images/go_board_09x09.png'),)
InteractiveViewer(
  maxScale: 2,minScale: 1,scaleEnabled: true,)
class InteractiveViewerDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    const int _rowCount = 20;
    const int _columnCount = 10;
    return Scaffold(
      appBar: AppBar(),body: Center(
        child: Container(
          height: 300,width: 300,child: InteractiveViewer(
            constrained: false,child: Table(
              columnWidths: <int,TableColumnWidth>{
                for (int column = 0; column < _columnCount; column += 1)
                  column: const FixedColumnWidth(100.0),},children: <TableRow>[
                for (int row = 0; row < _rowCount; row += 1)
                  TableRow(
                    children: <Widget>[
                      for (int column = 0; column < _columnCount; column += 1)
                        Container(
                          height: 50,color: row % 2 + column % 2 == 1
                              ? Colors.red
                              : Colors.green,);
  }
}
  • onInteractionStart:当用户开始平移或缩放手势时调用。
  • onInteractionUpdate:当用户更新组件上的平移或缩放手势时调用。
  • onInteractionEnd:当用户在组件上结束平移或缩放手势时调用。
InteractiveViewer(
  child: Image.asset('assets/images/go_board_09x09.png'),onInteractionStart: (ScaleStartDetails scaleStartDetails){
    print('onInteractionStart:$scaleStartDetails');
  },onInteractionUpdate: (ScaleUpdateDetails scaleUpdateDetails){
    print('onInteractionUpdate:$scaleUpdateDetails');
  },onInteractionEnd: (ScaleEndDetails endDetails){
    print('onInteractionEnd:$endDetails');
  },)
final TransformationController _transformationController =
      TransformationController();

InteractiveViewer(
  child: Image.asset('assets/images/go_board_09x09.png'),transformationController: _transformationController,)
var matrix = _transformationController.value.clone();
matrix.scale(1.5,1.0,1.0);
_transformationController.value = matrix;
import 'dart:math';

import 'package:flutter/material.dart';

///
/// desc:
///

class InteractiveViewerDemo extends StatefulWidget {
  @override
  _InteractiveViewerDemoState createState() => _InteractiveViewerDemoState();
}

class _InteractiveViewerDemoState extends State<InteractiveViewerDemo> {
  final TransformationController _transformationController =
      TransformationController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),body: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 10.0),child: Center(
              child: InteractiveViewer(
                child: Image.asset('assets/images/go_board_09x09.png'),Expanded(
            child: Container(),Row(
            children: [
              RaisedButton(
                child: Text('重置'),onPressed: () {
                  _transformationController.value = Matrix4.identity();
                },RaisedButton(
                child: Text('左移'),onPressed: () {
                  var matrix = _transformationController.value.clone();
                  matrix.translate(-5.0);
                  _transformationController.value = matrix;
                },RaisedButton(
                child: Text('放大'),onPressed: () {
                  var matrix = _transformationController.value.clone();
                  matrix.scale(1.5,1.0);
                  _transformationController.value = matrix;
                },);
  }
}
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68312.html