How to show html form with submit button and hidden input fields in flutter
2,154
I got one workaround for this.
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:webview_flutter/webview_flutter.dart' as webview_flutter;
const kHtml = """
Foo bar.
<form action="https://the-url-with-post-method/post" method="POST">
<input type="hidden" name="foo" value="bar" />
<input type="submit" value="Submit">
</form>
The end.
""";
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('issue 126')),
body: HtmlWidget(
kHtml,
factoryBuilder: (c) => _CustomWidgetFactory(c),
),
),
);
}
class _CustomWidgetFactory extends WidgetFactory {
_CustomWidgetFactory(HtmlWidgetConfig config) : super(config);
@override
NodeMetadata parseLocalName(NodeMetadata meta, String localName) {
if (localName != 'form') return super.parseLocalName(meta, localName);
return lazySet(null,
buildOp: BuildOp(
onWidgets: (meta, _) => [
Builder(
builder: (context) => RaisedButton(
child: Text("Submit this form."),
onPressed: () => Navigator.of(context).push(MaterialPageRoute(
builder: (_) => _FormSubmit(meta.domElement.outerHtml))),
),
),
],
));
}
}
class _FormSubmit extends StatelessWidget {
final String html;
_FormSubmit(String formHtml)
: html = """<html>
<body onload="document.getElementsByTagName('form')[0].submit();">
<p>Loading...</p>
<div style="opacity: 0">$formHtml</div>
</body>
</html>""";
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(),
body: webview_flutter.WebView(
initialUrl: Uri.dataFromString(
html,
mimeType: 'text/html',
).toString(),
javascriptMode: webview_flutter.JavascriptMode.unrestricted,
),
);
}
Comments
-
Sanjay Sharma over 1 year
I have one API that returns html form with hidden input fields (the input field values are fetched from some other APIs), post method and submit button. I want to show that form button on a card of a list and when user clicks on submit button it should open another webpage. Could you please tell me if there is any possible way of doing this in Flutter/Android? Is it possible to submit the request using any library and send the html response to an in-app browser? Please let me know if this can be achieved.
-
Bodrov over 4 yearsHi @snj, do you have any sample code? What have you tried so far?
-
Sanjay Sharma over 4 yearsI tried with flutter_html plugin and html plugin but no luck so far
-
satish almost 4 yearsHave you fount any solution? I am trying to implement like this,
-
Sanjay Sharma almost 4 yearsYes, I got workaround. Please check the answer
-
-
sh_ark over 2 yearsHi, is there a workaround like for flutter-web as well?