簡體   English   中英

Flutter 視圖未更新

[英]Flutter view not updating

我對 flutter 有看法。 代碼如下。 問題是調用setState()來更新視圖只會導致部分更新。 build() function 中使用 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()
    );
  }
}

原因是您使用的是 class 參數,而不是您創建的最終值。

改變這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM