我发现你的问题很有趣,所以我认为值得研究一下。我给出了一种一般性的答案,但我认为你会从中受益。
首先向数据类添加方法,只更新必填字段,
像这样:
class DataClass with ChangeNotifier {
String firstString = " ";
String secondString = " ";
void updateFirst(String newString) {
firstString = newString;
notifyListeners();
}
void updateSecond(String newString) {
secondString = newString;
notifyListeners();
}
}
现在是重构的时候了,你必须创建两个拥有自己构建方法的类(或方法)(你也可以定义两个方法并将BuildContext传递给它们):
class StringOne extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("StringOne build method is called");
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
children: [
Text(context.select((DataClass value) => value.firstString)),
Container(
height: 100,
width: 100,
child: TextField(
onChanged: (text) {
context.read<DataClass>().updateFirst(text);
},
),
)
],
)
],
);
}
}
和
class StringTwo extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("StringTwo build method is called");
return Column(
children: <Widget>[
Column(
children: [
Text(context.select((DataClass value) => value.secondString)),
Container(
height: 100,
width: 100,
child: TextField(
onChanged: (text) {
context.read<DataClass>().updateSecond(text);
},
),
),
],
)
],
);
}
}
最后在描述 UI 的其他类中有这些类:
class ProviderExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView(
children: [StringOne(), StringTwo()],
);
}
}
您可能会说它会增加冗长,实际上,重构通常会使代码更冗长,但它也使代码更清晰且易于维护。在您的情况下,它还可以防止不必要的构建。
Console :
I/flutter ( 1469): StringTwo build method is called
I/flutter ( 1469): StringTwo build method is called
I/flutter ( 1469): StringTwo build method is called
I/flutter ( 1469): StringTwo build method is called
I/zygote64( 1469): Increasing code cache capacity to 1024KB
I/flutter ( 1469): StringOne build method is called
I/chatty ( 1469): uid=10140(com.example.stack_overflow) 1.ui identical 7 lines
I/flutter ( 1469): StringOne build method is called
I/flutter ( 1469): StringOne build method is called