How can I disable JavaScript in Flutter app - flutter

I am trying to scrape a countdown website using Flutter webscraper package. I successfully scraped the images and titles, but couldn't scrape the timer running, as it changes according to the timer, so after doing some research I saw that if I disable the JavaScript I can scrape the counter but I'm unable to do so..
class _SchedulesState extends State<Schedules> {
late List<Map<String, dynamic>> scheduleWall = [];
late List<Map<String, dynamic>> scheduleEpisode = [];
late List<Map<String, dynamic>> scheduleName = [];
late List<Map<String, dynamic>> scheduleDay = [];
late List<Map<String, dynamic>> scheduleHour = [];
late List<Map<String, dynamic>> scheduleMins = [];
bool scheduleLoaded = false;
int page = 1;
void scheduleFetch() async {
final scheduleScraper = WebScraper("https://animecountdown.com");
isJavaScriptSimpleObject(false);
if (await scheduleScraper.loadWebPage("")) {
scheduleWall = scheduleScraper.getElement(
'countdown-content-main-columns-column-items-item-left-poster > img',
['src'],
);
scheduleName = scheduleScraper.getElement(
'countdown-content-main-columns-column-items-item-right > countdown-content-main-columns-column-items-item-right-title',
['title'],
);
scheduleEpisode = scheduleScraper.getElement(
'countdown-content-main-columns-column-items-item-right > countdown-content-main-columns-column-items-item-right-episode',
['title'],
);
scheduleDay = scheduleScraper.getElement(
'div.countdown-item.day > div.countdown-item-number',
['title'],
);
scheduleHour = scheduleScraper.getElement(
'div.countdown-item.hour > div.countdown-item-number',
['title'],
);
scheduleMins = scheduleScraper.getElement(
'div.countdown-item.min > div.countdown-item-number',
['title'],
);
// ignore: avoid_print
print(scheduleName);
setState(() {
scheduleLoaded = true;
});
}
}
#override
void initState() {
super.initState();
scheduleFetch();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xff121212),
body: scheduleLoaded
? SafeArea(
child: SingleChildScrollView(
child: Wrap(
children: [
for (int i = 0; i < scheduleWall.length; i++)
Padding(
padding: const EdgeInsets.only(
left: 25.0, top: 20.0, right: 25.0, bottom: 20.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Stack(
children: [
CachedNetworkImage(
imageUrl: "https:" +
scheduleWall[i]['attributes']['src'],
color: Colors.grey,
colorBlendMode: BlendMode.multiply,
fit: BoxFit.cover,
width: 400,
height: 450.0,
placeholder: (context, url) {
return const Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child: SpinKitPulse(
size: 40.0,
color: Colors.cyan,
),
),
);
},
),
Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Text(scheduleName[i]['title'],
maxLines: 2,
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 30.0)),
),
),
const SizedBox(
height: 115.0,
),
Center(
child: Text(scheduleEpisode[i]['title'],
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 30.0)),
),
const SizedBox(height: 140),
Row(
children: [
Padding(
padding:
const EdgeInsets.only(left: 85.0),
child: Text(scheduleEpisode[i]['title'],
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 2.0)),
),
Padding(
padding:
const EdgeInsets.only(left: 50.0),
child: Text(scheduleEpisode[i]['title'],
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 2.0)),
),
Padding(
padding:
const EdgeInsets.only(left: 50.0),
child: Text(scheduleEpisode[i]['title'],
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 2.0)),
),
const SizedBox(),
],
),
Row(
children: const [
Padding(
padding: EdgeInsets.only(left: 85.0),
child: Text("days",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20.0)),
),
Padding(
padding: EdgeInsets.only(left: 40.0),
child: Text("hours",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20.0)),
),
Padding(
padding: EdgeInsets.only(left: 30.0),
child: Text("mins",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20.0)),
),
],
)
],
)
],
),
),
)
],
),
),
)
: const Center(
child: SpinKitWanderingCubes(color: Colors.cyanAccent),
),
);
}
}

Related

flutter update stateful widget form stateless widget

