How to display a local image before webview is successfully loaded in Flutter?

Related searches

In Flutter, I would like to display a local image before my webview is loaded. In case the user hasn't turn on their wifi, an image will be shown instead of a blank white screen(ios) or an error message saying cannot connect to said webpage(android).

I am using the official webview_flutter package for this app.

Below is the code that I've tried, but it works on ios but doesn't work on android. In Android, when I turned off the wifi and launch the app, an error message which displays the webview link is shown.

Edit: Does not change from image to webview after wifi is connected and pressed the reload button.

final webViewKey1 = GlobalKey<WebViewContainerState>();
var _url = 'http://www.google.com';
final _key = UniqueKey();
bool _isLoadingPage;

class WebViewPage extends StatefulWidget {
  @override
  WebViewPageState createState() => WebViewPageState();
}

class WebViewPageState extends State<WebViewPage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Screen 1'),
        leading: IconButton(
          icon: Icon(Icons.menu),
          onPressed: (){
            Scaffold.of(context).openDrawer();
          },
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.refresh), 
            color: Colors.white,
            onPressed: () {
              webViewKey1.currentState?.reloadWebView();
            },
          ),
        ]
      ),
      body: 
          WebViewContainer(key: webViewKey1),   
    );
  }
}

class WebViewContainer extends StatefulWidget {
  WebViewContainer({Key key}) : super(key: key);

  @override
  WebViewContainerState createState() => WebViewContainerState();
}

class WebViewContainerState extends State<WebViewContainer> {
  WebViewController _webViewController;

  void initState() {
    super.initState();
    _isLoadingPage = true;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
        children: <Widget>[
          Opacity(opacity: _isLoadingPage?0:1, child: WebView(
            key: _key,
            initialUrl: _url,
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (controller) {
              _webViewController = controller;
            },
            onPageFinished: (finish) {
              setState(() {
                _isLoadingPage = false;
              });
            },
          ),
          ),
          _isLoadingPage
            ? Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/fail.png'),
                  fit: BoxFit.fill,
                ),
              ),
            )
            : Container(
              color: Colors.transparent,
            ),
        ],
      );
  }

  void reloadWebView() {
    _webViewController?.reload();
  }
}

Use opacity widget to make it invisible and on completion show it.

Opacity(opacity: _isLoadingPage?0:1, child: WebView(
          key: _key,
          initialUrl: _url,
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (webViewCreate) {
            _controller.complete(webViewCreate);
          },
          onPageFinished: (finish) {
            setState(() {
              _isLoadingPage = false;
            });
          },
        ),)

Load HTML from assets or local files � Issue #27086 � flutter/flutter , zoechi changed the title webview_flutter html + CSS + assets Load HTML from assets or local files on Jan 27, 2019 image not load within local html file in webview starts loading. print('开始加载webview'); EasyLoading.show(status: ' loading. Successfully merging a pull request may close this issue. In addition, it also includes how to display loading icon while waiting the image to be fully loaded. Display Image from Network. Displaying an image from network is very simple. You can use Flutter's built-in Image.network method with the URL as the argument. You can also pass some optional arguments to the method preceded by the name of the

You can use IndexedStack and switch between widget after WebView loaded using onPageFinished. You can use the connectivity plugin to check for connectivity.

