我创建了一个CupertinoDatePicker小部件,其初始值设置为变量。
当用户单击屏幕中的另一个小部件时,我想将选择器中的选定值更新为该变量值-但这不起作用(尽管CupertinoDatePicker小部件已重建)。
是错误还是我做错了什么?
代码(可以复制粘贴到dartPad中):

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
final _time = DateTime.now();
int _min = 5;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  createState() => MyWidgetSate();
}

class MyWidgetSate extends State<MyWidget> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('_min = ' + _min.toString(), style: Theme.of(context).textTheme.headline4),
        _buildDurationPicker(context),
        RaisedButton(
            onPressed: () {
              print('hello');
              setState(() {
                _min += 5;
              });
            },
            child: const Text('Add', style: TextStyle(fontSize: 20)),
          ),
        ],
    );
  }
}

Widget _buildDurationPicker(BuildContext context) {
    DateTime initDateTime = DateTime(_time.year, _time.month, _time.day)
        .add(Duration(minutes: _min));
    return Container(
      height: 216.0,
      color: Colors.white,
      child: CupertinoDatePicker(
        mode: CupertinoDatePickerMode.time,
        use24hFormat: true,
        initialDateTime: initDateTime,
        backgroundColor: Colors.transparent,
        onDateTimeChanged: (DateTime date) {
          //
        },
      ),
    );
  }

最佳答案

CupertinoDatePicker在内部维护状态,并且即使您更新了小部件的状态,也只能在其initialDateTime上设置initState
要在每次设置initialDateTime时强制进行重建,请将UniqueKey()分配为keyCupertinoDatePicker,它将在每次状态更改时使用新的initDateTime进行重建。

(...)
  CupertinoDatePicker(
        key: UniqueKey(),
        mode: CupertinoDatePickerMode.time,
        use24hFormat: true,
        initialDateTime: initDateTime,
        backgroundColor: Colors.transparent,
        onDateTimeChanged: (DateTime date) {
          //
        },
      ),

关于ios - Flutter-CupertinoDatePicker initialDateTime仅更新一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62835520/

10-13 03:54