i have 4 List and i want to change them by tapping on gesturedetector on tap event, but i receive an error. I tried call setState , but as i understood only stateful widget can do it. This lists already receive i just want to rebuild widget, i tried use it from state, but it also won't work.
error
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:vltest/Models/_request.dart';
import 'package:vltest/settings.dart';
import 'package:http/http.dart' as http;
import 'Models/_workers.dart';
import 'database.dart';
List<Requests> ActiveRequests = List.empty();
List<Requests> ClosedRequests = List.empty();
List<Requests> ActiveRequestsTO = List.empty();
List<Requests> ClosedRequestsTO = List.empty();
class RequestsPage extends StatefulWidget {
const RequestsPage();
#override
_RequestsPageState createState() => _RequestsPageState();
}
class _RequestsPageState extends State<RequestsPage> {
ScrollController controller = ScrollController();
bool closeTopContainer = false;
double topContainer = 0;
List<Widget> itemsData = [];
void getPostsData(List<Requests> list) {
List<Requests> responseList = list;
List<Widget> listItems = [];
responseList.forEach((post) {
listItems.add(Container(
height: 150,
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
color: Colors.white,
boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),
]),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
post.shopAddress,
style: const TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
post.problemPart,
style: const TextStyle(
fontSize: 12,
color: Colors.red,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
post.serialNumber,
style: const TextStyle(
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.bold),
)
],
),
//requestPhoto(post)
],
),
)));
});
setState(() {
itemsData = listItems;
});
}
void updatePostsData(List<Requests> list) {
List<Requests> responseList = list;
List<Widget> listItems = [];
responseList.forEach((post) {
GenerateRequestCards(listItems, post);
});
}
void GenerateRequestCards(List<Widget> listItems, Requests post) {
listItems.add(Container(
height: 150,
margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
color: Colors.white,
boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 10.0),
]),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
post.shopAddress,
style: const TextStyle(
fontSize: 15, fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
post.problemPart,
style: const TextStyle(
fontSize: 12,
color: Colors.red,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
post.serialNumber,
style: const TextStyle(
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.bold),
)
],
),
//requestPhoto(post)
],
),
)));
setState(() {
itemsData = listItems;
});
}
Image requestPhoto(Requests post) {
if (post.imageUrl == "") {
return Image.network(
post.imageUrl,
height: double.infinity,
);
} else {
return Image.network(
"https://i.ibb.co/TctYZfx/Logo-Main-3-1.jpg",
height: double.infinity,
);
}
}
#override
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => loadUserInfo().then((value) {
setState(() {});
}));
controller.addListener(() {
double value = controller.offset / 119;
setState(() {
topContainer = value;
closeTopContainer = controller.offset > 50;
});
});
}
#override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
final double categoryHeight = size.height * 0.30;
return SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.white,
leading: Icon(
Icons.arrow_back,
color: Colors.black,
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search, color: Colors.black),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.person, color: Colors.black),
onPressed: () {},
)
],
),
body: Container(
height: size.height,
child: Column(
children: <Widget>[
const SizedBox(
height: 10,
),
AnimatedOpacity(
duration: const Duration(milliseconds: 200),
opacity: closeTopContainer ? 0 : 1,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: size.width,
alignment: Alignment.topCenter,
height: closeTopContainer ? 0 : categoryHeight,
child: CategoriesScroller(
ActiveRequests: ActiveRequests,
ClosedRequests: ClosedRequests,
ActiveRequestsTO: ActiveRequestsTO,
ClosedRequestsTO: ClosedRequestsTO),
),
),
Expanded(
child: ListView.builder(
controller: controller,
itemCount: itemsData.length,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
double scale = 1.0;
if (topContainer > 0.5) {
scale = index + 0.5 - topContainer;
if (scale < 0) {
scale = 0;
} else if (scale > 1) {
scale = 1;
}
}
return Opacity(
opacity: scale,
child: Transform(
transform: Matrix4.identity()..scale(scale, scale),
alignment: Alignment.bottomCenter,
child: Align(
heightFactor: 0.7,
alignment: Alignment.topCenter,
child: itemsData[index]),
),
);
})),
],
),
),
),
);
}
Future<void> loadUserInfo() async {
Workers workers = await DBProvider.db.getWorkerInfo();
ActiveRequests = await getRequestsInfo(workers, "repair", "active");
ClosedRequests = await getRequestsInfo(workers, "repair", "closed");
ActiveRequestsTO = await getRequestsInfo(workers, "maintenance", "active");
ClosedRequestsTO = await getRequestsInfo(workers, "maintenance", "closed");
getPostsData(ActiveRequests);
setState(() {});
}
Future<void> updateLoadersData() async {
Workers workers = await DBProvider.db.getWorkerInfo();
ActiveRequests = await getRequestsInfo(workers, "repair", "active");
ClosedRequests = await getRequestsInfo(workers, "repair", "closed");
ActiveRequestsTO = await getRequestsInfo(workers, "maintenance", "active");
ClosedRequestsTO = await getRequestsInfo(workers, "maintenance", "closed");
setState(() {});
}
Future<List<Requests>> getRequestsInfo(
Workers workers, String type, String status) async {
Map data = {
'login': workers.login,
'type': type,
'status': status,
};
//encode Map to JSON
var body = json.encode(data);
final response = await http.post(
Uri.parse(GlobalSettings.serverHTTP + 'api/requests/list'),
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer ${workers.token}"
},
body: body);
if (response.statusCode == 200) {
Iterable l = json.decode(response.body);
List<Requests> loaders =
List<Requests>.from(l.map((model) => Requests.fromJson(model)));
return loaders;
} else {
throw Exception('Failed to load album');
}
}
List<T> map<T>(List list, Function handler) {
List<T> result = [];
for (var i = 0; i < list.length; i++) {
result.add(handler(i, list[i]));
}
return result;
}
}
class CategoriesScroller extends StatelessWidget {
const CategoriesScroller({
Key? key,
required this.ActiveRequests,
required this.ClosedRequests,
required this.ActiveRequestsTO,
required this.ClosedRequestsTO,
}) : super(key: key);
final List<Requests> ActiveRequests;
final List<Requests> ClosedRequests;
final List<Requests> ActiveRequestsTO;
final List<Requests> ClosedRequestsTO;
#override
Widget build(BuildContext context) {
final double categoryHeight =
MediaQuery.of(context).size.height * 0.30 - 50;
return SingleChildScrollView(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 20),
child: FittedBox(
fit: BoxFit.fill,
alignment: Alignment.topCenter,
child: Row(
children: <Widget>[
Container(
width: 150,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Active",
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"Repair",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
ActiveRequests.length.toString(),
style: TextStyle(fontSize: 16, color: Colors.white),
),
],
),
onTap: () {
List<Widget> list = [];
ActiveRequests.forEach((element) {
_RequestsPageState()
.GenerateRequestCards(list, element);
});
},
),
),
),
Container(
width: 150,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Closed",
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"Repair",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
ClosedRequests.length.toString(),
style: TextStyle(fontSize: 16, color: Colors.white),
),
],
),
onTap: () {
List<Widget> list = [];
ClosedRequests.forEach((element) {
_RequestsPageState()
.GenerateRequestCards(list, element);
});
},
),
),
),
Container(
width: 150,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Active",
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"Maintenance",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
ActiveRequestsTO.length.toString(),
style: TextStyle(fontSize: 16, color: Colors.white),
),
],
),
onTap: () {
List<Widget> list = [];
ActiveRequestsTO.forEach((element) {
_RequestsPageState()
.GenerateRequestCards(list, element);
});
},
),
),
),
Container(
width: 150,
margin: EdgeInsets.only(right: 20),
height: categoryHeight,
decoration: BoxDecoration(
color: Colors.orange.shade400,
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: GestureDetector(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Closed",
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"Maintenance",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
ClosedRequestsTO.length.toString(),
style: TextStyle(fontSize: 16, color: Colors.white),
),
],
),
onTap: () {
List<Widget> list = [];
ClosedRequestsTO.forEach((element) {
_RequestsPageState()
.GenerateRequestCards(list, element);
});
},
),
),
),
],
),
),
),
);
}
}
Give me an advice please...
Call setState after checking if it is mouted or not, like
if (mounted) {
setState(() {});
}
Sorry for long delay, honestly, i forgot about conversation, i solve problem by rewrite code , in statefull widget

