Webview不随setState更改而更新

时间:2019-08-11 17:13:01

标签: flutter dart

我无法理解为什么我无法使用新的URL更新Webview。现在,我加载并获取一个使用“共享首选项”保存的URL,然后尝试使用该URL更新Web视图,但该应用程序显示空白屏幕。如果需要,我可以初始加载URL,但仍然无法使用setState更新URL以在Webview中显示其他站点。

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';


class BookStudy extends StatefulWidget {
  @override
  _BookStudy createState() => _BookStudy();
  }

  class _BookStudy extends State<BookStudy> {

  final Set<String> _favorites = Set<String>();
    var surl;
    final _key = UniqueKey();
    WebViewController controller;

  @override
    void initState(){
      super.initState();

      _getBookmark().then((startUrl){
         setState(() {
           print('startUrl: $startUrl');
            surl = startUrl;   
            controller.loadUrl(startUrl); 
          });
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Column(
          children: [
            Expanded(
                child: WebView(
                    key: _key,
                    javaScriptMode: JavaScriptMode.unrestricted,
                    initialUrl: surl,
                    onWebViewCreated: (WebViewController webViewController) {
                        controller = webViewController;
                        }
                    ))
          ],
        ));
  }

  _saveBookmark(String url) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString('bookmarkedPage', url);
    print('BOOKMARK SAVED!!!');
  }

   Future<String> _getBookmark() async {
      final prefs = await SharedPreferences.getInstance();
      var myMark = prefs.getString('bookmarkedPage') ?? '';
      if (myMark != '' && myMark != null){
        print("FOUND BOOKMARK!");
        return myMark;
      }   
  }
}

0 个答案:

没有答案