FLUTTER: How can I show the weather Icon from Open Weather Map? - flutter

I Would like to show open weather icons on my app but I'm not sure how I can do so. A sample of the data I'm getting from openweather map is below, and I've also included an example of how I'm getting the other data.
My Code:
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'GetLocation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
void main() {
runApp(AuraWeather());
}
class AuraWeather extends StatefulWidget {
#override
_AuraWeatherState createState() => _AuraWeatherState();
}
class _AuraWeatherState extends State<AuraWeather> {
var apiKey = '5f10958d807d5c7e333ec2e54c4a5b16';
var weatherIcon;
var description;
var maxTemp;
var minTemp;
var format_sunRise;
var sunRise;
var format_sunSet;
var format_sunRiseEnd;
var format_sunSetEnd;
var sunSet;
var temp;
var city;
#override
Widget build(BuildContext context) {
setState(() {
getLocation();
});
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(displayBackground()),
),
),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaY: 2, sigmaX: 2),
child: Container(
color: Colors.black.withOpacity(0.5),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
children: <Widget>[
Container(
child: Center(
child: Text(
'$city',
style: TextStyle(
fontSize: 25,
color: Colors.white,
fontFamily: 'Roboto',
),
),
),
),
Container(
child: Icon(
FontAwesomeIcons.locationArrow,
color: Colors.white,
),
),
Container(
margin: EdgeInsets.only(top: 80),
child: Text(
'$temp' + '°',
style: TextStyle(
fontSize: 50,
color: Colors.white,
fontWeight: FontWeight.w600),
),
),
],
),
Container(
margin: EdgeInsets.only(top: 30),
child: Icon(
Icons.wb_sunny,
color: Colors.white,
size: 120,
),
),
Container(
child: Center(
child: Text(
'$maxTemp ° | $minTemp °',
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
),
Container(
child: Text(
'$description',
style: TextStyle(fontSize: 20,
color: Colors.white,
fontFamily: 'Roboto mono',),
),
),
Container(
child: FlatButton(
child: Icon(
Icons.refresh,
color: Colors.white,
size: 40,
),
color: Colors.transparent,
onPressed: () {
setState(
() {
getLocation();
},
);
},
),
),
],
),
),
),
),
),
);
}
// display background images based on current time
displayBackground() {
var now = DateTime.now();
//var currentTime = DateFormat.jm().format(now);
print('Sunrise time $format_sunRise');
print('Sunset time $format_sunSet');
print('Current time $now');
if ((now.isAfter(format_sunRise)) && (now.isBefore(format_sunRiseEnd))){
print('Morning');
return'images/Moon.png';
}else if((now.isAfter(format_sunRiseEnd)) && (now.isBefore(format_sunSet))){
return 'images/Sun.png';
}else if ((now.isAfter(format_sunSet)) && (now.isBefore(format_sunSetEnd))){
print('Evening');
return 'images/Moon.png';
}else if((now.isAfter(format_sunSetEnd)) && (now.isBefore(format_sunRise))){
return 'images/Blood.png';
}
}
//getLocation
void getLocation() async {
Getlocation getlocation = Getlocation();
await getlocation.getCurrentLocation();
print(getlocation.latitude);
print(getlocation.longitude);
print(getlocation.city);
city = getlocation.city;
getTemp(getlocation.latitude, getlocation.longitude);
}
//Get current temp
Future<void> getTemp(double lat, double lon) async {
var now = DateTime.now();
DateFormat dateFormat = new DateFormat.Hm();
http.Response response = await http.get(
'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
//print(response.body);
var dataDecoded = jsonDecode(response.body);
description = dataDecoded['weather'][0]['description'];
temp = dataDecoded['main']['temp'];
temp = temp.toInt();
maxTemp = dataDecoded['main']['temp_max'];
maxTemp = maxTemp.toInt();
minTemp = dataDecoded['main']['temp_min'];
minTemp = minTemp.toInt();
sunRise = dataDecoded['sys']['sunrise'];
format_sunRise = DateTime.fromMillisecondsSinceEpoch(sunRise*1000);
format_sunRiseEnd = format_sunRise.add(Duration(hours: 1));
sunSet = dataDecoded['sys']['sunset'];
format_sunSet = DateTime.fromMillisecondsSinceEpoch(sunSet*1000);
format_sunSetEnd = format_sunSet.add(Duration(hours: 1));
print('Current temp $temp');
print('Max temp $maxTemp');
print('Min temp $minTemp');
}
}
SAMPLE DATA:
{
coord: {
lon: 139.01,
lat: 35.02
},
weather: [
{
id: 800,
main: "Clear",
description: "clear sky",
icon: "01n"
}
],
base: "stations",
main: {
temp: 285.514,
pressure: 1013.75,
humidity: 100,
temp_min: 285.514,
temp_max: 285.514,
sea_level: 1023.22,
grnd_level: 1013.75
},
wind: {
speed: 5.52,
deg: 311
},
clouds: {
all: 0
},
dt: 1485792967,
sys: {
message: 0.0025,
country: "JP",
sunrise: 1485726240,
sunset: 1485763863
},
id: 1907296,
name: "Tawarano",
cod: 200
}
From the data above, I'm able to get: temp, temp_max, temp_min and description. This is how I've done it.
CODE:
http.Response response = await http.get(
'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
//print(response.body);
var dataDecoded = jsonDecode(response.body);
description = dataDecoded['weather'][0]['description'];
temp = dataDecoded['main']['temp'];
temp = temp.toInt();
maxTemp = dataDecoded['main']['temp_max'];
maxTemp = maxTemp.toInt();
minTemp = dataDecoded['main']['temp_min'];
minTemp = minTemp.toInt();
How can I get to show the ICON from url? Icon will be shown inside container number 5 in Scaffold widgget.

For this api icon code have an url actually, and it will be like that in your case.
icon_url = "http://openweathermap.org/img/w/" + dataDecoded["weather"]["icon"] +".png"
and you can use it as image:
Image.network(icon_url),
or directly:
Image.network('http://openweathermap.org/img/w/${dataDecoded["weather"]["icon"]}.png',),

Related

The list I created appears on all rows of the expansionpanellist

I'm new to Flutter and I'm having problems with expansion panel lists. Firstly, let me explain what I'm trying to do. I have a map application that gets the user's current location when they press the "start" button and displays the distance, date and time when the journey is finished and the "finish" button is pressed. Then, this information is stored in an expansion panel list on a separate "history" page.
However, I also have a third button called "add location". This button appears when the "start" button is pressed and allows the user to add their current location while the journey is ongoing. These locations are added to a list called "tripLocations" within my code. Then, when the "finish" button is pressed, all of this information is added to the expansion panel list.
My problem is that every time a journey is finished, the "tripLocations" list is displayed in the expansion panel list and shows all of the previous locations. However, I want each row in the expansion panel list to represent a single journey and only show the locations that were added during that journey. Essentially, there should be a "tripLocations" list for each row in the expansion panel list and it should be reset every time a new journey is started.
The following codes belong to my button.dart page.
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:material_dialogs/shared/types.dart';
import 'package:material_dialogs/widgets/buttons/icon_outline_button.dart';
import 'package:yolumukaydet/constant/constant.dart';
import 'package:latlong/latlong.dart';
import 'package:material_dialogs/material_dialogs.dart';
import 'package:lottie/lottie.dart';
import 'package:material_dialogs/widgets/buttons/icon_button.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geocoding_platform_interface/geocoding_platform_interface.dart';
class GradientText extends StatelessWidget {
const GradientText(
this.text, {
required this.gradient,
this.style,
});
final String text;
final TextStyle? style;
final Gradient gradient;
#override
Widget build(BuildContext context) {
return ShaderMask(
blendMode: BlendMode.srcIn,
shaderCallback: (bounds) => gradient.createShader(
Rect.fromLTWH(0, 0, bounds.width, bounds.height),
),
child: Text(text, style: style),
);
}
}// texte gradient atamak için yapıldı
class StartHistory{
String city1;
String district1;
bool isExpanded;
StartHistory({
required this.city1,
required this.district1,
this.isExpanded = false,});
}//varış yeri konumu gösterme
class StartHistoryData {
static List<StartHistory> starthistory = [];
static void addStartHistory(String city1, String district1) {
starthistory.add(StartHistory(city1: city1, district1: district1));
}
}//varış yeri konumu gösterme
class TripLocation {
String address;
TripLocation({
required this.address,
});
}
class History {
String distance;
String date;
String time;
String city;
String district;
bool isExpanded;
History({
required this.distance,
required this.date,
required this.time,
required this.city,
required this.district,
this.isExpanded = false,
});
}
class HistoryData {
static List<History> history = [];
static List<TripLocation> tripLocations = [];
static void addHistory(String distance, String date, String time, String city, String district,) {
history.add(History(distance: distance, date: date, time: time, city: city, district: district,));
}
static void addTripLocation(TripLocation tripLocation) {
tripLocations.add(tripLocation);
}
}//mesafe ,tarih ve saat bilgileri
class Location {
final double latitude;
final double longitude;
final String note;
Location({
required this.latitude,
required this.longitude,
required this.note,
});
}//Konum Ekle butonu için konum alıyor
TextEditingController _noteController = TextEditingController();
List<Map<String, String>> _locations = [];
class ImageButton extends StatefulWidget {
#override
_ImageButtonState createState() => _ImageButtonState();
}
class _ImageButtonState extends State<ImageButton>with TickerProviderStateMixin {
bool _isStarted = false;
bool _isStopped = true;
void _getCurrentLocation() async {
final position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
setState(() {
if (position != null) {
_currentPosition = position;
}
});
}
late Position _startPosition;
late Position _currentPosition;
double _distance = 0.0;
String _time = "";
Geolocator geolocator = Geolocator();
int _selectedIndex = 0;
final List<String> imageList = [
'assets/images/pwb3.png',
'assets/images/pwb4.png',
];
void _onPressed1() {
setState(() {
_selectedIndex = (_selectedIndex + 1) % imageList.length;
});
// buraya butona tıklama olayında yapmanız gereken diğer işlemleri ekleyebilirsiniz
}
late AnimationController _controller;
bool isOpened = false;
#override
void initState() {
_getCurrentLocation();
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 400),
);
super.initState();
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container(
child: Align(
child: Stack(
children: <Widget>[
Container(
margin: EdgeInsets.only(left:160,top: 540.0,right:150),
width: 350.0,
height: 350.0,
child: FloatingActionButton(
child: Image.asset(
imageList[_selectedIndex],
height: 350.0,
width: 350.0,
),
onPressed: () {
setState(() {
_onPressed1();
isOpened = !isOpened;
if (isOpened) {
_controller.forward();
} else {
_controller.reverse();
}
});
},
),
),
Visibility(
visible: _isStarted,
child: Align(
alignment: Alignment.topRight,
child: Container(
width: 75.0,
height: 85.0,
margin: EdgeInsets.only(top: 540.0,right:50),
child: ScaleTransition(
scale: _controller,
child: FloatingActionButton(
backgroundColor: Constant.green,
child: Icon(Icons.add,size: 40.0,color: Constant.darkgrey,),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
String noteText = '';
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Container(
padding: EdgeInsets.all(20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Konumunuz Eklenecek',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18.0,
),
),
SizedBox(height: 10.0),
Divider(
color: Colors.black,
height: 1.0,
),
SizedBox(height: 10.0),
Text(
'Eklediğiniz konum ve notlar geçmiş sayfasına kaydedilecektir.',
style: TextStyle(
fontSize: 8.0,
),
),
SizedBox(height: 10.0),
TextField(
controller: _noteController,
decoration: InputDecoration(hintText: 'Notunuzu Ekleyin'),
),
SizedBox(height: 10.0),
ElevatedButton(
onPressed: () async {
_getCurrentLocation();
//BURASI İL VE İLÇE KONUM ADLARINI ALIYOR VE CİTY İLE DİSTİRCT DEĞİŞKENİN ATIYOR
List<Placemark> placemarks = await placemarkFromCoordinates(_currentPosition.latitude, _currentPosition.longitude);
String _address = '${placemarks[0].administrativeArea}, ${placemarks[1].subAdministrativeArea}';
var tripLocation = TripLocation(address: _address);
HistoryData.addTripLocation(tripLocation);
Navigator.pop(context);
setState(() {});
print("tripLocation");
},
child: Text('Tamam'),
),
],
),
),
);
},
);
},
),
),
),
)),// KONUM EKLE BUTTONU
Visibility(
visible: _isStarted,
child: Align(
alignment: Alignment.topLeft,
child: Container(
width: 75.0,
height: 75.0,
margin: EdgeInsets.only(left:50,top: 540.0,),
child: ScaleTransition(
scale: _controller,
child: FloatingActionButton(
backgroundColor: Constant.green,
child: Icon(Icons.stop,size:40.0,color: Constant.darkgrey,),
onPressed: () async {
setState(() {
_isStopped = true;
_isStarted = false;
});
//BURASI İL VE İLÇE KONUM ADLARINI ALIYOR VE CİTY İLE DİSTİRCT DEĞİŞKENİN ATIYOR
List<Placemark> placemarks = await placemarkFromCoordinates(_currentPosition.latitude, _currentPosition.longitude);
String? city = placemarks.isNotEmpty ? placemarks[0].administrativeArea: '';
String? district = placemarks.isNotEmpty ? placemarks[1].subAdministrativeArea : '';
//
//
_currentPosition = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
final Distance distance = new Distance();
var km = distance.as(
LengthUnit.Kilometer,
new LatLng(_startPosition.latitude, _startPosition.longitude),
new LatLng(_currentPosition.latitude,_currentPosition.longitude));
setState(() {
_time = DateTime.now().toString().substring(0, 19);
});
setState(() {
_distance = km as double;
});
showDialog(
context: context,
builder: (context) {
return AlertDialog(
backgroundColor: Constant.darkgrey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50.0),
),
title: Container(
alignment: Alignment.center,
child: Text('Mesafe Bilgisi',
style: TextStyle(
color: Colors.white
),)),
content: Container(
height: 400,
width: 400,
decoration: BoxDecoration(
color: Constant.darkgrey,
borderRadius: BorderRadius.circular(50.0),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
GradientText(
'$_distance km',
style: const TextStyle(fontSize: 80,
fontFamily: 'digital',
),
gradient: LinearGradient(colors: [
Colors.white54,
Colors.white70,
]),
),
Text("Tarih ${DateTime.now().toString().split(' ').first} / SAAT ${DateTime.now().toString().split(' ').last.substring(0, 8)}",
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.white
),
),
Text(
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.white
),"$city / $district"),
Container(
width:350,
height: 45,
child: FloatingActionButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(5),
topRight: Radius.circular(5),
bottomLeft: Radius.circular(5),
bottomRight: Radius.circular(5),
),
),
backgroundColor: Constant.green,
child: Text("TAMAM",
style: TextStyle(
color: Constant.darkgrey,
),),
onPressed: () {
HistoryData.addHistory("$_distance km", "${DateTime.now().toString().split(' ').first}", "${DateTime.now().toString().split(' ').last.substring(0, 8)}","$city","$district",);
Navigator.of(context).pop();
},
),
),
],
),
),
);
},
);
},
),
),
),
),
),// STOP BUTTONU
Visibility(
visible: _isStopped,
child: Align(
alignment: Alignment.topCenter,
child: Container(
width: 75.0,
height: 75.0,
margin: EdgeInsets.only(top: 440.0),
child: ScaleTransition(
scale: _controller,
child: FloatingActionButton(
backgroundColor: Constant.green,
child: Icon(Icons.start,size:40.0,color: Constant.darkgrey,),
onPressed: () async {
List<Placemark> placemarks = await placemarkFromCoordinates(_currentPosition.latitude, _currentPosition.longitude);
String? city1 = placemarks.isNotEmpty ? placemarks[0].administrativeArea: '';
String? district1 = placemarks.isNotEmpty ? placemarks[1].subAdministrativeArea : '';
StartHistoryData.addStartHistory("$city1","$district1");
setState(() {
_isStarted = true;
_isStopped = false;
});
_startPosition = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
},
),
),
),
),) // START BUTTONU
],
),
),
);
}
}
These codes belong to my historypage.dart file
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'package:yolumukaydet/appbar.dart';
import 'package:yolumukaydet/constant/constant.dart';
import 'package:yolumukaydet/menu.dart';
import 'package:yolumukaydet/navigator_bar.dart';
import 'package:flutter/material.dart';
import 'package:yolumukaydet/button.dart';
class GecmisPage extends StatefulWidget {
#override
_GecmisPageState createState() => _GecmisPageState();
}
class _GecmisPageState extends State<GecmisPage> {
List<Map<String, dynamic>> _locations = [];
void _removeItem(String date) {
int indexToRemove = HistoryData.history.indexWhere((element) =>
element.date == date);
setState(() {
HistoryData.history.removeAt(indexToRemove);
});
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
duration: const Duration(milliseconds: 600),
content: Text('#$date tarihli bilginiz silindi.')));
} // delete tuşu
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Constant.darkgrey,
appBar: AppBarPage(),
body: Column(
children: [
ExpansionPanelList(
expansionCallback: (int index, bool isExpanded) {
setState(() {
HistoryData.history[index].isExpanded = !isExpanded;
});
},
children: List.generate(
HistoryData.history.length,
(index) {
return ExpansionPanel(
backgroundColor: Constant.opacgrey,
headerBuilder: (BuildContext context, bool isExpanded) {
return ListTile(
title: Text("Tarih: " + HistoryData.history[index].date + " - " + HistoryData.history[index].city + "/" + HistoryData.history[index].district),
leading: IconButton(
onPressed: () => _removeItem(HistoryData.history[index].date),
icon: const Icon(
Icons.delete,
color: Constant.green,
),
),
);
},
body: Container(
height: 500,
width: double.infinity,
color: Constant.opacgrey,
child: Container(
height: 250,
width: double.infinity,
decoration: BoxDecoration(),//boş bırakıldı
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Mesafe :", style: TextStyle(fontSize: 18.0)),
Text("${HistoryData.history[index].distance}",
style: TextStyle(fontSize: 18.0)),
Text(" / ", style: TextStyle(fontSize: 18.0)),
Text("Saat :", style: TextStyle(fontSize: 18.0)),
Text("${HistoryData.history[index].time}",
style: TextStyle(fontSize: 18.0)),
],
),
),
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Varış Yeri :", style: TextStyle(fontSize: 18.0)),
Text("${StartHistoryData.starthistory[index].city1}",
style: TextStyle(fontSize: 18.0)),
Text(" / ", style: TextStyle(fontSize: 18.0)),
Text("${StartHistoryData.starthistory[index].district1}",
style: TextStyle(fontSize: 18.0)),
],
),
),
Container(
height: 400,
width: double.infinity,
decoration: BoxDecoration(
border: Border.all(color: Colors.black,width: 2)
),
child:
ListView.builder(
itemCount: HistoryData.tripLocations.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(HistoryData.tripLocations[index].address),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
setState(() {
HistoryData.tripLocations.removeAt(index);
});
},
),
);
},
)
),
],
),
),
),
),
isExpanded: HistoryData.history[index].isExpanded,
);
},
),
),
],
),
);
}
}
Where should I make the corrections here? I'm waiting for your help, thank you.