Scrolling the page using SingleChildScrollView?

I try to use SingleChildScrollView to create the scrolling page but it comes out the error, how could I solve the problem? The result is that the fixed appbar and a scrollable form.
The error: RenderFlex children have non-zero flex but incoming height constraints are unbounded.
The error seems to tell me that the height is not enough but I am frustrated in what mistakes I have made.
the code I designed:
import 'package:dailyreport/weatheritem.dart';
import 'package:scroll_snap_list/scroll_snap_list.dart';
class ReferenceDetail extends StatefulWidget {
#override
_ReferenceDetailState createState() => _ReferenceDetailState();
}
class _ReferenceDetailState extends State<ReferenceDetail> {
final _formKey = GlobalKey<FormState>();
late Function slideAction;
List<Widget> weatherData = [];
ScrollController controller = ScrollController();
bool closeTopContainer = false;
double topContainer = 0;
int _focusedIndex = 0;
void _onItemFocus(int index) {
setState(() {
_focusedIndex = index;
});
}
void getPostData() {
List<dynamic> returnweather = WEATHERITEM; //get the weather data
List<Widget> weatherlist = [];
returnweather.forEach((post) {
weatherlist.add(
Container(
height: 200,
width: 120,
margin: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 40.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
color: Colors.white,
boxShadow: [
BoxShadow(color: Colors.black.withAlpha(100), blurRadius: 5.0),
]),
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset(
post["weather"],
),
SizedBox(height: 5.0),
Text(
post["weather_name"],
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.grey,
),
),
],
),
),
),
);
});
setState(() {
weatherData = weatherlist;
});
SizedBox(height: 50.0);
}
int selectedRadio = 0;
#override
void initState() {
super.initState();
selectedRadio = 0;
_onItemFocus(_focusedIndex);
getPostData();
controller.addListener(() {
double value = controller.offset / 119;
setState(() {
topContainer = value;
closeTopContainer = controller.offset > 100;
});
});
}
setSelectedRadio(int val) {
setState(() {
selectedRadio = val;
});
}
#override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.orange.shade200, Colors.white])),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: new AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back_ios_outlined,
color: Colors.black, size: 30),
onPressed: () {
Navigator.of(context).pop();
},
),
title: Text(
'日報表',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 30,
color: Colors.black,
),
),
),
body: SingleChildScrollView(
child: Form(
key: _formKey,
child:
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Padding(
padding: const EdgeInsets.only(top: 25.0, left: 20.0),
child: Container(
child: Text(
'項目名稱:',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Center(
child: Text(
'Chuk Yuen Shopping Ctr.30 project',
style:
TextStyle(fontSize: 16, fontWeight: FontWeight.normal),
),
),
),
RadioListTile(
value: 1,
groupValue: selectedRadio,
title: Text(
'參考編號:',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
'202012170000',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.normal,
),
),
onChanged: (value) {
setSelectedRadio(1);
},
),
RadioListTile(
value: 2,
groupValue: selectedRadio,
title: Text(
'客戶編號:',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
onChanged: (value) {
setSelectedRadio(2);
},
),
selectedRadio == 2
? Padding(
padding: const EdgeInsets.only(
top: 5.0, left: 20.0, right: 20.0),
child: TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: BorderSide.none,
),
fillColor: Colors.white,
filled: true,
hintText: '輸入客戶編號',
),
),
)
: SizedBox(),
Padding(
padding: EdgeInsets.only(left: 20.0),
child: Text(
'發布日期:',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Padding(
padding: EdgeInsets.only(
top: 10.0, left: 20.0, right: 20.0, bottom: 10.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
height: 50,
color: Colors.white,
child: InkWell(
onTap: () async {
final initialDate = DateTime.now();
await showDatePicker(
context: context,
initialDate: initialDate,
//showEXTalkDay == false ? initialDate : exTalkDay,
firstDate: DateTime(DateTime.now().year - 2),
lastDate: DateTime(DateTime.now().year + 3),
builder: (BuildContext context, Widget? child) {
return Theme(
data: Theme.of(context).copyWith(
colorScheme: ColorScheme.light(),
primaryColor: Colors.orange,
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
primary: Colors.grey)),
),
child: child!,
);
},
);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(left: 30),
child: Text(
'28/08/21',
/*showEXTalkDay == false
? 'DD/MM/YY'
: '${exTalkDay.day}/${exTalkDay.month}/${exTalkDay.year}'*/
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.grey[500],
),
),
),
Expanded(child: SizedBox()),
Padding(
padding: EdgeInsets.only(right: 20),
child: Image(
image: AssetImage('assets/arrowupanddown.png')),
),
],
),
),
),
),
),
SizedBox(height: 10.0),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'天氣:',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
flex: 1,
child: ScrollSnapList(
shrinkWrap: true,
onItemFocus: _onItemFocus,
itemSize: 150,
scrollDirection: Axis.horizontal,
itemCount: weatherData.length,
itemBuilder: (context, index) {
double scale = 1.0;
if (topContainer > 0.5) {
scale = index + 0.5 - topContainer;
if (scale < 0) {
scale = 0;
} else if (scale > 1) {
scale = 1;
}
}
return GestureDetector(
child: Opacity(
opacity: scale,
child: Transform(
transform: Matrix4.identity()..scale(scale, scale),
alignment: Alignment.bottomCenter,
child: Align(
heightFactor: 1.0,
alignment: Alignment.topCenter,
child: weatherData[index]),
),
),
);
}),
),
SizedBox(height: 20.0),
Row(children: [
Padding(
padding: const EdgeInsets.only(left: 20.0, top: 15.0),
child: Text(
'工地現場工作',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
Expanded(child: SizedBox()), //space between two elements
Padding(
padding: const EdgeInsets.only(right: 20.0),
child: ClipRRect(
borderRadius: BorderRadius.circular(50),
child: SizedBox(
height: 50,
width: 100,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
Colors.orange.shade600),
),
onPressed: () {
Navigator.of(context).pop();
}, //onpressed
child: Text(
'添加',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
]),
SizedBox(height: 20),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: Text(
'任務',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
]),
),
),
),
);
}
}
How about wrap SingleChildScrollView with Expanded?
That mentioned at here.
The Column has no Expanded children, so rather than take on the infinite height from its BoxConstraints.maxHeight, (the viewport provides no maximum height constraint), it automatically tries to shrink to fit its children. It cannot be smaller than its BoxConstraints.minHeight, though, and It therefore becomes the bigger of the minimum height provided by the ConstrainedBox and the sum of the heights of the children.
you should use SafeArea widget or Container widget as child of SingleChildScrollView

