在我的 flutter 应用程序中,我需要将数据从一个小部件传递到另一个小部件。两者都封装在一个 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,),
),
],
),
我该如何解决这个问题?还有其他传递值的方法吗? 提前致谢
答案 0 :(得分:0)
您真正要寻找的是功能而不是小部件,这里是解决方案:
在某处声明函数
int updateMonth(int month) => month = DateTime.now().month;
&然后在任何你想要的地方调用它 - 它会根据你的请求获取数据并返回它
updateMonth(_focusedDay);
唯一的问题是 - 我真的不明白你想计算什么,但这是你问题的解决方案