How to get certain user data when clicking to one specific item in List View Flutter from Firebase Realtime Database?

Currently, I am working on a Flutter project which is a tricycle booking system. I am developing two mobile apps in flutter, one for the passenger, and another for the driver. The functionality that I'm having a problem is that a passenger should ask or request a driver for his/her booking. On the driver's side, the driver will be able to see the list of active passengers (these are those who requested a ride). All these rides are stored in a list called pList. When a modal popup displays all the items (passengers that request a ride) in the pList, and then the driver chose one, the passenger data that is being fetched is only the passenger who FIRST requested a ride or the first item being listed in the list, and not the one who the driver has chosen. Do you have any idea why and how will I fix this problem?
What I want to happen is when the driver clicked on passenger C, passenger C data will be fetched and not passenger A (first to request). Any help will be much appreciated.
Here is my code:
readUserInformation(BuildContext context) async
{
Object? empty = "";
var passengerListKeys = Provider.of<AppInfo>(context, listen: false).activePassengerList;
for(String eachPassengerKey in passengerListKeys)
{
FirebaseDatabase.instance.ref()
.child("All Ride Requests")
.child(eachPassengerKey)
.once()
.then((snapData)
{
if(snapData.snapshot.value != null)
{
var passengerRequestInfo = snapData.snapshot.value;
if (passengerRequestInfo.toString() == empty.toString())
{
print("Same lang");
return null;
}
else
{
empty = passengerRequestInfo;
setState(() {
pList.add(passengerRequestInfo);
});
print("pList: " + pList.toString());
}
double originLat = double.parse((snapData.snapshot.value! as Map)["origin"]["latitude"]);
double originLng = double.parse((snapData.snapshot.value! as Map)["origin"]["longitude"]);
String originAddress = (snapData.snapshot.value! as Map)["originAddress"];
double destinationLat = double.parse((snapData.snapshot.value! as Map)["destination"]["latitude"]);
double destinationLng = double.parse((snapData.snapshot.value! as Map)["destination"]["longitude"]);
String destinationAddress = (snapData.snapshot.value! as Map)["destinationAddress"];
String userName = (snapData.snapshot.value! as Map)["username"];
String userId = (snapData.snapshot.value! as Map)["id"];
// String userPhone = (snapData.snapshot.value! as Map)["phone"];
String? rideRequestId = snapData.snapshot.key;
UserRideRequestInformation userRideRequestDetails = UserRideRequestInformation();
userRideRequestDetails.originLatLng = LatLng(originLat, originLng);
userRideRequestDetails.originAddress = originAddress;
userRideRequestDetails.destinationLatLng = LatLng(destinationLat, destinationLng);
userRideRequestDetails.destinationAddress = destinationAddress;
userRideRequestDetails.userName = userName;
userRideRequestDetails.userId = userId;
// userRideRequestDetails.userPhone = userPhone;
userRideRequestDetails.rideRequestId = rideRequestId;
showDialog(
context: context,
builder: (BuildContext context) => ConfirmDialogBox(
userRideRequestDetails: userRideRequestDetails,
),
);
}
else
{
Fluttertoast.showToast(msg: "This Ride Request Id do not exist.");
}
});
}
}
This is the UI for the modal popup:
import 'package:ehatid_driver_app/new_trip_screen.dart';
import 'package:ehatid_driver_app/user_ride_request_information.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:responsive_sizer/responsive_sizer.dart';
import 'global.dart';
class ConfirmDialogBox extends StatefulWidget
{
UserRideRequestInformation? userRideRequestDetails;
ConfirmDialogBox({this.userRideRequestDetails});
#override
State<ConfirmDialogBox> createState() => _ConfirmDialogBoxState();
}
class _ConfirmDialogBoxState extends State<ConfirmDialogBox>
{
final currentFirebaseUser = FirebaseAuth.instance.currentUser!;
#override
Widget build(BuildContext context)
{
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
backgroundColor: Colors.transparent,
elevation: 2,
child: Container(
margin: const EdgeInsets.all(8),
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.white,
),
child: ListView.builder(
itemCount: pList.length,
itemBuilder: (BuildContext context, int index)
{
return GestureDetector(
onTap: ()
{
setState(() {
chosenPassengerId = pList[index]["id"].toString();
print("Passenger Id: " + chosenPassengerId.toString());
FirebaseDatabase.instance.ref()
.child("passengers")
.child(chosenPassengerId!)
.once()
.then((snap)
{
print("Snap: " + snap.toString());
if(snap.snapshot.value != null)
{
//send notification to that specific driver
// sendNotificationToDriverNow(chosenPassengerId!);
//Display Waiting Response from a Driver UI
// showWaitingResponseFromPassengerUI();
print("Waiting for Response");
//Response from the driver
FirebaseDatabase.instance.ref()
.child("passengers")
.child(chosenPassengerId!)
.child("newRideStatus")
.set("accepted");
FirebaseDatabase.instance.ref()
.child("passengers")
.child(chosenPassengerId!)
.child("newRideStatus")
.onValue.listen((eventSnapshot)
{
//accept the ride request push notification
//(newRideStatus = accepted)
if(eventSnapshot.snapshot.value == "accepted")
{
//design and display ui for displaying driver information
rideRequest(context);
print("accepted");
}
});
}
else
{
Fluttertoast.showToast(msg: "This passenger do not exist. Try again.");
}
});
});
// Navigator.pop(context, "passengerChoosed");
},
child: Card(
color: Colors.white54,
elevation: 3,
shadowColor: Colors.green,
margin: EdgeInsets.all(8.0),
child: ListTile(
title: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 6.0),
child: Text(
pList[index]["username"],
style: const TextStyle(
fontFamily: 'Montserrat',
fontSize: 16,
color: Color(0xFF272727),
fontWeight: FontWeight.bold,
),
),
),
Icon(
Icons.verified_rounded,
color: Color(0xFF0CBC8B),
),
],
),
SizedBox(height: 1.h,),
//icon + pickup
Row(
children: [
Image.asset(
"assets/images/origin.png",
height: 26,
width: 26,
),
const SizedBox(width: 12,),
Expanded(
child: Container(
child: Text(
pList[index]["originAddress"],
style: const TextStyle(
fontFamily: 'Montserrat',
fontSize: 14,
color: Color(0xFF272727),
),
),
),
),
],
),
SizedBox(height: 1.h,),
Row(
children: [
Image.asset(
"assets/images/destination.png",
height: 26,
width: 26,
),
const SizedBox(width: 12,),
Expanded(
child: Container(
child: Text(
pList[index]["destinationAddress"],
style: const TextStyle(
fontFamily: 'Montserrat',
fontSize: 14,
color: Color(0xFF272727),
),
),
),
),
],
),
],
),
),
),
);
},
),
),
);
}
rideRequest(BuildContext context)
{
String getRideRequestId="";
FirebaseDatabase.instance.ref()
.child("drivers")
.child(currentFirebaseUser.uid)
.child("newRideStatus")
.set(widget.userRideRequestDetails!.rideRequestId);
FirebaseDatabase.instance.ref()
.child("drivers")
.child(currentFirebaseUser.uid)
.child("newRideStatus")
.once()
.then((snap)
{
if(snap.snapshot.value != null)
{
getRideRequestId = snap.snapshot.value.toString();
}
else
{
Fluttertoast.showToast(msg: "This ride request do not exists.");
}
if(getRideRequestId == widget.userRideRequestDetails!.rideRequestId)
{
FirebaseDatabase.instance.ref()
.child("drivers")
.child(currentFirebaseUser.uid)
.child("newRideStatus")
.set("accepted");
Fluttertoast.showToast(msg: "Accepted Successfully.");
//trip started now - send driver to new tripScreen
Navigator.push(context, MaterialPageRoute(builder: (c)=> NewTripScreen(
userRideRequestDetails: widget.userRideRequestDetails,
)));
}
else
{
Fluttertoast.showToast(msg: "This Ride Request do not exists.");
}
});
}
}