How can I prevent a listview from showing this error from showing RangeError (index) - flutter

I have a list that displays items from an endpoint. When I make an HTTP request, the request goes through but when I try to scroll I get half of the data, and towards the tail end, I get an error. Please can anyone help me? The error that displays when I want to scroll down is this below:
RangerError (index): invalid value: Not in range 0..7,
inclusive: 8
See also:
these are the methods that helps me make the get HTTP request:
Future<void> get_farmer_eop() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
print(user['UserName']);
final response = await http.get(
'http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${user['UserName']}',
headers: _setHeaders());
print('${response.statusCode}popo');
if (response.statusCode == 200) {
final jsonStatus = jsonDecode(response.body);
var maineops = jsonStatus['Eop'];
var eoplines = maineops['EopLines'];
setState(() {
q = maineops;
r = eoplines;
});
// print('trandid');
// print('${q['TransId']}kukuk');
} else {
throw Exception();
}
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
and this is full Code:
//initializing
import 'dart:convert';
import 'package:erg_app/StartScan.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:erg_app/models/eopModel.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ProfilePage extends StatefulWidget {
final String result;
final String dc_result;
ProfilePage({this.result, this.dc_result});
#override
_ProfilePageState createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
//From Eop Model
List<EopLine> eops = new List();
var p;
var q;
var r;
var user;
var userData;
var userDetail;
var anchors;
#override
initState() {
super.initState();
// _getUserInfo();
get_farmer();
get_farmer_eop();
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
debugShowCheckedModeBanner: false,
home: p == null
? Scaffold(
body: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
backgroundColor: Colors.grey,
),
),
)
: Scaffold(
appBar: AppBar(
title: new Center(
child: new Text('Farmers Data', textAlign: TextAlign.left)),
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
leading: new IconButton(
icon: new Icon(Icons.assignment_ind),
onPressed: () {},
),
),
body: Container(
child: ListView(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 20),
),
Padding(
padding: EdgeInsets.only(left: 110, right: 110),
child: CircleAvatar(
radius: 80,
backgroundColor: Colors.grey,
backgroundImage: NetworkImage(p['PhotoUrl']),
),
),
Text(
p['FullName'],
style: TextStyle(
fontFamily: 'SourceSansPro',
fontSize: 25,
),
textAlign: TextAlign.center,
),
Text(
p['ApplicationId'],
style: TextStyle(
fontSize: 18,
fontFamily: 'SourceSansPro',
color: Colors.green[400],
letterSpacing: 2.5,
),
textAlign: TextAlign.center,
),
Container(
margin: EdgeInsets.only(top: 20),
),
SizedBox(
height: 20.0,
width: 200,
child: Divider(
color: Colors.teal[100],
),
),
Text(
'Farmer Details',
textAlign: TextAlign.center,
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Text(
'Appication ID:',
style: TextStyle(
fontSize: 20,
fontFamily: 'SourceSansPro',
color: Colors.green[700],
letterSpacing: 2.5,
),
),
title: Text(
p['ApplicationId'],
style: TextStyle(
fontFamily: 'BalooBhai', fontSize: 20.0),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Text(
'BVN:',
style: TextStyle(
fontSize: 20,
fontFamily: 'SourceSansPro',
color: Colors.green[700],
letterSpacing: 2.5,
),
),
title: Text(
p['Bvn'],
style: TextStyle(
fontFamily: 'BalooBhai', fontSize: 20.0),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Text(
'Marital Status:',
style: TextStyle(
fontSize: 20,
fontFamily: 'SourceSansPro',
color: Colors.green[700],
letterSpacing: 2.5,
),
),
title: Text(
p['MaritalStatus'],
style: TextStyle(
fontFamily: 'BalooBhai', fontSize: 20.0),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Text(
'Anchor:',
style: TextStyle(
fontSize: 20,
fontFamily: 'SourceSansPro',
color: Colors.green[700],
letterSpacing: 2.5,
),
),
title: Text(
p['AnchorAcronym'],
style: TextStyle(
fontFamily: 'BalooBhai', fontSize: 20.0),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Text(
'Gender:',
style: TextStyle(
fontSize: 20,
fontFamily: 'SourceSansPro',
color: Colors.green[700],
letterSpacing: 2.5,
),
),
title: Text(
p['Gender'],
style: TextStyle(
fontFamily: 'BalooBhai', fontSize: 20.0),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Text(
'Phone:',
style: TextStyle(
fontSize: 20,
fontFamily: 'SourceSansPro',
color: Colors.green[700],
letterSpacing: 2.5,
),
),
title: Text(
p['PhoneNo'],
style: TextStyle(
fontFamily: 'BalooBhai', fontSize: 20.0),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Text(
'State/LGA:',
style: TextStyle(
fontSize: 20,
fontFamily: 'SourceSansPro',
color: Colors.green[700],
letterSpacing: 2.5,
),
),
title: Text(
'${p['State']} / ${p['Lga']}',
style: TextStyle(
fontFamily: 'BalooBhai', fontSize: 20.0),
),
),
),
Card(
color: Colors.white,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 25.0),
child: ListTile(
leading: Text(
'Farm Size:',
style: TextStyle(
fontSize: 20,
fontFamily: 'SourceSansPro',
color: Colors.green[700],
letterSpacing: 2.5,
),
),
title: Text(
'${p['Size']}',
style: TextStyle(
fontFamily: 'BalooBhai', fontSize: 20.0),
),
),
),
//Geo code was here
Divider(),
Row(
// mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
SizedBox(width: 15),
Icon(Icons.timelapse,
size: 30, color: Colors.green[400]),
SizedBox(width: 15),
Text(
'EOP Details',
style:
TextStyle(color: Colors.green[400], fontSize: 20),
),
],
),
Padding(
padding: const EdgeInsets.all(5.0),
child: Card(
elevation: 4.0,
color: Colors.grey[100],
margin: EdgeInsets.only(
left: 10, right: 10, top: 20, bottom: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Container(
padding:
EdgeInsets.only(left: 15, top: 20, bottom: 10),
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(width: 10),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
left: 10, top: 10),
child: Text(
'TransId:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding: const EdgeInsets.only(
left: 50, top: 12),
child: Text(
q['TransId'],
// anchors[i]['Oid'].toString(),
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Container(
height: 20,
),
// button was here
],
),
),
),
),
ListView.builder(
shrinkWrap: true,
itemCount: r.length,
itemBuilder: (BuildContext context, int i) {
////////////// 1st card///////////
return Card(
elevation: 4.0,
color: Colors.grey[100],
margin: EdgeInsets.only(
left: 10, right: 10, top: 20, bottom: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Container(
padding: EdgeInsets.only(
left: 15, top: 20, bottom: 10),
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Container(width: 10),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
left: 10, top: 10),
child: LimitedBox(
child: Text(
'Item Name:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration:
TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
),
Padding(
padding: const EdgeInsets.only(
left: 20, top: 12),
child: Flexible(
child: Text(
r[i]['ItemName'],
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration:
TextDecoration.none,
fontWeight:
FontWeight.normal,
),
),
)),
],
),
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
left: 10, top: 10),
child: Flexible(
child: Text(
'Quantity Allocated:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration:
TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
),
Padding(
padding: const EdgeInsets.only(
left: 20, top: 12),
child: Flexible(
child: Text(
'${r[i]['QuantityAllocated']}',
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration:
TextDecoration.none,
fontWeight:
FontWeight.normal,
),
),
)),
],
),
Container(
height: 20,
),
// button was here
],
),
),
),
),
);
}),
Divider(),
Container(
margin: EdgeInsets.only(top: 20, bottom: 30),
child: Center(
child: RaisedButton(
padding: EdgeInsets.fromLTRB(80, 10, 80, 10),
color: Colors.green,
child: Text(
"Complete",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 14),
),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) =>
StartScanPage(widget.dc_result)));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
),
),
),
],
),
),
),
);
}
Future<void> get_farmer() async {
final response = await http
.get('http://api.ergagro.com:112/GetFarmerByBvn?Bvn=${widget.result}');
print('${response.statusCode}yoyo');
if (response.statusCode == 200) {
final jsonStatus = jsonDecode(response.body);
setState(() {
p = jsonStatus['Farmer'];
});
print('${p['Oid']}');
} else {
throw Exception();
}
}
Future<void> get_farmer_eop() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
print(user['UserName']);
final response = await http.get(
'http://api.ergagro.com:112/GenerateFarmersEop?farmerBvn=${widget.result}&dcOid=${widget.dc_result}&agentName=${user['UserName']}',
headers: _setHeaders());
print('${response.statusCode}popo');
if (response.statusCode == 200) {
final jsonStatus = jsonDecode(response.body);
var maineops = jsonStatus['Eop'];
var eoplines = maineops['EopLines'];
setState(() {
q = maineops;
r = eoplines;
});
// print('trandid');
// print('${q['TransId']}kukuk');
} else {
throw Exception();
}
}
_setHeaders() => {
'Content-type': 'application/json',
'Accept': 'application/json',
};
}
class profile {
String name,
bvn,
phone,
appliId,
state,
farmsize,
geocord,
anchor,
lga,
gender,
maritalStatus;
profile(
this.name,
this.bvn,
this.phone,
this.appliId,
this.state,
this.farmsize,
this.geocord,
this.anchor,
this.lga,
this.gender,
this.maritalStatus);
}
Try to use r.length - 1 . It should help.

