Skip to content

Instantly share code, notes, and snippets.

@brickpop
Last active May 11, 2019 18:00
Show Gist options
  • Save brickpop/6ed786ed74c97eb9bd7cc351af70ba09 to your computer and use it in GitHub Desktop.
Save brickpop/6ed786ed74c97eb9bd7cc351af70ba09 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.pink,
),
home: MyHomePage(title: 'Flutter'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Center(
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: double.infinity,
decoration: BoxDecoration(color: Colors.blue),
child: Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Text(
"HI VOC",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20),
)),
)),
RENDERED_IMAGE,
RENDERED_IMAGE,
RENDERED_IMAGE,
RENDERED_IMAGE,
RENDERED_IMAGE,
RENDERED_IMAGE,
RENDERED_IMAGE,
RENDERED_IMAGE,
Card(
margin: EdgeInsets.all(10),
child: Container(
width: double.infinity,
margin: EdgeInsets.all(20),
child: Column(
children: <Widget>[
Text("HOLA"),
],
),
),
),
Container(
width: double.infinity,
height: 70,
margin: EdgeInsets.only(top: 10, bottom: 10),
child: FlatButton(
onPressed: runBrowserAction,
color: Colors.purple,
child: Text(
"SUBMIT",
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
),
Text('You have pushed the button $_counter times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
const RENDERED_IMAGE = Image(
image: NetworkImage(
"https://images.unsplash.com/photo-1557246519-f38ee04b918d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1374&q=80"),
height: 200,
width: double.infinity,
fit: BoxFit.fitWidth);
runBrowserAction() {
final flutterWebviewPlugin = new FlutterWebviewPlugin();
flutterWebviewPlugin.launch("https://www.google.com", hidden: true);
flutterWebviewPlugin
// .evalJavascript("window.navigator.userAgent")
.evalJavascript("JSON.stringify({hello:'234'})")
.then((String val) {
print("RECEIVED $val");
});
}
import 'package:rxdart/rxdart.dart';
class ItemsBloc {
List<int> items =
[]; //if the data is not passed by paramether it initializes with 0
BehaviorSubject<List<int>> _subjectItems;
ItemsBloc({this.items}) {
_subjectItems = new BehaviorSubject<List<int>>.seeded(
this.items); //initializes the subject with element already
}
Observable<List<int>> get counterObservable => _subjectItems.stream;
void pushNew() {
items.add(items.length);
_subjectItems.sink.add(items);
}
void removeLast() {
if (items.length <= 0) return;
items.removeAt(items.length - 1);
_subjectItems.sink.add(items);
}
void dispose() {
_subjectItems.close();
}
}
import 'dart:async';
import 'package:flutter/material.dart';
// import 'bloc/counter.dart';
import 'bloc/items.dart';
import 'util/webruntime.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new HomePage(title: 'Flutter Demo'),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {
ItemsBloc _itemsBloc = new ItemsBloc(items: []);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('The list has the following items:'),
new StreamBuilder(
stream: _itemsBloc.counterObservable,
builder: (context, AsyncSnapshot<List<int>> snapshot) {
String txt = snapshot.data != null
? snapshot.data.map((int v) => v.toString()).join((","))
: "";
return new Text(txt,
style: Theme.of(context).textTheme.display1);
})
],
),
),
floatingActionButton: new Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
new Padding(
padding: EdgeInsets.only(bottom: 10),
child: new FloatingActionButton(
onPressed: _itemsBloc.pushNew,
tooltip: 'Increment',
child: new Icon(Icons.add),
)),
Padding(
padding: EdgeInsets.only(bottom: 10),
child: new FloatingActionButton(
onPressed: _itemsBloc.removeLast,
tooltip: 'Decrement',
child: new Icon(Icons.remove),
),
),
WebRuntimeHook(),
new FloatingActionButton(
onPressed: () {
// new Timer(Duration(milliseconds: 1), () => WebRuntime.triggerAction());
WebRuntime.triggerAction();
},
tooltip: 'Launch',
child: new Icon(Icons.cast_connected),
),
]));
}
@override
void dispose() {
_itemsBloc.dispose();
super.dispose();
}
}
import 'package:flutter/material.dart';
import 'util/web-runtime.dart';
WebRuntime webRuntime = new WebRuntime();
// MAIN
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Web Runtime Test',
),
// Text(
// '$_counter',
// style: Theme.of(context).textTheme.display1,
// ),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
webRuntime.triggerAction();
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
name: myapp2
description: A new Flutter project.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_inappbrowser: ^1.1.3
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/runtime.html
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
<!DOCTYPE html>
<html>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script>
function sendMessage(payload = {}) {
window.flutter_inappbrowser.callHandler("JS_HANDLER", payload);
return null;
}
function action1() {
fetch("https://www.google.com")
.then(response => response.json())
.then(data => sendMessage({ data: data.substr(0, 1000) }))
.catch(err => sendMessage({ error: err.message }))
}
function action2() {
Promise.resolve("HELLO WORLD")
.then(data => sendMessage({ data }))
.catch(err => sendMessage({ error: err.message }))
}
</script>
</head>
<body>
<h1>RUNTIME</h1>
</body>
</html>
import 'dart:async';
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';
// BROWSER
class WebRuntime extends InAppBrowser {
Completer _init;
Future init() async {
if (_init == null) {
_init = new Completer();
} else if (_init.isCompleted) {
return;
}
await this.openFile("assets/runtime.html", options: {
"useShouldOverrideUrlLoading": true,
"useOnLoadResource": true,
"hidden": true
});
await _init.future;
// listen for post messages coming from the JavaScript side
this
.webViewController
.addJavaScriptHandler("JS_HANDLER", onMessageReceived);
}
// @override
// void onBrowserCreated() async {
// print("\n\nBrowser Ready!\n\n");
// _init.complete();
// }
// @override
// void onLoadStart(String url) {
// print("\n\nStarted $url\n\n");
// }
@override
onLoadStop(String url) {
_init.complete();
}
@override
void onLoadError(String url, int code, String message) {
// print("\n\nCan't load $url.. Error: $message\n\n");
_init.completeError("Unable to initialize the Web Runtime");
}
// @override
// void onExit() {
// print("\n\nBrowser closed!\n\n");
// }
@override
void shouldOverrideUrlLoading(String url) {
// IGNORE ALL NAVIGATION REQUESTS
}
// @override
// void onLoadResource(
// WebResourceResponse response, WebResourceRequest request) {
// print("Started at: " +
// response.startTime.toString() +
// "ms ---> duration: " +
// response.duration.toString() +
// "ms " +
// response.url);
// }
@override
void onConsoleMessage(ConsoleMessage consoleMessage) {
print("""
console output: ${consoleMessage.message}
""");
}
// RUN CODE ON THE BROWSER
triggerAction() async {
await this.init();
await this.webViewController.injectScriptCode('''
// sendMessage({a: 1, hello: "world"});
action1();
action2();
''');
// "window.flutter_inappbrowser.callHandler('JS_HANDLER', 1, 5,'string', {'key': 5}, [4,6,8]);"
}
// GOT A MESSAGE FROM THE BROWSER
onMessageReceived(arguments) async {
print(arguments);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment