Currently, I need to go back and reopen the page to get new data. I am not able to successfully make the dynamic component. Some people suggested using setState() but I am not able to put a scaffold inside it. If I try to setState() the uri parsing line I get stuck loading without any list being displayed. If you could guide me about how to achieve the dynamic component of the app it would be great. Thanks in advance!
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
class LiveData extends StatefulWidget {
const LiveData({Key? key}) : super(key: key);
@override
State<LiveData> createState() => _LiveDataState();
}
class _LiveDataState extends State<LiveData> {
static const color = Color(0xFFfdecbd);
static const boxbgcolor = Color(0xFFfff8e5);
var data = [];
getFeedbackFromSheet() async {
var raw = await http.get(Uri.parse(
"https://script.google.com/macros/s/AKfycbyqH82oPAYxw0rXhGa3DcpjaOeL2hjnJP-Ia7VGZEimS8HjgPOLhmXqqYRK1qW0EfUT/exec"));
var jsonFeedback = convert.jsonDecode(raw.body);
setState(() {
data = jsonFeedback;
});
//print('this is json Feedback $jsonFeedback');
}
@override
void initState() {
getFeedbackFromSheet();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: color,
body: ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
var feedback = data[data.length-1- index];
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
color: boxbgcolor,
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Padding(
padding: const EdgeInsets.all(4.0),
child: ListTile(
title: Text("Date : " feedback["Date"].toString()),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Soil Temperature : "
feedback["Soil Temperature"].toString()),
Text("Temperature : "
feedback["Temperature"].toString()),
Text("Humidity : " feedback["Humidity"].toString()),
Text("Soil Moisture : "
feedback["Soil Moisture"].toString()),
],
),
),
),
),
);
},
),
);
}
}
CodePudding user response:
One way to keep your widget up to date with the latest data is to refresh periodically.
@override
void initState() {
getFeedbackFromSheet();
timer = Timer.periodic(const Duration(seconds: 10), (_) => getFeedbackFromSheet());
super.initState();
}
CodePudding user response:
You can use RefreshIndicator to refresh data
RefreshIndicator is a widget in Flutter that supports Material's swipe-to-refresh. It works by showing a circular progress indicator when the child's Scrollable is overscrolled. If the user ends the scroll and the indicator has been dragged far enough, it will call onRefresh.
RefreshIndicator(
onRefresh: getFeedbackFromSheet,
child: ListView.builder(
...
),
)