How can i display a button based on http response in flutter

I am making an http request to and endpoint in flutter and based on my response I want to display a button but its not working, please can anybody help me? I am new to flutter. The endpoint requires two parameters which is UserID and agent ID and I all getting that from shared preference file.
userId = b6caf34c-a425-4710-a3ee-aa22a382882a
agentId : 57
Please someone should help me out.
this is my service file:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
class CallApi{
final String _url = 'http://api.ergagro.com:112/';
postData(data, apiUrl) async {
// + await _getToken();
var fullUrl = _url + apiUrl;
return await http.post(
fullUrl,
body: jsonEncode(data),
headers: _setHeaders()
);
}
// + await _getToken();
getData(apiUrl) async {
var fullUrl = _url + apiUrl;
return await http.get(
fullUrl,
headers: _setHeaders()
);
}
_setHeaders() => {
'Content-type' : 'application/json',
'Accept' : 'application/json',
};
_getToken() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var token = localStorage.getString('token');
return '?token=$token';
}
}
the view Screen the two buttons are almost at the end of the view screen:
import 'package:erg_app/StartScan.dart';
import 'package:erg_app/StockPage.dart';
import 'package:erg_app/Widgets/nav-drawer.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:erg_app/api/api.dart';
class detailsPage extends StatefulWidget {
Map<String, dynamic> value;
detailsPage({Key key, #required this.value}) : super(key: key);
#override
_detailsPageState createState() => _detailsPageState(value);
}
class _detailsPageState extends State<detailsPage> {
var user;
var userData;
var userDetail;
var anchors;
var dailyStatus;
var dailyStocks;
#override
void initState() {
_getUserInfo();
super.initState();
_checkDailyStockTakingStatus();
}
void _getUserInfo() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var userJson = localStorage.getString('loginRes');
user = json.decode(userJson);
userDetail = user['UserDetail'];
anchors = user['Anchors'];
setState(() {
userData = user;
});
}
void _checkDailyStockTakingStatus() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var res = await CallApi().getData('CheckDailyStockTakingStatus?userId=${user['UserId']}&agentId=${userDetail['Oid']}');
var body = json.decode(res.body);
if (body['Success']) {
dailyStatus = localStorage.setString('inventoryStatus', json.encode(body));
// I want to use the dailyStocks to access the nested stock items in the array
dailyStocks = dailyStatus['Stock'];
} else {
// // _showMsg();
print(Text('Something Went Wrong'));
}
}
Map<String, dynamic> value;
_detailsPageState(this.value);
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: NavDrawer(),
appBar: AppBar(
title: Text("Anchor Details"),
iconTheme: IconThemeData(color: Colors.white),
backgroundColor: Colors.green,
),
body: Container(
padding: const EdgeInsets.fromLTRB(10, 30, 10, 10),
child: ListView(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(width: 15),
Icon(Icons.home, size: 30, color: Colors.green[400]),
SizedBox(width: 15),
Text(
'${value['Acronym']} Distribution Center(s)',
style: TextStyle(color: Colors.green[400], fontSize: 20),
),
],
),
ListView.builder(
shrinkWrap: true,
itemCount: value['DistributionCentres'].length,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (BuildContext context, int i) {
return Padding(
padding: const EdgeInsets.all(10.0),
////////////// 1st card///////////
child: Card(
elevation: 4.0,
color: Colors.grey[100],
margin: EdgeInsets.only(
left: 10, right: 10, top: 20, bottom: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Container(
padding: EdgeInsets.only(left: 15, top: 20, bottom: 10),
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 50.0,
height: 50.0,
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.cover,
image: AssetImage(
'assets/images/user.png')))),
),
SizedBox(
width: 20,
),
Text(
value['DistributionCentres'][i]['Name'],
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 20,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
],
),
Container(width: 10),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Allocated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 70, top: 12),
child: Text(
'300',
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Validated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 70, top: 12),
child: Text(
'400',
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Non Validated Farmers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 40, top: 12),
child: Text(
'123',
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Distribution Centers:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 60, top: 12),
child: Text(
'76',
textAlign: TextAlign.left,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Row(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(left: 10, top: 10),
child: Text(
'Daily Inventory Status:',
textAlign: TextAlign.left,
style: TextStyle(
color: Color(0xFF9b9b9b),
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
Padding(
padding:
const EdgeInsets.only(left: 50, top: 12),
child: Text(
'Completed',
textAlign: TextAlign.left,
style: TextStyle(
color: 'Completed' == 'Completed'
? Colors.green
: Colors.red,
fontSize: 14.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
],
),
Container(
height: 20,
),
Row(
children: <Widget>[
/////////// Based on the response I want to use it to control these two buttons below
///if the response is 200 it should display validate farmer else it should display Take Inventory/////////////
Padding(
padding: const EdgeInsets.all(10.0),
//this is where I want to perform the check but its not working
// dailyStatus['StatusCode'] == 200
child: 'InCompleted' == 'Completed'
? FlatButton(
child: Padding(
padding: EdgeInsets.only(
top: 8,
bottom: 8,
left: 10,
right: 10),
child: Text(
'Validate Farmers',
textDirection: TextDirection.ltr,
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
color: Colors.green,
shape: new RoundedRectangleBorder(
borderRadius:
new BorderRadius.circular(
20.0)),
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
StartScanPage() ));
// Edit()was here
},
)
//if the status is not 200 then it should allow an agent to take inventory
: FlatButton(
child: Padding(
padding: EdgeInsets.only(
top: 8,
bottom: 8,
left: 10,
right: 8),
child: Text(
'Take Inventory',
textDirection: TextDirection.ltr,
style: TextStyle(
color: Colors.white,
fontSize: 15.0,
decoration: TextDecoration.none,
fontWeight: FontWeight.normal,
),
),
),
color: Colors.blueGrey,
shape: new RoundedRectangleBorder(
borderRadius:
new BorderRadius.circular(
20.0)),
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
StockInventoryPage() ));
},
),
),
/////////// End of Buttons /////////////
],
),
],
),
),
),
);
})
],
),
),
);
}
}
I also tried to do this but its still didn't work please I need help:
void _checkDailyStockTakingStatus() async {
try {
final queryParameters = {
'userId': 'b6caf34c-a425-4710-a3ee-aa22a382882a',
'agentId': '57',
};
// SharedPreferences localStorage = await SharedPreferences.getInstance();
// var res = await CallApi().getData('CheckDailyStockTakingStatus?
// userId=${user['UserId']}&agentId=${userDetail['Oid']}');
final uri = Uri.http('http://api.ergagro.com:112/',
'CheckDailyStockTakingStatus?', queryParameters);
print("FullUrl");
print(uri);
var res = await get(uri, headers: {'Content-Type': 'application/json'});
var body = json.decode(res.body);
print(body[0]);
// var status = localStorage.setString('inventoryStatus',
//json.encode(body));
// setState(() {
// dailyStatus = status;
// });
} catch (e) {
print(Text('Error Occured: $e'));
}
}
Error message
You need to use setState after you modify the variable in State.
Ex.
void _checkDailyStockTakingStatus() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var res = await CallApi().getData('CheckDailyStockTakingStatus?userId=${user['UserId']}&agentId=${userDetail['Oid']}');
var body = json.decode(res.body);
if (body['Success']) {
var status= localStorage.setString('inventoryStatus', json.encode(body));
// I want to use the dailyStocks to access the nested stock items in the array
var stocks= status['Stock'];
setState((){
dailyStatus = status;
dailyStocks = stocks;
});
} else {
// // _showMsg();
print(Text('Something Went Wrong'));
}
}
See https://flutter.dev/docs/development/ui/interactive
Change uri to:
final uri = Uri.http('api.ergagro.com:112','/CheckDailyStockTakingStatus', queryParameters);
Also setState after getting the data to rebuild the widget:
setState(() {
dailyStocks = dailyStatus['Stock'];
});

