Skip to content

Instantly share code, notes, and snippets.

@malibayram
Created April 26, 2020 01:49
Show Gist options
  • Save malibayram/a24b35cc9da10a05a3bea45f39e1a0bc to your computer and use it in GitHub Desktop.
Save malibayram/a24b35cc9da10a05a3bea45f39e1a0bc to your computer and use it in GitHub Desktop.
class MyApp26April extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Server',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.pink,
),
home: MyHomePage(title: 'Flutter Server App'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
StreamController<Map> _streamController = StreamController<Map>();
Timer _timer;
Future getData() async {
var url = 'https://milk-white-reveille.000webhostapp.com/get.php';
http.Response response = await http.get(url);
Map data = json.decode(response.body);
//Add your data to stream
_streamController.add(data);
}
@override
void initState() {
getData();
//Check the server every 5 seconds
_timer = Timer.periodic(Duration(seconds: 5), (timer) => getData());
super.initState();
}
@override
void dispose() {
//cancel the timer
if (_timer.isActive) _timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
centerTitle: true,
),
body: StreamBuilder<Map>(
stream: _streamController.stream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData)
return ListView(
children: [
ListTile(
title: Text(snapshot.data['title']),
subtitle: Text(snapshot.data['type']),
),
],
);
return Text('Loading...');
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment