本文主要是介绍flutter 嵌套 StatefulWidget 不刷新,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
widget1 中有一个按钮和 widget2 ,
点击一次按钮 数字i+1,调用 widget2(i); widget1 widget2 都是 StatefulWidget
import 'package:flutter/material.dart';
import 'package:stack_trace/stack_trace.dart';
import 'dart:developer' as dev;void main() {runApp(MaterialApp(title: 'Dict', home: Scaffold(body: widget1())));
}class widget1 extends StatefulWidget {@overrideState<widget1> createState() => widget1_();
}class widget1_ extends State<widget1> {int i=1;@overrideWidget build(BuildContext context) {return Row(children: [ElevatedButton(child: Text("normal"),onPressed: () {setState(() {i=i+1;});},),widget2(i)],);}
}class widget2 extends StatefulWidget {int i;widget2(this.i) {//这一行能够收到变化debug(i.toString());}@overrideState<widget2> createState() => widget2_(i);
}class widget2_ extends State<widget2> {int i;widget2_(this.i) {//这里不会变化 甚至变化的时候都不会重新执行这里的代码debug(i.toString());}@overrideWidget build(BuildContext context) {return Text(i.toString());}
}
debug(Object? object,[int i=1]) {if(i>0){//获取 调用当前程序 所在 的文件 以及具体的行//将 StackTrace 对象转换成 Chain 对象//toTrace().frames // 拿出其中一条信息//[1] 上一层var frame = Chain.current().toTrace().frames[i];print("file :${frame.uri} line ${frame.line}");}var str = object.toString();if(str.length>450){dev.log(str);}print(object);
}
1.传递一个UniqueKey()可以解决 让它强制刷新,
2.或者使用 ValueKey(),
3.GlobalKey bKey = GlobalKey();textKey.currentState.onPressed(_count); 这个方案测试无效
import 'package:flutter/material.dart';
import 'package:stack_trace/stack_trace.dart';
import 'dart:developer' as dev;void main() {runApp(MaterialApp(title: 'Dict', home: Scaffold(body: widget1())));
}class widget1 extends StatefulWidget {@overrideState<widget1> createState() => widget1_();
}class widget1_ extends State<widget1> {int i=1;@overrideWidget build(BuildContext context) {return Row(children: [ElevatedButton(child: Text("normal"),onPressed: () {setState(() {i=i+1;});},),widget2(i,ValueKey(i))],);}
}class widget2 extends StatefulWidget {int i;Key key;widget2(this.i,this.key) {//这一行能够收到变化debug(i.toString());}@overrideState<widget2> createState() => widget2_(i);
}class widget2_ extends State<widget2> {int i;widget2_(this.i) {//这里不会变化 甚至变化的时候都不会重新执行这里的代码debug(i.toString());}@overrideWidget build(BuildContext context) {return Text(i.toString());}
}
debug(Object? object,[int i=1]) {if(i>0){//获取 调用当前程序 所在 的文件 以及具体的行//将 StackTrace 对象转换成 Chain 对象//toTrace().frames // 拿出其中一条信息//[1] 上一层var frame = Chain.current().toTrace().frames[i];print("file :${frame.uri} line ${frame.line}");}var str = object.toString();if(str.length>450){dev.log(str);}print(object);
}
这篇关于flutter 嵌套 StatefulWidget 不刷新的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!