Flutter - How do I get different results using the same future?

I am trying to get a different Times set by the user on each button. But show the same time for all of them. Whenever I change it, it changes the time of all their text. How do I do it, please explain?
This is my code:
import 'package:flutter/material.dart';
import 'package:flutter_duration_picker/flutter_duration_picker.dart';
import 'dart:async';
class EndurancePage extends StatefulWidget {
#override
_EndurancePageState createState() => _EndurancePageState();
}
class _EndurancePageState extends State<EndurancePage> {
Duration _duration = Duration();
Future<Null> _selectTime(BuildContext context) async {
final Duration picked =
await showDurationPicker(context: context, initialTime: _duration);
if (picked != null && picked != _duration) {
print('Time Selected: ${_duration.toString()}');
setState(() {
_duration = picked;
});
} }
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 100.0, bottom: 30.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Excer",
textAlign: TextAlign.center,
style:
const TextStyle(fontSize: 35.0, color: Colors.white),
),
Text(
"sices",
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 35.0,
color: Colors.white,
fontWeight: FontWeight.bold),
),
]),
),
Padding(
padding: EdgeInsets.only(bottom: 20.0),
child: Text(
"Select a few and set their duration.",
style: const TextStyle(color: Colors.white70, fontSize: 17.0),
),
),
SizedBox(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 25.0),
child: Container(
height: 1.0,
color: Colors.yellowAccent,
),
),
),
//---------------LIST OF EVENTS---------------
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"Push UPS",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () {
_selectTime(context);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"Pull UPS",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () {
_selectTime(context);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"What's Today?",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () {
_selectTime(context);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
],
),
),
);
}
}
So, I start the app and the initial time is 0 initial time
Then I set the time on the first button setting time
Now it changes the time on all buttons final state
how do I get different times for different buttons?
The problem is that your are using just one variable and when you change that variable all Text widgets get updated with the same value.
You need to use three duration variables, one for each value.
The simplest way is the following:
import 'package:flutter/material.dart';
import 'package:flutter_duration_picker/flutter_duration_picker.dart';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: EndurancePage(),
);
}
}
class EndurancePage extends StatefulWidget {
#override
_EndurancePageState createState() => _EndurancePageState();
}
class _EndurancePageState extends State<EndurancePage> {
Duration _duration1 = Duration();
Duration _duration2 = Duration();
Duration _duration3 = Duration();
Future<Null> _selectTime(BuildContext context, int timer) async {
if (timer == 1) {
final Duration picked =
await showDurationPicker(context: context, initialTime: _duration1);
if (picked != null && picked != _duration1) {
setState(() {
_duration1 = picked;
});
}
} else if (timer == 2) {
final Duration picked =
await showDurationPicker(context: context, initialTime: _duration2);
if (picked != null && picked != _duration2) {
setState(() {
_duration2 = picked;
});
}
} else if (timer == 3) {
final Duration picked =
await showDurationPicker(context: context, initialTime: _duration3);
if (picked != null && picked != _duration3) {
setState(() {
_duration3 = picked;
});
}
}
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 100.0, bottom: 30.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Excer",
textAlign: TextAlign.center,
style:
const TextStyle(fontSize: 35.0, color: Colors.white),
),
Text(
"sices",
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 35.0,
color: Colors.white,
fontWeight: FontWeight.bold),
),
]),
),
Padding(
padding: EdgeInsets.only(bottom: 20.0),
child: Text(
"Select a few and set their duration.",
style: const TextStyle(color: Colors.white70, fontSize: 17.0),
),
),
SizedBox(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 25.0),
child: Container(
height: 1.0,
color: Colors.yellowAccent,
),
),
),
//---------------LIST OF EVENTS---------------
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"Push UPS",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () {
_selectTime(context, 1);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration1.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"Pull UPS",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () {
_selectTime(context, 2);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration2.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"What's Today?",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () {
_selectTime(context, 3);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration3.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
],
),
),
);
}
}
Another option, passing the duration variable as a parameter would be the following:
import 'package:flutter/material.dart';
import 'package:flutter_duration_picker/flutter_duration_picker.dart';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: EndurancePage(),
);
}
}
class EndurancePage extends StatefulWidget {
#override
_EndurancePageState createState() => _EndurancePageState();
}
class _EndurancePageState extends State<EndurancePage> {
Duration _duration1 = Duration();
Duration _duration2 = Duration();
Duration _duration3 = Duration();
Future<Duration> _selectTime(BuildContext context, Duration duration) async {
final Duration picked =
await showDurationPicker(context: context, initialTime: duration);
if (picked != null && picked != duration) {
setState(() {});
return picked;
}
return null;
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 100.0, bottom: 30.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Excer",
textAlign: TextAlign.center,
style:
const TextStyle(fontSize: 35.0, color: Colors.white),
),
Text(
"sices",
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 35.0,
color: Colors.white,
fontWeight: FontWeight.bold),
),
]),
),
Padding(
padding: EdgeInsets.only(bottom: 20.0),
child: Text(
"Select a few and set their duration.",
style: const TextStyle(color: Colors.white70, fontSize: 17.0),
),
),
SizedBox(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 25.0),
child: Container(
height: 1.0,
color: Colors.yellowAccent,
),
),
),
//---------------LIST OF EVENTS---------------
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"Push UPS",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () async {
_duration1 = await _selectTime(context, _duration1);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration1.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"Pull UPS",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () async {
_duration2 = await _selectTime(context, _duration2);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration2.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 50.0, top: 20.0, bottom: 10.0),
child: Text(
"What's Today?",
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0),
child: FlatButton(
onPressed: () async {
_duration3 = await _selectTime(context, _duration3);
},
child: new Icon(
Icons.timelapse,
color: Colors.white,
),
),
),
Padding(
padding: EdgeInsets.only(top: 8.0, right: 20.0),
child: Text(
'${_duration3.inMinutes.toString()} min',
style: const TextStyle(color: Colors.white, fontSize: 25.0),
),
),
],
),
],
),
),
);
}
}