【发布时间】:2021-06-07 20:27:13
【问题描述】:
我对 Flutter 很陌生,我在网上阅读的数百万个答案让我更加困惑。这是我的页面:
class SecondDegreePage extends StatefulWidget {
const SecondDegreePage({Key key}) : super(key: key);
@override
SecondDegreePageState createState() => SecondDegreePageState();
}
class SecondDegreePageState extends State<SecondDegreePage> {
final GlobalKey<FormState> _formKey = new GlobalKey();
final controllerParamA = TextEditingController();
final controllerParamB = TextEditingController();
final controllerParamC = TextEditingController();
Quadratic _solver = Quadratic([
(Random().nextInt(10) + 1) * 1.0,
(Random().nextInt(10) + 1) * 1.0,
(Random().nextInt(10) + 1) * 1.0
]);
void updateData() {
setState(() {
_solver = Quadratic([
(Random().nextInt(10) + 1) * 1.0,
(Random().nextInt(10) + 1) * 1.0,
(Random().nextInt(10) + 1) * 1.0
]);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalization.of(context).title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
// Input form
Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.all(20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
EquationInputField(
controller: controllerParamA,
textHint: 'a',
width: 70,
),
EquationInputField(
controller: controllerParamB,
textHint: 'b',
width: 70,
),
EquationInputField(
controller: controllerParamC,
textHint: 'c',
width: 70,
),
],
),
),
),
// Submit button
Padding(
padding: EdgeInsets.fromLTRB(0, 30, 0, 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () => updateData(),
color: Colors.blue,
elevation: 6,
child: Text(
AppLocalization.of(context).solve,
style: TextStyle(
color: Colors.white
),
),
)
],
),
),
//Solutions
Expanded(
child: Padding(
padding: EdgeInsets.only(bottom: 10),
child: AlgebraicSolutions(
solver: _solver
),
),
),
],
),
);
}
@override
void dispose() {
controllerParamA.dispose();
controllerParamB.dispose();
controllerParamC.dispose();
super.dispose();
}
}
Quadratic 类型只是一个做一些数学运算的类,没有什么重要的。问题出在这一行:
RaisedButton(
onPressed: () => updateData()
}
为什么什么也没发生?我已经阅读了对 setState 的调用调用了 build 方法,并且重新构建了小部件。因此,我希望
child: AlgebraicSolutions(
solver: _solver
),
这里_solver 参考得到更新。 AlgebraicSolutions 如下:
class AlgebraicSolutions extends StatefulWidget {
final Algebraic solver;
const AlgebraicSolutions({Key key, @required this.solver}) : super(key: key);
@override
AlgebraicSolutionsState createState() => AlgebraicSolutionsState();
}
class AlgebraicSolutionsState extends State<AlgebraicSolutions> {
//'Quadratic' is a subtype of Algebraic
Algebraic _solver;
@override
void initState() {
_solver = widget.solver;
super.initState();
}
@override
Widget build(BuildContext context) {
var solutions = _solver.solve();
return ListView.builder(
itemCount: solutions.length,
itemBuilder: (context, index) {
//...
}
);
}
}
那是因为我在 AlgebraicSolutionsState 中使用 initState 会破坏某些东西吗?
请注意,二次型是代数型的子类。
【问题讨论】:
-
会不会是因为我在分开的页面中有小部件?