Skip to content

Instantly share code, notes, and snippets.

@rominirani
Created March 8, 2018 21:22
Show Gist options
  • Save rominirani/68b27ea2d1a711fa9bec7761f109d9b3 to your computer and use it in GitHub Desktop.
Save rominirani/68b27ea2d1a711fa9bec7761f109d9b3 to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Famous Quotes',
home: new RandomQuotes(),
);
}
}
class RandomQuotes extends StatefulWidget {
@override
createState() => new RandomQuotesState();
}
class RandomQuotesState extends State<RandomQuotes> {
var _randomQuote = '-';
@override
Widget build(BuildContext context) {
var spacer = new SizedBox(height: 32.0);
return new Scaffold(
appBar: new AppBar(
title: new Text('Famous Quotes'),
),
body: new Center(
child : new Padding(
padding: new EdgeInsets.all(20.0),
child : new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(_randomQuote,style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 24.toDouble())),
spacer,
spacer,
new RaisedButton(
onPressed: _getRandomQuote,
child: new Text('Get a Random Quote'),
),
],
),
),
),
);
}
_getRandomQuote() async {
var url = '<FUNCTION_URL>';
var httpClient = new HttpClient();
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(UTF8.decoder).join();
var data = JSON.decode(json);
result = data['quote'] + "\n-- " + data['person'];
} else {
result =
'Error getting a random quote:\nHttp status ${response.statusCode}';
}
} catch (exception) {
result = 'Failed invoking the getRandomQuote function.';
}
// If the widget was removed from the tree while the message was in flight,
// we want to discard the reply rather than calling setState to update our
// non-existent appearance.
if (!mounted) return;
setState(() {
_randomQuote = result;
});
}
}
@phuocding
Copy link

Thanks, how can I using cloud function to update database cloud firestore?

@phuocding
Copy link

How to secure database when someone change <FUNCTION_URL>'?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment