FluttersetState未更新小部件

4sup72z8  于 2023-01-05  发布在  Flutter
关注(0)|答案(2)|浏览(147)

我有一个名为pickDateRange的函数,由于某种原因,在setState之后,dateRangePicker没有更新它在小部件中的值。我想知道如何解决这个问题。当我从函数体打印dateRangePicker的值时,它发生了变化,但在小部件中什么也没有发生。

class _DealsInfoSectionState extends State<DealsInfoSection> {
  DateTimeRange dateTimeRange =
      DateTimeRange(start: DateTime.now(), end: DateTime.now());
  bool doItOnce = false;

  @override
  void initState() {
    super.initState();
    context.read<DealsBloc>().add(const FetchDeals());
  }

Future _pickDateRange(DateTimeRange dateTimeRange) async {
    DateTimeRange? newDateRange = await showDateRangePicker(
        context: context,
        initialDateRange: dateTimeRange,
        firstDate: DateTime(2010),
        lastDate: DateTime(2030),
        builder: (BuildContext? context, Widget? child) {
          return StatefulBuilder( ///<<here
              builder: (context, stateSetter) { ///<<here
                return FittedBox(
                  child: Theme(
                    data: ThemeData(
                      primaryColor: colorBlue,
                    ),
                    child: child!,
                  ),
                );
              }
          );
        });

    if (newDateRange == null) return;

    setState(() {
      dateTimeRange = newDateRange;
    });
    print(dateTimeRange);
    context.read<DealsBloc>().add(FetchDealsWithDate(
        startDate: newDateRange.start.millisecondsSinceEpoch,
        endDate: newDateRange.end.millisecondsSinceEpoch + 86400000));
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    var income = 0.0;

    return Container(
  width: width * 0.85,
  child: BlocBuilder<DealsBloc, DealsState>(
      builder: (context, state) {
        income = 0;
        if (state.deals.isNotEmpty) {
          state.deals.forEach((element) {
            income += element.amount;
          });
          if (!doItOnce) {
            dateTimeRange = DateTimeRange(
                start: DateTime.fromMillisecondsSinceEpoch(
                    state.deals[state.deals.length - 1].dateCreated),
                end: DateTime.fromMillisecondsSinceEpoch(
                    state.deals[0].dateCreated));
            doItOnce = !doItOnce;
            print(dateTimeRange);
          }
        }
        return Column(children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Date: ',
                style: Theme
                    .of(context)
                    .textTheme
                    .headline6,
              ),
              InkWell(
                onTap: () => _pickDateRange(dateTimeRange),
                child: Text(
                  '${DateFormat('yyyy/MM/dd').format(
                      dateTimeRange.start)} - '
                      '${DateFormat('yyyy/MM/dd').format(
                      dateTimeRange.end)}',
                  style: Theme
                      .of(context)
                      .textTheme
                      .subtitle1
                      ?.copyWith(color: Colors.black),
                ),
              )
            ],
          )
        ]);
       }
     ),
   );
  }
}
    • 输出:**
I/flutter (25750): 2023-01-01 00:00:00.000 - 2023-01-05 10:51:12.127

当我选择范围时

I/flutter (25750): 2023-01-02 00:00:00.000 - 2023-01-04 00:00:00.000

输出正确,但Widget中未更新任何内容

vmjh9lq9

vmjh9lq91#

您无法看到更改,因为WidgetsBlocBuilder的范围内
错误:

Builder
|_      👈 you are setting state here
|_ BlocBuilder
   |_ Widget    👈 Your widget which is listening

正确方法:

Builder
|_              👈 setState here
|_Widget        👈 Observable widget should be here
|_ BlocBuilder
  |_
tjvv9vkg

tjvv9vkg2#

我觉得就应该这样

...

  InkWell(
                onTap: ()async{
 DateTimeRange? newDateRange = await showDateRangePicker(
                                  context: context,
                                  initialDateRange: dateTimeRange,
                                  firstDate: DateTime(2010),
                                  lastDate: DateTime(2030),
                                  builder: (BuildContext? context, Widget? child) {
                                    return FittedBox(
                                      child: Theme(
                                        data: ThemeData(
                                          primaryColor: colorBlue,
                                        ),
                                        child: child!,
                                      ),
                                    );

                                  });

                              if(newDateRange != null){
                                setState(() {
                                  dateTimeRange = newDateRange;
                                });
                              };
        context.read<DealsBloc>().add(FetchDealsWithDate(
          startDate: newDateRange.start.millisecondsSinceEpoch,
          endDate: newDateRange.end.millisecondsSinceEpoch + 
        86400000));
 }

相关问题