How Can i create a conditional questionnaire in Flutter

I am trying to build a questionnaire within an application
The idea is that the user answers questions
So every answer he gives is in one question
Accordingly he will receive the following question
For example if he answered a question with answer a
Will get one question
If he answered the same question with answer b
Will get another question later
how can i solve this
The code is attached
Thanks
import 'package:flutter/material.dart';
import 'package:gsheets/question_model.dart';
class QuizScreen extends StatefulWidget {
#override
State<QuizScreen> createState() => _QuizScreenState();
}
class _QuizScreenState extends State<QuizScreen> {
//define the datas
List<Question> questionList = getQuestions();
int currentQuestionIndex = 0;
int score = 0;
Answer? selectedAnswer;
int? nextQuestionId;
int? questionId;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 5, 50, 80),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
child:
Column(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
const Text(
"Simple Quiz App",
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
),
_questionWidget(),
_answerList(),
_nextButton(),
]),
),
);
}
_questionWidget() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Question ${currentQuestionIndex + 1}/${questionList.length.toString()}",
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 20),
Container(
alignment: Alignment.center,
width: double.infinity,
padding: const EdgeInsets.all(32),
decoration: BoxDecoration(
color: Colors.orangeAccent,
borderRadius: BorderRadius.circular(16),
),
child: Text(
questionList[currentQuestionIndex].questionText,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
)
],
);
}
_answerList() {
return Column(
children: questionList[currentQuestionIndex]
.answerList
.map(
(e) => _answerButton(e),
)
.toList(),
);
}
Widget _answerButton(Answer answer) {
bool isSelected = answer == selectedAnswer;
return Container(
width: double.infinity,
margin: const EdgeInsets.symmetric(vertical: 8),
height: 48,
child: ElevatedButton(
child: Text(answer.answerText),
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
primary: isSelected ? Colors.orangeAccent : Colors.white,
onPrimary: isSelected ? Colors.white : Colors.black,
),
onPressed: () {
// if (selectedAnswer == null) {
// if (answer.isCorrect) {
// score++;
// }
setState(() {
selectedAnswer = answer;
});
}
// },
),
);
}
_nextButton() {
// if(answer == )
bool isLastQuestion = false;
if (currentQuestionIndex == questionList.length - 1) {
isLastQuestion = true;
}
return Container(
width: MediaQuery.of(context).size.width * 0.5,
height: 48,
child: ElevatedButton(
child: Text(isLastQuestion ? "Submit" : "Next"),
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
primary: Colors.blueAccent,
onPrimary: Colors.white,
),
onPressed: () {
// if(nextQuestionId == questionId)
if (isLastQuestion) {
//display score
showDialog(context: context, builder: (_) => _showScoreDialog());
} else {
//next question
setState(() {
selectedAnswer = null;
currentQuestionIndex++;
});
}
},
),
);
}
_showScoreDialog() {
bool isPassed = false;
if (score >= questionList.length * 0.6) {
//pass if 60 %
isPassed = true;
}
String title = isPassed ? "Passed " : "Failed";
return AlertDialog(
title: Text(
title + " | Score is $score",
style: TextStyle(color: isPassed ? Colors.green : Colors.redAccent),
),
content: ElevatedButton(
child: const Text("Restart"),
onPressed: () {
Navigator.pop(context);
setState(() {
currentQuestionIndex = 0;
score = 0;
selectedAnswer = null;
});
},
),
);
}
}
========================
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gsheets/quiz.dart';
class Question {
final String questionText;
final List<Answer> answerList;
final int questionId;
Question(this.questionText, this.answerList, this.questionId);
}
class Answer {
final String answerText;
final int nextQuestionId;
// final bool selectedOption;
Answer(this.answerText, this.nextQuestionId);
}
List<Question> getQuestions() {
List<Question> list = [];
list.add(Question(
"Which school did you learn",
[
Answer("a", 3),
Answer("b", 2),
],
3,
));
list.add(Question(
"what is your age",
[
Answer("18", 3),
Answer("20", 5),
],
2,
));
list.add(Question(
"which car do you drive",
[
Answer("c", 3),
Answer("d", 2),
],
3,
));
return list;
}

