首页 > 解决方案 > 重置子部件的状态

问题描述

以下是我遇到问题的代码摘要:

父小部件

class HomePage extends StatefulWidget {
  @override
    State<HomePage> createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  final GlobalKey<AsyncLoaderState> _asyncLoaderState = GlobalKey<AsyncLoaderState>();
  List<DateTime> rounds;
  List<PickupModel> pickups;
  DateTime currentDate;

  Widget build(BuildContext context) {
    var _asyncLoader = AsyncLoader(
      key: _asyncLoaderState,
      initState: () async => await _getData(),
      renderLoad: () => Scaffold(body: Center(child: CircularProgressIndicator())),
      renderError: ([error]) => Text('Sorry, there was an error loading'),
      renderSuccess: ({data}) => _buildScreen(context),
    );

    return _asyncLoader;
  }

  Widget _buildScreen(context) {
    return Scaffold(
      body: PickupList(pickups),
    );
  }


  Future<Null> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
      context: context,
    );

    if (picked != null && picked != currentDate) {
      currentDate = picked;
      pickups = await api.fetchPickupList(currentDate);
      setState(() {
      });
    }
  }

  _getData() async {
    rounds =  await api.fetchRoundsList();
    currentDate = _getNextRound(rounds);
    pickups = await api.fetchPickupList(currentDate);
  }
}

儿童小部件

(Listview 构建图块)

class PickupTile extends StatefulWidget{
  final PickupModel pickup;

  PickupTile(this.pickup);

  @override
    State<StatefulWidget> createState() {
      return PickupTileState();
    }
}

class PickupTileState extends State<PickupTile> {
  Duration duration;
  Timer timer;
  bool _isUnavailable;
  bool _isRunning = false;
  bool _isDone = false;

  @override
    void initState() {
      duration = widget.pickup.duration;
      _isUnavailable = widget.pickup.customerUnavailable;
      super.initState();
    }

  @override
    Widget build(BuildContext context) {
    return  Row(
      children: [
          // UI widgets
      ]
}

所以我有一个父小部件一个初始的拾取列表,显示在子 PickupTile 中。可以使用 更改所显示的取件日期_selectDate。这会获取存储在父状态中的新拾取列表,并使用正确的属性重建子级。但是,子小部件的状态(持续时间、isRunning、isDone...)不会重置,因此在更改日期时它们会留在屏幕上。

如果觉得我遗漏了一些明显的东西,但我不知道如何重置子小部件的状态或创建新的 PickupTiles,以便在更改日期时获得新的单独状态。

标签: dartflutterstate

解决方案


推荐阅读