如何在WebView Flutter中显示加载指示器?

9avjhtql  于 2023-06-07  发布在  Flutter
关注(0)|答案(3)|浏览(190)

我想在WebView的网页加载时显示加载指示器。下面是我的代码:

class Dates extends StatelessWidget {
  const Dates({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers = {
  Factory(() => EagerGestureRecognizer())
};

UniqueKey _key = UniqueKey();

    return MaterialApp(
      debugShowCheckedModeBanner: false,
    
      home: WebView(
        initialUrl: "https://www.allendalecolumbia.org/calendar",
        gestureRecognizers: gestureRecognizers,
        
      )
    );
  }
}
o0lyfsai

o0lyfsai1#

您可以将其 Package 在future builder中,并返回加载小部件,直到页面收到http200或完全加载。
有关使用future builder和返回不同小部件直到操作完成的更多信息,请参阅found here

e37o9pze

e37o9pze2#

要在Webview上制作Loading指示符,可以使用boolean函数和webView widgetsonPageFinished函数进行加载...
使用有状态小部件。

完整代码如下:

class Dates extends State< Dates >{

  
  bool isLoading=true;
  final _key = UniqueKey();
  
  const Dates({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

  final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers = 
       { Factory(() => EagerGestureRecognizer())};

    return Scaffold(
      body: Stack(
        children: <Widget>[
          WebView(
            key: _key,
            initialUrl: "https://www.allendalecolumbia.org/calendar",
            javascriptMode: JavascriptMode.unrestricted,
            gestureRecognizers: gestureRecognizers,
            onPageFinished: (finish) {
              setState(() {
                isLoading = false;
              });
            },
          ),
          isLoading ? Center( child: CircularProgressIndicator(),)
                    : Stack(),
        ],
      ),
    );
  }

}

希望这对你有用。

t2a7ltrp

t2a7ltrp3#

首先像这样定义变量:

bool isLoading = true;

然后这样做:

Stack(
  children: <Widget>[
    WebView(
      onPageFinished: (finish) {
        setState(() {
          isLoading = false;
        });
      },
    ),
    isLoading
        ? Center(
            child: CircularProgressIndicator(),
          )
        : SizedBox(),
  ],
)

注意:您需要在StatefulWidget中执行此操作才能正常工作。如果你不想使用StatefulWidget,你可以像这样使用StatefulBuilder小部件:

class Dates extends StatelessWidget {
  const Dates({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    bool isLoading = true;
    return StatefulBuilder(
      builder: (context, setState) {
        return Stack(
          children: <Widget>[
            WebView(
              onPageFinished: (finish) {
                setState(() {
                  isLoading = false;
                });
              },
            ),
            isLoading
                ? Center(
                    child: CircularProgressIndicator(),
                  )
                : SizedBox(),
          ],
        );
      },
    );
  }
}

相关问题