Search code examples
flutterpostwebview

How to Post Data to URL in Flutter WebView


I want to post some data to the URL body in Flutter WebView. So, how can I do it?


Solution

  • webview_flutter doesn't have a method to send post requests at this moment. However, you can try my flutter_inappwebview plugin. It supports POST requests!

    A simple example using the current latest version 5.0.5+3 of the flutter_inappwebview plugin is:

    var postData = Uint8List.fromList(utf8.encode("firstname=Foo&lastname=Bar"));
    controller.postUrl(url: Uri.parse("https://example.com/my-post-endpoint"), postData: postData);
    

    where the postData is the Body of the request in x-www-form-urlencoded format.

    For example, if you have a PHP server, you can access the firstname and lastname values as you normally would do, that is $_POST['firstname'] and $_POST['lastname'].

    You can also initialize the InAppWebView widget with an initial POST request like this:

    child: InAppWebView(
      initialUrlRequest: URLRequest(
        url: Uri.parse("https://example.com/my-post-endpoint"),
        method: 'POST',
        body: Uint8List.fromList(utf8.encode("firstname=Foo&lastname=Bar")),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      ),
      onWebViewCreated: (controller) {
        
      },
    ),