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'];
});
Related
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
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),
),
);
}
}
Hi in the below code when I am hit the signin button showing below error ,below details are passing as body I am able to print the data but response is not coming anything.
Enter mobile number and password able to see the response in postman but from app not getting any error.
Can any one help me where I did the mistake
{Mobile: 8250030771, Password: Test#123, Otp: N, Type: Patient}
Error: type 'Null' is not a 'bool' in boolean expression
SignIn.dart:
class SignIn extends StatefulWidget {
#override
_SignInState createState() => _SignInState();
}
class _SignInState extends State<SignIn> {
final _formKey = GlobalKey<FormState>();
late String mobile, password,otp,type;
bool isLoading=false;
TextEditingController _mobileController=new TextEditingController();
TextEditingController _passwordController=new TextEditingController();
TextEditingController _otpController=new TextEditingController();
GlobalKey<ScaffoldState>_scaffoldKey=GlobalKey();
late ScaffoldMessengerState scaffoldMessenger ;
#override
Widget build(BuildContext context) {
scaffoldMessenger = ScaffoldMessenger.of(context);
return Scaffold(
key: _scaffoldKey,
body: SingleChildScrollView(
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Stack(
children: <Widget>[
Container(
width: double.infinity,
height: double.infinity,
child: Image.asset(
"assets/background.jpg",
fit: BoxFit.fill,
),
),
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Image.asset(
"assets/logo.png",
height: 30,
width: 30,
alignment: Alignment.center,
)),
SizedBox(
height: 13,
),
Text(
"Learn With Us",
style: GoogleFonts.roboto(
textStyle: TextStyle(
fontSize: 27,
color: Colors.white,
letterSpacing: 1)),
),
SizedBox(
height: 5,
),
Container(
width: 180,
child: Text(
"RRTutors, Hyderabad",
textAlign: TextAlign.center,
style: GoogleFonts.roboto(
textStyle: TextStyle(
color: Colors.white54,
letterSpacing: 0.6,
fontSize: 11),
),
),
),
SizedBox(
height: 40,
),
Text(
"Sign In",
textAlign: TextAlign.center,
style: GoogleFonts.roboto(
textStyle: TextStyle(
color: Colors.white,
letterSpacing: 1,
fontSize: 23,
),
),
),
SizedBox(
height: 8,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Learn new Technologies 😋",
textAlign: TextAlign.center,
style: GoogleFonts.roboto(
textStyle: TextStyle(
color: Colors.white70,
letterSpacing: 1,
fontSize: 17,
),
),
),
],
),
SizedBox(
height: 30,
),
Form(
key: _formKey,
child: Container(
margin:
EdgeInsets.symmetric(vertical: 10, horizontal: 45),
child: Column(
children: <Widget>[
TextFormField(
style: TextStyle(
color: Colors.white,
),
controller: _mobileController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white)),
hintText: "Mobile",
hintStyle: TextStyle(
color: Colors.white70, fontSize: 15),
),
onSaved: (val) {
mobile = val!;
},
),
SizedBox(
height: 16,
),
TextFormField(
style: TextStyle(
color: Colors.white,
),
controller: _passwordController,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.white)),
hintText: "Password",
hintStyle: TextStyle(
color: Colors.white70, fontSize: 15),
),
onSaved: (val) {
mobile = val!;
},
),
SizedBox(
height: 30,
),
Stack(
children: [
GestureDetector(
onTap: () {
if(isLoading)
{
return;
}
if(_mobileController.text.isEmpty||_passwordController.text.isEmpty)
{
scaffoldMessenger.showSnackBar(SnackBar(content:Text("Please Fill all fileds")));
return;
}
login(_mobileController.text,_passwordController.text,);
setState(() {
isLoading=true;
});
//Navigator.pushReplacementNamed(context, "/home");
},
child: Container(
alignment: Alignment.center,
width: double.infinity,
padding: EdgeInsets.symmetric(
vertical: 10, horizontal: 0),
height: 50,
decoration: BoxDecoration(
border: Border.all(color: Colors.white),
borderRadius: BorderRadius.circular(50),
),
child: Text(
"SUBMIT",
textAlign: TextAlign.center,
style: GoogleFonts.roboto(
textStyle: TextStyle(
color: Colors.white,
fontSize: 16,
letterSpacing: 1)),
),
),
),
Positioned(child: (isLoading)?Center(child: Container(height:26,width: 26,child: CircularProgressIndicator(backgroundColor: Colors.green,))):Container(),right: 30,bottom: 0,top: 0,)
],
)
],
),
),
),
SizedBox(
height: 20,
),
Text(
"OR",
style: TextStyle(fontSize: 14, color: Colors.white60),
),
SizedBox(
height: 20,
),
Image.asset(
"assets/fingerprint.png",
height: 36,
width: 36,
),
SizedBox(
height: 30,
),
GestureDetector(
onTap: () {
Navigator.pushReplacementNamed(context, "/signup");
},
child: Text(
"Don't have an account?",
style: GoogleFonts.roboto(
textStyle: TextStyle(
color: Colors.white70,
fontSize: 13,
decoration: TextDecoration.underline,
letterSpacing: 0.5)),
),
)
],
),
),
],
),
),
));
}
login(mobile,password) async
{
Map data = {
'Mobile': mobile,
'Password': password,
'Otp':"N",
'Type':"Patient",
};
print(data.toString());
final response= await http.post(
Uri.parse(LOGIN),
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
body: data,
encoding: Encoding.getByName("utf-8")
) ;
setState(() {
isLoading=false;
});
if (response.statusCode == 200) {
Map<String,dynamic> resposne=jsonDecode(response.body);
if(!resposne['error'])
{
Map<String,dynamic>user=resposne['data'];
print(" LoginId ${user['LoginId']}");
savePref(1,user['name'],user['email'],user['id']);
Navigator.pushReplacementNamed(context, "/home");
}else{
print(" ${resposne['Message']}");
}
scaffoldMessenger.showSnackBar(SnackBar(content:Text("${resposne['Message']}")));
} else {
scaffoldMessenger.showSnackBar(SnackBar(content:Text("Please try again!")));
}
}
savePref(int value, String name, String email, int id) async {
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setInt("value", value);
preferences.setString("name", name);
preferences.setString("email", email);
preferences.setString("id", id.toString());
preferences.commit();
}
}
boolean expression is only contains true or false,
your data can be null then you can make if statement
bool data(data){
if(data==null){
return false;
}
else{
return data;
}
Your provided information didn't enough to solve the issue but I guess the issue is caused here:
Map<String,dynamic> resposne=jsonDecode(response.body);
if(!resposne['error']) // <---------- HERE
{
Map<String,dynamic>user=resposne['data'];
print(" LoginId ${user['LoginId']}");
savePref(1,user['name'],user['email'],user['id']);
Navigator.pushReplacementNamed(context, "/home");
}else{
print(" ${resposne['Message']}");
}
Because the response doesn't contain 'error' parameter so the result will be Null and you can't use ! with null value, so you can check if it's null or not before using ! like below:
if (response['error'] != null && !resposne['error']) {
You can try the answer and let me know if it works or not and give me the response result to make sure where the issue is and I will edit this answer to solve the issue.
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
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.