我对颤振有看法。其代码如下。问题是调用 setState()
来更新视图只会导致部分更新。在 build()
函数中使用 selectedDate 的值可以正常工作。但是调用下面的 _loadHtml()
并不反映日期的变化。有人可以帮我解决这个问题或告诉我我做错了什么吗?
class somePage extends StatefulWidget {
static const String routeName = '/somePage';
@override
_somePageState createState() => _somePageState();
}
class _somePageState extends State<somePage> {
DateTime selectedDate = DateTime.now().toLocal();
@override
Widget build(BuildContext context) {
return new Scaffold(
...
body: LayoutReadings(
selectedDate: '${selectedDate.year}-${selectedDate.month}-${selectedDate.day}'
),
floatingActionButton: FloatingActionButton(
onPressed: () => _selectDate(context),
tooltip: 'Select Date',
child: Icon(Icons.calendar_today_sharp),
),
);
}
Future<void> _selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2021, 2),
lastDate: DateTime(2031));
if (picked != null && picked != selectedDate) {
setState(() {
selectedDate = picked;
});
}
}
@override
void initState(){
super.initState();
}
}
class LayoutSomePage extends StatefulWidget {
final String selectedDate;
WebViewController _controller;
LayoutSomePage({this.selectedDate});
_LayoutSomePageState createState() => _LayoutSomePageState();
}
class _LayoutSomePageState extends State<LayoutSomePage> {
@override
Widget build(BuildContext context) {
print('layout called with date: ' + widget.selectedDate); // works correctly
return new WebView(
initialUrl: 'about:blank',
onWebViewCreated: (WebViewController webViewController) {
widget._controller = webViewController;
_loadHtml();
},
);
}
void _loadHtml() async {
String content = '<!doctype html>';
content += '<html>';
content += '<head></head>';
content += '<body>';
content += widget.selectedDate; // doesn't work correctly
content += '</body>';
content += '</html>';
widget._controller.loadUrl(
Uri.dataFromString(
content,
mimeType: 'text/html',
encoding: Encoding.getByName('utf-8')
).toString()
);
}
}
答案 0 :(得分:0)
原因是您使用的是类参数,而不是您创建的最终值。
改变这个
content += widget.selectedDate; // doesn't work correctly
到
content += selectedDate // this is your variable and when you use set state u changing this value not the one in the widget tree