web view for flutter web application

Issue

I’m new in flutter and I start to create a web application via flutter. I need a web view for opening a internet page. webView is worked for ios and android but not support web application.

import 'dart:io';
import 'package:jsonmapper/articlemap.dart';
import 'package:main.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

class ArticlePage extends StatefulWidget {
  final String title;
  final String nid;

  ArticlePage(this.title, this.nid, {Key key}) : super(key: key);

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

class _ArticlePageState extends State<ArticlePage> {
  ArticleMap _articleMap;
  bool _firstnavigate = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
          style: styles.textStyle(color: Colors.white),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      body: Platform.isAndroid || Platform.isIOS
          ? WebView(
              initialUrl: url,
              javascriptMode: JavascriptMode.unrestricted,
              navigationDelegate: (NavigationRequest request) {
                if (_firstnavigate) {
                  _firstnavigate = false;
                  return NavigationDecision.navigate;
                } else {
                  launch(request.url);
                  return NavigationDecision.prevent;
                }
              },
            )
          : launchURL(url),
    );
  }

  launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}

when I lunch URL in web application I have this error.

Expected a value of type 'widget?', but got one of type '_Future<dynamic>'

do you have any idea or better solution for this problem?!

Solution

You are expected to deliver a Widget to the Scaffold.body property but launchURL(url) is returning another type (Future<dynamic>).
To get rid of the error you can for example let the user click on a button to launch your url:

Platform.isAndroid || Platform.isIOS
    ? WebView(
  initialUrl: url,
  javascriptMode: JavascriptMode.unrestricted,
  navigationDelegate: (NavigationRequest request) {
    if (_firstnavigate) {
      _firstnavigate = false;
      return NavigationDecision.navigate;
    } else {
      launch(request.url);
      return NavigationDecision.prevent;
    }
  },
) : ElevatedButton(
  onPressed: () => launchURL(url),
  child: Text('Go to Website'),
)

Answered By – Marwén

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *