【问题标题】:Passing data from one widget to another in the same tree将数据从一个小部件传递到同一树中的另一个小部件
【发布时间】:2021-09-26 03:37:10
【问题描述】:

在我的颤振应用程序中,我需要将数据从一个小部件传递到另一个小部件。两者都封装在一个 Column 小部件中,下图最好地描述了它

我尝试使用继承的小部件,但这似乎没有帮助,这是我创建的继承小部件的代码:

import 'package:flutter/material.dart';

class updateMonth extends StatefulWidget {
 final Widget child;
  const updateMonth({Key? key,required this.child}) : super(key: key);

  @override
  _updateMonthState createState() => _updateMonthState();
}

class _updateMonthState extends State<updateMonth> {
  int month=DateTime.now().month;

  void updMonth(int newMonth){
    setState(() =>
      month=newMonth
    );
  }

  @override
  Widget build(BuildContext context)=>monthFromCal(
      child: widget.child,
      month: month,
      newMonth: this,
  );
}


class monthFromCal extends InheritedWidget {
  final int month;
  final _updateMonthState newMonth;
  const monthFromCal({
    Key? key,
    required Widget child,
    required this.month,
    required this.newMonth

  }) : super(key: key, child: child);

  static _updateMonthState of(BuildContext context)=>context
         .dependOnInheritedWidgetOfExactType<monthFromCal>()!.newMonth; //NULL CHECK

  @override
  bool updateShouldNotify(monthFromCal old) {
    return old.month!=month;
  }
}

updateMonth() 是一个有状态的小部件,它应该接收和更新 month 的值,然后将其传递给继承的小部件 monthFromCal()。当我运行它时,我得到“用于空值的空检查运算符”错误。对于您的参考,这里有两个小部件:

Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                  TableCalendar(
                  focusedDay: _focusedDay,   ///DateTime _focusedDay=DateTime.now();
                  onPageChanged: (focusedDay) {
                    _focusedDay = focusedDay;
                    setState(() {
                   monthFromCal.of(context).updMonth(_focusedDay.month);
                     });
                  },
                    ),

                Container(
                      height: MediaQuery.of(context).size.height*0.3,
                      width: MediaQuery.of(context).size.width,
                    child: monthEvents(month: DateTime.now().month,),
                    ),
                  ],
            ),

我该如何解决这个问题?还有其他传递价值的方法吗? 提前致谢

【问题讨论】:

    标签: flutter flutter-widget inherited-widget


    【解决方案1】:

    你真正要找的是一个功能而不是一个小部件,这里是解决方案:

    在某处声明函数

    int updateMonth(int month) => month = DateTime.now().month;
    

    & 然后在任何你想要的地方调用它 - 它会根据你的请求获取数据并返回它

    updateMonth(_focusedDay);
    

    唯一的问题是 - 我并没有真正得到你想要计算的结果,但这是你问题的解决方案

    【讨论】:

    • 所以变量_focusedDay初始化为DateTime.now(),并在onPageChanged()内部重新赋值。我想要的是将_focusedDay 的更新值传递给小部件monthEvents() 我没有从你的答案中得到预期的结果,你能再看看吗?
    猜你喜欢
    • 2020-02-22
    • 2020-08-08
    • 2020-08-20
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2020-11-15
    相关资源
    最近更新 更多