我想提取一个内含onPressed
和setState
的部件,但是我得到了这个信息:“无法提取封闭类方法的引用。”
有没有办法做到这一点?
我想把我的代码分成不同的小部件,以便它保持清晰。这里是一个简化的代码示例:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Calculator(),
);
}
}
class Calculator extends StatefulWidget {
@override
_CalculatorState createState() => _CalculatorState();
}
class _CalculatorState extends State<Calculator> {
var myValue = 0;
void calculate() {
myValue = 12;
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
child: TextButton(
onPressed: () {
setState(() {
calculate();
});
},
child: Text(
'Button 001',
),
),
),
TextOutput(myValue: myValue),
],
),
);
}
}
class TextOutput extends StatelessWidget {
const TextOutput({
Key key,
@required this.myValue,
}) : super(key: key);
final int myValue;
@override
Widget build(BuildContext context) {
return Container(
child: Text(
myValue.toString(),
),
);
}
}
我想将其提取到一个单独的小部件中:
Container(
child: TextButton(
onPressed: () {
setState(() {
calculate();
});
},
child: Text(
'Button 001',
),
),
),