ConnectivityResult _connectionStatus;
  final Connectivity _connectivity = Connectivity();
  StreamSubscription<ConnectivityResult> _connectivitySubscription;
  int _page = 1;

  @override
  void initState() {
    super.initState();
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  Future<void> initConnectivity() async {
    ConnectivityResult result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return;
    }

    _updateConnectionStatus(result);
  }

  @override
  Widget build(BuildContext context) {
    print(_connectionStatus);
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: IndexedStack(
        index: _page,
        children: <Widget>[
          WebView(
            initialUrl: 'https://www.google.com/',
            onPageFinished: (_) {
              if (_connectionStatus != ConnectivityResult.none) {
                setState(() {
                  _page = 0;
                });
              }
            },
          ),
          Container(
            child: Center(
              child: Text('Some Image'),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    switch (result) {
      case ConnectivityResult.wifi:
      case ConnectivityResult.mobile:
      case ConnectivityResult.none:
        setState(() => _connectionStatus = result);
        break;
      default:
        setState(() => _connectionStatus = result);
        break;
    }
  }

[webview_flutter] Add loadAssetFile to load html file from local , #23 How to display custom html instead of URL in fluttercommunity/ The naming is by analogy to Image.asset and Image.file . result.success(null); // Tells Android WebView to allow js script to load local files using "file://" protocol. But we can append them back to nsUrl , the absolute path, before� Displaying images is fundamental for most mobile apps. Flutter provides the Image widget to display different types of images.. To work with images from a URL, use the Image.network() constructor.

You can use my plugin flutter_inappwebview, that has a lot of events, including events to manage errors (such as net::ERR_ADDRESS_UNREACHABLE) while the WebView is loading an url (onLoadError event) and when it receives HTTP errors, such as 403, 404, etc (onLoadHttpError event).

You can use the connectivity plugin to listen for network state changes by subscribing to the stream exposed by connectivity plugin.

Also, you can use IndexedStack and switch between widgets after the WebView is loaded using onLoadStop.

Full example:

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';

import 'package:connectivity/connectivity.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

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

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: InAppWebViewPage()
    );
  }
}

class InAppWebViewPage extends StatefulWidget {
  @override
  _InAppWebViewPageState createState() => new _InAppWebViewPageState();
}

class _InAppWebViewPageState extends State<InAppWebViewPage> {
  InAppWebViewController webView;
  int _page = 2;
  bool _loadError = false;
  StreamSubscription<ConnectivityResult> subscription;

  @override
  initState() {
    super.initState();
    subscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      if (result != ConnectivityResult.none && webView != null) {
        print("reload");
        _loadError = false;
        webView.reload();
      }
    });
  }

  @override
  dispose() {
    super.dispose();
    subscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text("InAppWebView")
        ),
        body: IndexedStack(
          index: _page,
          children: <Widget>[
            InAppWebView(
              initialUrl: "https://flutter.dev",
              initialHeaders: {},
              initialOptions: InAppWebViewWidgetOptions(
                  inAppWebViewOptions: InAppWebViewOptions(
                    clearCache: true,
                    debuggingEnabled: true,
                  ),
              ),
              onWebViewCreated: (InAppWebViewController controller) {
                webView = controller;
              },
              onLoadStart: (InAppWebViewController controller, String url) {

              },
              onLoadStop: (InAppWebViewController controller, String url) {
                print(url);
                setState(() {
                  if (!_loadError) {
                    _page = 0;
                  } else {
                    _page = 1;
                  }
                });
              },
              onLoadError: (InAppWebViewController controller, String url, int code, String message) async {
                print("error $url: $code, $message");
                _loadError = true;
              },
              onLoadHttpError: (InAppWebViewController controller, String url, int statusCode, String description) async {
                print("HTTP error $url: $statusCode, $description");
              },
            ),
            (Platform.isAndroid) ? Container(
                child: Text("My custom error message"),
            ) : Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/fail.png'),
                    fit: BoxFit.fill,
                  ),
                )
            ),
            Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/loading.jpg'),
                  fit: BoxFit.fill,
                ),
              )
            )
          ],
        ),
    );
  }
}

Loading Local Assets in WebView in Flutter | by Sha Qian, A rotating cube is rendered in the scene and every time I tap the refresh button, the cube changes its color. Image for post. Thank you for reading� WebView is just like any other widget in Flutter and can be composed with other widgets layering on top of it. Note that the favorite button is just a regular FloatingActionButton that is hovering

如何在Flutter中成功加载WebView之前显示本地图像?, How to display a local image before webview is successfully loaded in Flutter? 发表于 2019-07-29 05:24:10. 活跃于 2019-11-30 11:13:22. 查看173 次. As you can see above, we have imported flutter webview and assign the web url we want to access to flutter webview url property. 4. Run your app. You can use flutter command to run your app – $ flutter run. If everything goes well, you will see a website similar to the image below in your flutter webview.

Ios webview load url, The image file should be imported into the Xcode project also. close = function() { window. It contains WKWebView to allow iOS developers to load & display interactive web 4, the Xamarin. dev website of all pub packages in flutter. Jan 12, 2013 � This function would be called before loading each url in the WebView. zoechi changed the title webview_flutter 0.2.0 whenComplete completes before pages is loaded webview_flutter 0.2.0 loadUrl completes before pages is loaded Jan 24, 2019 zoechi mentioned this issue Jan 25, 2019

@neelu004: I saw that you use a subfolder (i.e. "assets/file/") for your html file.The Flutter-webview plugin is very tedious if it comes to folder/subfolder/ locations.

Comments
  • When I try to reload the webview when wifi is disconnected, the error message "Webpage not available" is still shown on Android, any idea on how to fix it?
  • When I try to reload the webview when wifi is disconnected, the error message "Webpage not available" is still shown on Android, any idea on how to fix it?
  • I have updated the answer. Here I'm checking the connectivity and updating the widget.
  • The image doesn't reload to show the webview when wifi is connected, even when I pressed the reload button, the image is stuck and doesn't show webview, any idea why that's happening?
  • Code is in the edit, I've tried your method, but it shows the image when I launch the app even when wifi is connected