The getter 'totalCartPrice' was called on null. Receiver: null Tried calling: totalCartPrice

The app itself works well. The product is added to the cart, but when you go to the cart page, this error appears. Maybe someone came across. I looked at similar errors, but my solution did not help.
The getter 'totalCartPrice' was called on null. Receiver: null Tried calling: totalCartPrice
enter code here
import 'package:flutter/material.dart';
import 'package:food_course/scr/helpers/order.dart';
import 'package:food_course/scr/helpers/style.dart';
import 'package:food_course/scr/models/cart_item.dart';
import 'package:food_course/scr/models/products.dart';
import 'package:food_course/scr/providers/app.dart';
import 'package:food_course/scr/providers/user.dart';
import 'package:food_course/scr/widgets/custom_text.dart';
import 'package:food_course/scr/widgets/loading.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';
class CartScreen extends StatefulWidget {
#override
_CartScreenState createState() => _CartScreenState();
}
class _CartScreenState extends State<CartScreen> {
final _key = GlobalKey<ScaffoldState>();
OrderServices _orderServices = OrderServices();
#override
Widget build(BuildContext context) {
final user = Provider.of<UserProvider>(context);
final app = Provider.of<AppProvider>(context);
return Scaffold(
key: _key,
appBar: AppBar(
iconTheme: IconThemeData(color: black),
backgroundColor: white,
elevation: 0.0,
title: CustomText(text: "Shopping Cart"),
leading: IconButton(
icon: Icon(Icons.close),
onPressed: () {
Navigator.pop(context);
}),
),
backgroundColor: white,
body: app.isLoading ? Loading() : ListView.builder(
itemCount: user.userModel.cart.length,
itemBuilder: (_, index) {
return Padding(
padding: const EdgeInsets.all(16),
child: Container(
height: 120,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: white,
boxShadow: [
BoxShadow(
color: red.withOpacity(0.2),
offset: Offset(3, 2),
blurRadius: 30)
]),
child: Row(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20),
topLeft: Radius.circular(20),
),
child: Image.network(
user.userModel.cart[index].image,
height: 120,
width: 140,
fit: BoxFit.fill,
),
),
SizedBox(
width: 10,
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
RichText(
text: TextSpan(children: [
TextSpan(
text: user.userModel.cart[index].name+ "\n",
style: TextStyle(
color: black,
fontSize: 20,
fontWeight: FontWeight.bold)),
TextSpan(
text: "\$${user.userModel.cart[index].price / 100} \n\n",
style: TextStyle(
color: black,
fontSize: 18,
fontWeight: FontWeight.w300)),
TextSpan(
text: "Quantity: ",
style: TextStyle(
color: grey,
fontSize: 16,
fontWeight: FontWeight.w400)),
TextSpan(
text: user.userModel.cart[index].quantity.toString(),
style: TextStyle(
color: primary,
fontSize: 16,
fontWeight: FontWeight.w400)),
]),
),
IconButton(
icon: Icon(
Icons.delete,
color: red,
),
onPressed: ()async{
app.changeLoading();
bool value = await user.removeFromCart(cartItem: user.userModel.cart[index]);
if(value){
user.reloadUserModel();
print("Item added to cart");
_key.currentState.showSnackBar(
SnackBar(content: Text("Removed from Cart!"))
);
app.changeLoading();
return;
}else{
print("ITEM WAS NOT REMOVED");
app.changeLoading();
}
})
],
),
)
],
),
),
);
}),
bottomNavigationBar: Container(
height: 70,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
RichText(
text: TextSpan(children: [
TextSpan(
text: "Total: ",
style: TextStyle(
color: grey,
fontSize: 22,
fontWeight: FontWeight.w400)),
TextSpan(
text: " \$${user.userModel.totalCartPrice / 100}",
style: TextStyle(
color: primary,
fontSize: 22,
fontWeight: FontWeight.normal)),
]),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20), color: primary),
child: FlatButton(
onPressed: () {
if(user.userModel.totalCartPrice == 0){
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20.0)), //this right here
child: Container(
height: 200,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Your cart is emty', textAlign: TextAlign.center,),
],
),
],
),
),
),
);
});
return;
}
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(20.0)), //this right here
child: Container(
height: 200,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('You will be charged \$${user.userModel.totalCartPrice / 100} upon delivery!', textAlign: TextAlign.center,),
SizedBox(
width: 320.0,
child: RaisedButton(
onPressed: () async{
var uuid = Uuid();
String id = uuid.v4();
_orderServices.createOrder(
userId: user.user.uid,
id: id,
description: "Some random description",
status: "complete",
totalPrice: user.userModel.totalCartPrice,
cart: user.userModel.cart
);
for(CartItemModel cartItem in user.userModel.cart){
bool value = await user.removeFromCart(cartItem: cartItem);
if(value){
user.reloadUserModel();
print("Item added to cart");
_key.currentState.showSnackBar(
SnackBar(content: Text("Removed from Cart!"))
);
}else{
print("ITEM WAS NOT REMOVED");
}
}
_key.currentState.showSnackBar(
SnackBar(content: Text("Order created!"))
);
Navigator.pop(context);
},
child: Text(
"Accept",
style: TextStyle(color: Colors.white),
),
color: const Color(0xFF1BC0C5),
),
),
SizedBox(
width: 320.0,
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
"Reject",
style: TextStyle(color: Colors.white),
),
color: red
),
)
],
),
),
),
);
});
},
child: CustomText(
text: "Check out",
size: 20,
color: white,
weight: FontWeight.normal,
)),
)
],
),
),
),
);
}
}
USER.dart
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:food_course/scr/helpers/order.dart';
import 'package:food_course/scr/helpers/user.dart';
import 'package:food_course/scr/models/cart_item.dart';
import 'package:food_course/scr/models/order.dart';
import 'package:food_course/scr/models/products.dart';
import 'package:food_course/scr/models/user.dart';
import 'package:uuid/uuid.dart';
enum Status{Uninitialized, Authenticated, Authenticating, Unauthenticated}
class UserProvider with ChangeNotifier{
FirebaseAuth _auth;
FirebaseUser _user;
Status _status = Status.Uninitialized;
Firestore _firestore = Firestore.instance;
UserServices _userServicse = UserServices();
OrderServices _orderServices = OrderServices();
UserModel _userModel;
// getter
UserModel get userModel => _userModel;
Status get status => _status;
FirebaseUser get user => _user;
// public variables
List<OrderModel> orders = [];
final formkey = GlobalKey<FormState>();
TextEditingController email = TextEditingController();
TextEditingController password = TextEditingController();
TextEditingController name = TextEditingController();
UserProvider.initialize(): _auth = FirebaseAuth.instance{
_auth.onAuthStateChanged.listen(_onStateChanged);
}
Future<bool> signIn()async{
try{
_status = Status.Authenticating;
notifyListeners();
await _auth.signInWithEmailAndPassword(email: email.text.trim(), password: password.text.trim());
return true;
}catch(e){
_status = Status.Unauthenticated;
notifyListeners();
print(e.toString());
return false;
}
}
Future<bool> signUp()async{
try{
_status = Status.Authenticating;
notifyListeners();
await _auth.createUserWithEmailAndPassword(email: email.text.trim(), password: password.text.trim()).then((result){
_firestore.collection('users').document(result.user.uid).setData({
'name':name.text,
'email':email.text,
'uid':result.user.uid,
"likedFood": [],
"likedRestaurants": []
});
});
return true;
}catch(e){
_status = Status.Unauthenticated;
notifyListeners();
print(e.toString());
return false;
}
}
Future signOut()async{
_auth.signOut();
_status = Status.Unauthenticated;
notifyListeners();
return Future.delayed(Duration.zero);
}
void clearController(){
name.text = "";
password.text = "";
email.text = "";
}
Future<void> reloadUserModel()async{
_userModel = await _userServicse.getUserById(user.uid);
notifyListeners();
}
Future<void> _onStateChanged(FirebaseUser firebaseUser) async{
if(firebaseUser == null){
_status = Status.Unauthenticated;
}else{
_user = firebaseUser;
_status = Status.Authenticated;
_userModel = await _userServicse.getUserById(user.uid);
}
notifyListeners();
}
Future<bool> addToCard({ProductModel product, int quantity})async{
print("THE PRODUC IS: ${product.toString()}");
print("THE qty IS: ${quantity.toString()}");
try{
var uuid = Uuid();
String cartItemId = uuid.v4();
List cart = _userModel.cart;
// bool itemExists = false;
Map cartItem ={
"id": cartItemId,
"name": product.name,
"image": product.image,
"restaurantId": product.restaurantId,
"totalRestaurantSale": product.price * quantity,
"productId": product.id,
"price": product.price,
"quantity": quantity
};
CartItemModel item = CartItemModel.fromMap(cartItem);
// if(!itemExists){
print("CART ITEMS ARE: ${cart.toString()}");
_userServicse.addToCart(userId: _user.uid, cartItem: item);
// }
return true;
}catch(e){
print("THE ERROR ${e.toString()}");
return false;
}
}
getOrders()async{
orders = await _orderServices.getUserOrders(userId: _user.uid);
notifyListeners();
}
Future<bool> removeFromCart({CartItemModel cartItem})async{
print("THE PRODUC IS: ${cartItem.toString()}");
try{
_userServicse.removeFromCart(userId: _user.uid, cartItem: cartItem);
return true;
}catch(e){
print("THE ERROR ${e.toString()}");
return false;
}
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:food_course/scr/providers/app.dart';
import 'package:food_course/scr/providers/category.dart';
import 'package:food_course/scr/providers/product.dart';
import 'package:food_course/scr/providers/restaurant.dart';
import 'package:food_course/scr/providers/user.dart';
import 'package:food_course/scr/screens/home.dart';
import 'package:food_course/scr/screens/login.dart';
import 'package:food_course/scr/screens/splash.dart';
import 'package:food_course/scr/widgets/loading.dart';
import 'package:provider/provider.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MultiProvider(
providers: [
ChangeNotifierProvider.value(value: AppProvider()),
ChangeNotifierProvider.value(value: UserProvider.initialize()),
ChangeNotifierProvider.value(value: CategoryProvider.initialize()),
ChangeNotifierProvider.value(value: RestaurantProvider.initialize()),
ChangeNotifierProvider.value(value: ProductProvider.initialize()),
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Food App',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: ScreensController())));
}
class ScreensController extends StatelessWidget {
#override
Widget build(BuildContext context) {
final auth = Provider.of<UserProvider>(context);
switch (auth.status) {
case Status.Uninitialized:
return Splash();
case Status.Unauthenticated:
case Status.Authenticating:
return LoginScreen();
case Status.Authenticated:
return Home();
default:
return LoginScreen();
}
}
}

Update page data after pop Navigation Updated #5

I have page Navigate to second page with variable (dID) with await to return same value if it has been changed ,at the second page if i did't do anything the value must return without any changes ,if i changed slider the value of (dID) must be increase by (1) ,but when i Navigate.pop the return value is same without increasing.
New update : After many test i did the problem is in the second page ,when i change the slider value i call a function to get the new value (newSavedDayId) ,and it is get it correctly but just inside the function ,after the slider change and get the new value ,it is returned to null :
newSavedDayId = Instance of 'Future<dynamic>'
second page which return value :
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../classes/viewdigree.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
class Days extends StatefulWidget {
#override
_DaysState createState() => _DaysState();
}
TextEditingController insertedDegree = TextEditingController();
class _DaysState extends State<Days> {
#override
Widget build(BuildContext context) {
List digrees = [];
var widthView = MediaQuery.of(context).size.width;
Map rdata = ModalRoute.of(context).settings.arguments;
var did = int.parse(rdata['dayId'].toString());
var u_id = rdata['userID'];
var m_id = rdata['courseId'];
var lang = rdata['lang'];
int w_id;
var newSavedDayId = rdata['savedDayID']; ----// received value
var username;
if (did <= 6) {
w_id = 1;
} else if (did <= 12) {
w_id = 2;
} else if (did <= 18) {
w_id = 3;
} else {
w_id = 4;
}
Future<List> fetchDigrees() async {
var url =
'https://srdtraining.com/api/controller/activities/activiy_list.php?d_id=$did&m_id=$m_id&u_id=$u_id';
var response = await http.get(url);
var data = jsonDecode(response.body);
print(data);
for (var x in data) {
Digree newdigree = Digree(
x['index'],
x['title_k'],
x['title_a'],
x['aya'],
x['link'],
x['activity_k'],
x['activity_a'],
x['act_id'],
x['mydigree']);
digrees.add(newdigree);
}
return digrees;
}
// Insert Func
send_degree(uId, actId, degree, w_id, did, m_id) async {
var sendData = {
'u_id': uId.toString(),
'act_id': actId.toString(),
'digree': degree.toString(),
'm_id': m_id.toString(),
'd_id': did.toString(),
'w_id': w_id.toString()
};
var url = 'https://srdtraining.com/api/controller/data/changedata.php';
var response = await http.post(url, body: sendData);
}
// End of Insert Func
//get user status .................. // this is the function to get new value
void getUserStatus() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
username = preferences.getString('username');
});
var url =
"http://srdtraining.com/api/controller/users/status_user.php?username=$username";
var response = await http.get(url);
var data = jsonDecode(response.body);
setState(() {
newSavedDayId = int.parse(data['d_id']); ----// Set New value by getting it from API after increasing by server.
});
print('newSavedDayId = $newSavedDayId');----// here it is print new value with increasing correctly
}
// End get user
return FutureBuilder(
future: fetchDigrees(),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Scaffold(
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('./assets/images/background.png'),
fit: BoxFit.cover)),
child: Center(
child: Text("Loading"),
),
),
);
} else {
YoutubePlayerController _controller = YoutubePlayerController(
initialVideoId: snapshot.data[0].link,
flags: YoutubePlayerFlags(
autoPlay: false,
mute: false,
));
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context, newSavedDayId);
}),
backgroundColor: Colors.pink[900],
title: Text(
'ژیان و قورئان',
style: TextStyle(fontSize: 32),
),
centerTitle: true,
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('./assets/images/background.png'),
fit: BoxFit.cover)),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: ListView(
padding: EdgeInsets.fromLTRB(25, 20, 25, 20),
shrinkWrap: true,
children: <Widget>[
Text(
lang == 'k'
? snapshot.data[0].title_k
: snapshot.data[0].title_a,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 32, color: Colors.white)),
//for top margin
SizedBox(height: 20.0),
// dexription
Container(
padding: const EdgeInsets.all(15),
width: widthView,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: const Color.fromRGBO(180, 80, 80, 0.3)),
child: Text(snapshot.data[0].aya,
textAlign: TextAlign.justify,
textDirection: TextDirection.rtl,
style: TextStyle(
fontFamily: 'Hafs',
fontSize: 26,
color: Colors.greenAccent[100])),
),
// now populating your ListView for `Directionality`
Column(
children: <Widget>[
// Start activities
Column(
children: snapshot.data.map<Widget>((item) {
double _value =
double.parse(item.mydigree.toString());
return Directionality(
textDirection: TextDirection.rtl,
child: Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
border: Border.all(
width: 2, color: Colors.white),
color:
Color.fromRGBO(230, 200, 200, 0.2)),
width: widthView,
padding: EdgeInsets.all(25),
margin: EdgeInsets.fromLTRB(0, 25, 0, 25),
child: Column(
children: <Widget>[
Text(
lang == 'k'
? item.activity_k
: item.activity_a,
textAlign: TextAlign.justify,
style: TextStyle(
fontSize: 28, color: Colors.white),
),
SizedBox(
height: 15,
),
Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.yellow[200]
.withOpacity(0.2),
spreadRadius: 2,
blurRadius: 20,
)
],
borderRadius:
BorderRadius.circular(15),
color:
Color.fromRGBO(0, 0, 0, 0.4)),
width: widthView,
padding: EdgeInsets.all(10),
child: Slider(
max: 100,
min: 0,
divisions: 100,
value: _value,
label: _value.round().toString(),
onChanged: (val) {
send_degree(u_id, item.act_id,
val, w_id, did, m_id);
},
onChangeEnd: (val) {
setState(() {
_value = val;
});
getUserStatus(); /// when i print the value here it is give me null
}),
),
SizedBox(
height: 10,
),
Text('$_value',
style: TextStyle(
fontSize: 26,
color: Colors.white))
],
),
)
],
),
);
}).toList()),
// End activities
SizedBox(
height: 20,
),
Text('خەلەکا ئەڤرو',
textAlign: TextAlign.right,
style:
TextStyle(fontSize: 26, color: Colors.yellow)),
SizedBox(
height: 20,
),
YoutubePlayer(
controller: _controller,
showVideoProgressIndicator: true,
progressIndicatorColor: Colors.blueAccent,
),
],
),
],
),
),
);
}
});
}
}
you can usef ValueChanged onChanged and do a callback to the page you want to update ,
you can passe the onChanged funtion on the parametre ,
when you change your value use : onChanged()
than in the page you want to see the update on call your function with set state ,
I solved it by merging two function in one :
Future<List> fetchDigrees() async {
var url =
'https://srdtraining.com/api/controller/activities/activiy_list.php?d_id=$did&m_id=$m_id&u_id=$u_id';
var response = await http.get(url);
var data = jsonDecode(response.body);
print(data);
for (var x in data) {
Digree newdigree = Digree(
x['index'],
x['title_k'],
x['title_a'],
x['aya'],
x['link'],
x['activity_k'],
x['activity_a'],
x['act_id'],
x['mydigree']);
digrees.add(newdigree);
}
return digrees;
}
void getUserStatus() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
username = preferences.getString('username');
});
var url =
"http://srdtraining.com/api/controller/users/status_user.php?username=$username";
var response = await http.get(url);
var data = jsonDecode(response.body);
setState(() {
newSavedDayId = int.parse(data['d_id']); ----// Set New value by getting it from API after increasing by server.
});
and they now like this and worked correctly :
Future<List> fetchDigrees() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
username = preferences.getString('username');
var url1 =
"http://srdtraining.com/api/controller/users/status_user.php?username=$username";
var response1 = await http.get(url1);
var data1 = jsonDecode(response1.body);
newSavedDayId = int.parse(data1['d_id']);
print('newSavedDayId before retrun = $newSavedDayId');
var url =
'https://srdtraining.com/api/controller/activities/activiy_list.php?d_id=$did&m_id=$m_id&u_id=$u_id';
var response = await http.get(url);
var data = jsonDecode(response.body);
print(data);
for (var x in data) {
Digree newdigree = Digree(
x['index'],
x['title_k'],
x['title_a'],
x['aya'],
x['link'],
x['activity_k'],
x['activity_a'],
x['act_id'],
x['mydigree']);
digrees.add(newdigree);
}
return digrees;
}