transfer data from one widget to the whole project in Flutter - flutter

I have some Radios and i want to take some different String based on which Radio is selected.
These Radios are located in another file, and there are several files which i want to take data and bring to my main file and than to save these data into my cloud firebase.
I created another file to store all these Informations but i cant save these data into this class. Can u show me some ways how can i do that?
//this is my informations class
class Informations {
String nom;
String lieu;
String type;
String typDePlonge;
String topographie;
String temperatureEau;
String courant;
String visibilite;
String niveauRequis;
String autonomie;
String quandPlonger;
String requin;
String mammifere;
String reptile;
String crustace;
String raie;
String limace;
String cephalopode;
String corail;
String poissonPelagique;
String poissonDeRecif;
String poissonDeFond;
String vmAutres;
String niveauAcceptes;
String activitesProposes;
String photo;
Informations(
{this.type,
this.nom,
this.photo,
this.activitesProposes,
this.autonomie,
this.cephalopode,
this.corail,
this.courant,
this.crustace,
this.lieu,
this.limace,
this.mammifere,
this.niveauAcceptes,
this.niveauRequis,
this.poissonDeFond,
this.poissonDeRecif,
this.poissonPelagique,
this.quandPlonger,
this.raie,
this.reptile,
this.requin,
this.temperatureEau,
this.topographie,
this.typDePlonge,
this.visibilite,
this.vmAutres});
}
//this is where i have my data.
//For each radio selected i want to take that string which is near the radio,
//the string which is shown at the text widget.
class ActivitesProposes extends StatefulWidget {
const ActivitesProposes({Key key}) : super(key: key);
#override
_ActivitesProposesState createState() => _ActivitesProposesState();
}
class _ActivitesProposesState extends State<ActivitesProposes> {
bool isStrechedActivities = false;
int groupValueActivities = 0;
void handleGroupValueActivities(int value) {
setState(() {
groupValueActivities = value;
});
}
#override
Widget build(BuildContext context) {
return new Padding(
padding: EdgeInsets.fromLTRB(20, 10, 20, 0),
child: Container(
// height: double.infinity,
width: double.infinity,
child: Padding(
padding: const EdgeInsets.all(2.0),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
border: GradientBorder.uniform(
width: 3.0,
gradient: LinearGradient(colors: <Color>[
Color(0xff59a5da),
Color(0xff60af6c)
], stops: [
0.3,
0.5
])),
borderRadius: BorderRadius.circular(30.0),
),
child: Column(
children: [
Container(
height: 45,
width: double.infinity,
padding: EdgeInsets.only(right: 10),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: <Color>[
Color(0xff59a5da),
Color(0xff60af6c),
]),
borderRadius: BorderRadius.all(
Radius.circular(25))),
constraints: BoxConstraints(
minHeight: 45,
minWidth: double.infinity,
),
alignment: Alignment.center,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Padding(
padding:
const EdgeInsets.symmetric(
horizontal: 10,
vertical: 10),
child: Text(
'Activités proposées',
style: new TextStyle(
fontSize: 20,
color: Colors.white,
decorationThickness: 3.0,
fontWeight: FontWeight.w900,
),
),
),
),
Padding(
padding: const EdgeInsets.all(0.0),
child: GestureDetector(
onTap: () {
setState(() {
isStrechedActivities =
!isStrechedActivities;
});
},
child: Icon(
isStrechedActivities
? Icons.keyboard_arrow_up
: Icons.keyboard_arrow_down,
color: Colors.white,
size: 40,
),
),
),
],
),
),
ExpandedSectionThreeRows(
expand: isStrechedActivities,
height: 100,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 18.0),
child: Container(
color: Colors.white70,
child: ListView(
padding: EdgeInsets.all(0),
shrinkWrap: true,
children: [
//controller: scrollController2,
Row(
children: [
Radio(
value: 0,
groupValue:
groupValueActivities,
onChanged:
handleGroupValueActivities),
new Text('cours plongée',
style: new TextStyle(
color:
groupValueActivities ==
0
? Colors.blue
.shade900
: Colors.black,
)),
],
),
Row(
children: [
Radio(
value: 1,
groupValue:
groupValueActivities,
onChanged:
handleGroupValueActivities),
new Text('sortie bateau',
style: new TextStyle(
color:
groupValueActivities ==
1
? Colors.blue
.shade900
: Colors
.black)),
],
),
Row(
children: [
Radio(
value: 2,
groupValue:
groupValueActivities,
onChanged:
handleGroupValueActivities),
new Text(
'location équipement',
style: new TextStyle(
color:
groupValueActivities ==
2
? Colors.blue
.shade900
: Colors.black,
)),
],
),
],
),
),
),
),
],
),
))
],
),
],
),
)),
);
}
}
//The button where im gonna register these data is on another file.

i fixed this really easy, i dont know why i wrote this question here anyway XD.
here is the code:
final informations = Informations();//added a reference for my informations class
// at the function of my radio i added this code and based on what radio
// is selected i add a diff text to my Informations class variable
void handleGroupValueActivities(int value) {
setState(() {
groupValueActivities = value;
if (groupValueActivities == 0){
informations.activitesProposes = 'cours plongee';
}else if(groupValueActivities == 1){
informations.activitesProposes = 'sortie bateau';
}else if(groupValueActivities == 2){
informations.activitesProposes = 'location equipment';
}else {
infromations.activitesProposes = null;
}// and if none of them is selected i return null.
print(informations.activitesProposes);
});
}

Related

Access dynamically properties of class in Dart / Flutter

In my application, the user enters notes that appear as cards one below the other in order of insertion on the main page. When entering notes he selects a colored label. I would like each note entered to have the text highlighted in the color of the chosen label.
How can I do that?
Can I get the property Color of the class Label to use it on the containers of the main page cards?
This is the label.dart code
import 'package:hive/hive.dart';
#HiveType(typeId: 3)
class Label extends HiveObject {
#HiveField(0)
String name;
#HiveField(1)
int color;
Label({this.name, this.color});
}
class LabelAdapter extends TypeAdapter<Label> {
#override
final typeId = 3;
#override
Label read(BinaryReader reader) {
var numOfFields = reader.readByte();
var fields = <int, dynamic>{
for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Label(
name: fields[0] as String,
color: fields[1] as int,
);
}
#override
void write(BinaryWriter writer, Label obj) {
writer
..writeByte(2)
..writeByte(0)
..write(obj.name)
..writeByte(1)
..write(obj.color);
}
}
This is the code of the card in the main page:
Container buildTaskCard(Task personModel) {
return Container(
margin: const EdgeInsets.fromLTRB(20, 5, 20, 5),
padding: const EdgeInsets.fromLTRB(18, 10, 10, 10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.black38,
offset: Offset(0.5, 0.5),
blurRadius: 2,
),
]),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(0, 4, 0, 4.0),
child: Text(
personModel.name,
style: regularBoldTxt,
),
),
Container(
height: 1,
color: Colors.grey[300],
),
const SizedBox(height: 10),
Row(
children: [
Container(
color: Colors.red,
width: 40,
height: 50,
),
Container(
margin: const EdgeInsets.only(left: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: [
Text(
personModel.description,
style: regularTxt.copyWith(color: Colors.black54),
),
const SizedBox(height: 5),
Text(
personModel.statusTag ?? "",
style: regularBoldTxt,
),
],
),
)
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Icon(Icons.timer),
const SizedBox(width: 5),
Text(
DateFormat("hh:ss a").format(personModel.startTime) +
" - " +
DateFormat("hh:ss a").format(personModel.endTime),
style: regularTxt,
),
const SizedBox(width: 10),
],
),
],
),
);
}
You can pass the color to your method:
Container buildTaskCard(Task personModel, [Color color = Colors.white]) {
return Container(
margin: const EdgeInsets.fromLTRB(20, 5, 20, 5),
padding: const EdgeInsets.fromLTRB(18, 10, 10, 10),
decoration: BoxDecoration(
color: color, //I believe you want to change this color?
borderRadius: BorderRadius.circular(10),
....
);
Then whenever you call this method you use the int of your label class to create your color and pass it
late final Widget container;
final Task task = ... //your taks;
final Label? label = box.get('myLabels') as Label?; // I dont't know where you call your box or what is its name
if (label != null) {
final Color color = Color(label.color);
container = buildTaskCard(mytask, color);
} else {
container = buildTaskCard(mytask);
}
....
And construct your widget with it

How to fetch data (Text) from Website in Flutter / dart?

So, I'm pretty new on Flutter (just about a week) and dart but I hope this Question is not toooooo stupid:
I'm trying to create an App for an existing Website (a forum). I dont want to use the flutter WebView, because I want to create an comepletly new Interface (The Website is not optimized for mobile View, that's why I'm builing this App).
The (german) Forum:
https://www.porsche-914.com/forum
I want to fetch the single forum topics as well as the posts itself including username, title and date and then map the text to a custom widget to display it. The Widget Part is no problem, it's already done but I cant figure out how to fetch that data from the website and how to store it.
I don't know, hope you can help me...
Thanks a lot for the taken time.
How the mapping should work:
fetched[index].title, fetched[index].text
Center(
child: NeumorphismPost(
title: fetched[index].title,
titleColor: Theme.of(context).cardColor,
textColor: Theme.of(context).cardColor,
text: fetched[index].text,
width: 370,
onTap: () {
_popupPage(context,
title: fetched[index].title,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
fetched[index].text,
style: TextStyle(
color: Theme.of(context).cardColor,
fontSize: 18),
),
),
);
},
),
),
This is my custom Widget:
import 'package:flutter/material.dart';
class NeumorphismPost extends StatefulWidget {
final double width;
final double height;
final double borderRadius;
final String title;
final String text;
final Color titleColor;
final Color textColor;
final double titleSize;
final double textSize;
final Function onTap;
NeumorphismPost({
this.width = 185,
this.height = 185,
this.title = "Title",
this.text = "",
this.borderRadius = 20,
this.titleColor = const Color(0xFF424242),
this.textColor = const Color(0xFF424242),
this.titleSize = 22,
this.textSize = 18,
required this.onTap,
});
#override
State<NeumorphismPost> createState() => _NeumorphismPostState();
}
class _NeumorphismPostState extends State<NeumorphismPost> {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Wrap(
direction: Axis.vertical,
children: [
SingleChildScrollView(
child: SizedBox(
height: widget.height,
width: widget.width,
child: GestureDetector(
onTap: () {},
child: Scaffold(
backgroundColor: Colors.transparent,
body: SizedBox(
height: widget.height,
width: widget.width,
child: Center(
child: Container(
height: widget.height,
width: widget.width,
decoration: BoxDecoration(
color: Theme.of(context).backgroundColor,
borderRadius:
BorderRadius.circular(widget.borderRadius),
boxShadow: [
BoxShadow(
color: Theme.of(context).hintColor,
offset: const Offset(5, 5),
blurRadius: 15,
spreadRadius: 1,
),
BoxShadow(
color: Theme.of(context).backgroundColor,
offset: Offset(-5, -5),
blurRadius: 15,
spreadRadius: 1,
)
],
),
child: Wrap(
direction: Axis.horizontal,
children: [
SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: <Widget>[
Wrap(
direction: Axis.horizontal,
children: [
SizedBox(
height: widget.height / 3,
child: Wrap(
children: [
Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets
.symmetric(
horizontal: 15,
vertical: 15),
child: Text(
widget.title,
textAlign:
TextAlign.center,
overflow:
TextOverflow.fade,
style: TextStyle(
fontSize:
widget.titleSize,
fontWeight:
FontWeight.bold,
color:
widget.titleColor,
),
),
),
],
),
],
),
),
],
),
Wrap(
direction: Axis.horizontal,
children: [
GestureDetector(
onTap: () {
widget.onTap();
},
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 5),
child: SizedBox(
height: widget.height / 1.38,
child: Padding(
padding:
const EdgeInsets.symmetric(
horizontal: 15,
vertical: 15),
child: Text(
widget.text,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: widget.textSize,
fontWeight:
FontWeight.normal,
color: widget.textColor,
),
),
),
),
),
),
],
),
],
),
),
),
],
),
),
),
),
),
),
),
),
],
),
);
}
}
From my point of view, you want to create a scraper. I checked the target website (https://www.porsche-914.com/forum), it can be scraped without any special technique (they don't have many Ajax calls (you may test by using Postman)). So it is a possible task. My suggestion flow is:
Load the raw HTML using any technique (http, dio, inappwebview ...)
Parse it using BeautifulSoup (https://pub.dev/packages/beautiful_soup_dart) (or any parser; it is just my favorite parser.)
Map it to your existing model.
Here is some example code. Hope it helps:
import 'package:http/http.dart' as http;
import 'package:beautiful_soup_dart/beautiful_soup.dart';
class TestParse {
excuteSample() async {
var url = Uri.parse('https://www.porsche-914.com/forum');
var response = await http.get(url);
BeautifulSoup bs = BeautifulSoup(response.body);
final allHeaderName = bs.findAll('td', attrs: {'class': 'oben'});
allHeaderName.forEach((element) {
print('the header: ${element.text}');
});
}
}
Here is the result:
The final result you need is a long story and long code. Hope this will give you a starting point.
UPDATE: I added the full demo code, using your requested code:
import 'package:beautiful_soup_dart/beautiful_soup.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(const MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final testparse = TestParse();
List<String> yourModelPleaseReplaceThis = [];
#override
void initState() {
super.initState();
excuteRequestAndParse();
}
excuteRequestAndParse() async {
final result =
await testparse.excuteSample(); //[1] i guess you missing this await
setState(() {
yourModelPleaseReplaceThis = result;
});
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: (context, index) {
return Center(
child: NeumorphismPost(
title: yourModelPleaseReplaceThis[index],
titleColor: Theme.of(context).cardColor,
textColor: Theme.of(context).cardColor,
text: yourModelPleaseReplaceThis[index],
width: 370,
onTap: () {
//THIS CODE BELOW IS YOUR CODE....
},
),
);
},
itemCount: yourModelPleaseReplaceThis.length,
);
}
}
// BELOW IS TESTING CODE....
class TestParse {
Future<List<String>> excuteSample() async {
var url = Uri.parse('https://www.porsche-914.com/forum');
var response = await http.get(url);
BeautifulSoup bs = BeautifulSoup(response.body);
final allHeaderName = bs.findAll('td', attrs: {'class': 'oben'});
allHeaderName.forEach((element) {
print('the header: ${element.text}');
});
return Future.value(allHeaderName.map((e) => e.text).toList());
}
}
class NeumorphismPost extends StatefulWidget {
final double width;
final double height;
final double borderRadius;
final String title;
final String text;
final Color titleColor;
final Color textColor;
final double titleSize;
final double textSize;
final Function onTap;
NeumorphismPost({
this.width = 185,
this.height = 185,
this.title = "Title",
this.text = "",
this.borderRadius = 20,
this.titleColor = const Color(0xFF424242),
this.textColor = const Color(0xFF424242),
this.titleSize = 22,
this.textSize = 18,
required this.onTap,
});
#override
State<NeumorphismPost> createState() => _NeumorphismPostState();
}
class _NeumorphismPostState extends State<NeumorphismPost> {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Wrap(
direction: Axis.vertical,
children: [
SingleChildScrollView(
child: SizedBox(
height: widget.height,
width: widget.width,
child: GestureDetector(
onTap: () {},
child: Scaffold(
backgroundColor: Colors.transparent,
body: SizedBox(
height: widget.height,
width: widget.width,
child: Center(
child: Container(
height: widget.height,
width: widget.width,
decoration: BoxDecoration(
color: Theme.of(context).backgroundColor,
borderRadius:
BorderRadius.circular(widget.borderRadius),
boxShadow: [
BoxShadow(
color: Theme.of(context).hintColor,
offset: const Offset(5, 5),
blurRadius: 15,
spreadRadius: 1,
),
BoxShadow(
color: Theme.of(context).backgroundColor,
offset: Offset(-5, -5),
blurRadius: 15,
spreadRadius: 1,
)
],
),
child: Wrap(
direction: Axis.horizontal,
children: [
SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: <Widget>[
Wrap(
direction: Axis.horizontal,
children: [
SizedBox(
height: widget.height / 3,
child: Wrap(
children: [
Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets
.symmetric(
horizontal: 15,
vertical: 15),
child: Text(
widget.title,
textAlign:
TextAlign.center,
overflow:
TextOverflow.fade,
style: TextStyle(
fontSize:
widget.titleSize,
fontWeight:
FontWeight.bold,
color:
widget.titleColor,
),
),
),
],
),
],
),
),
],
),
Wrap(
direction: Axis.horizontal,
children: [
GestureDetector(
onTap: () {
widget.onTap();
},
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 5),
child: SizedBox(
height: widget.height / 1.38,
child: Padding(
padding:
const EdgeInsets.symmetric(
horizontal: 15,
vertical: 15),
child: Text(
widget.text,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: widget.textSize,
fontWeight:
FontWeight.normal,
color: widget.textColor,
),
),
),
),
),
),
],
),
],
),
),
),
],
),
),
),
),
),
),
),
),
],
),
);
}
}
This is the result:
Please note:
This list I created is for sample, so it is just a list of Strings. You should create a complete Model.

ListView.builder returns Null check operator used on a null value

I'm developing a job search app that scrapes data from Indeed using Python which is being sent back to my Flutter UI as JSON data. The JSON data is being received successfully, however, Im getting an error of Null check operator used on a null value. The error appears to be stemming from the _jobSearch widget.
The relevant error-causing widget was ListView lib/ui/home_page.dart:256
Exception caught by scheduler library
Null check operator used on a null value
Here is the code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter_job_portal/theme/colors.dart';
import 'package:flutter_job_portal/theme/images.dart';
import 'package:flutter_job_portal/ui/bottom_menu_bar.dart';
import 'package:flutter_job_portal/ui/job_detail_page.dart';
String job = ""; //user's response will be assigned to this variable
String final_response = "";
final _formkey = GlobalKey<FormState>(); //key created to interact with the form
//function to validate and save user form
Future<void> _savingData() async {
final validation = _formkey.currentState.validate();
if (!validation) {
return;
}
_formkey.currentState.save();
}
Future<List<Job>> _getJobs() async {
final url = 'http://127.0.0.1:5000/job';
final response1 = await http.post(Uri.parse(url), body: json.encode({'job': job}));
final response2 = await http.get(Uri.parse(url));
final decoded = json.decode(response2.body);
List<Job> jobs = [];
for (var i in decoded) {
Job job = Job(i['Title'], i['Company'], i['Location'], i['Salary']);
jobs.add(job);
}
return jobs;
}
class Job {
final String title;
final String company;
final String location;
final String salary;
Job(this.title, this.company, this.location, this.salary);
}
class HomePage extends StatelessWidget {
const HomePage({Key key}) : super(key: key);
Widget _appBar(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Row(
children: [
CircleAvatar(
backgroundImage: AssetImage(Images.user1),
),
Spacer(),
IconButton(
icon: Icon(Icons.notifications_none_rounded),
onPressed: () {},
)
],
),
);
}
Widget _header(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 12),
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Hello, Alex!",
style: TextStyle(
fontSize: 15,
color: KColors.subtitle,
fontWeight: FontWeight.w500,
)),
SizedBox(
height: 6,
),
Text("Swipe to find your future",
style: TextStyle(
fontSize: 20,
color: KColors.title,
fontWeight: FontWeight.bold)),
SizedBox(
height: 10,
),
Row(
children: [
Expanded(
child: Container(
height: 45,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: KColors.lightGrey,
borderRadius: BorderRadius.circular(10)),
child: Form(
key: _formkey,
child: TextFormField(
decoration: InputDecoration(
hintText: 'Search job title or keywords',
),
onSaved: (value) {
job =
value; //getting data from the user form and assigning it to job
},
),
),
),
),
SizedBox(
width: 16,
),
Container(
decoration: BoxDecoration(
color: KColors.primary,
borderRadius: BorderRadius.circular(10),
),
height: 40,
child: IconButton(
color: KColors.primary,
icon: Icon(Icons.search, color: Colors.white),
onPressed: () async {
_savingData();
_getJobs();
},
),
)
],
)
],
),
);
}
Widget _recommendedSection(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
margin: EdgeInsets.symmetric(vertical: 12),
height: 200,
width: MediaQuery.of(context).size.width,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Recommended",
style: TextStyle(fontWeight: FontWeight.bold, color: KColors.title),
),
SizedBox(height: 10),
Expanded(
child: ListView(
scrollDirection: Axis.horizontal,
children: [
_recommendedJob(context,
company: "Google",
img: Images.google,
title: "UX Designer",
sub: "\$45,000 Remote",
isActive: true),
_recommendedJob(context,
company: "DropBox",
img: Images.dropbox,
title: "Research Assist",
sub: "\$45,000 Remote",
isActive: false)
],
),
),
],
),
);
}
Widget _recommendedJob(
BuildContext context, {
String img,
String company,
String title,
String sub,
bool isActive = false,
}) {
return Padding(
padding: const EdgeInsets.only(right: 10),
child: GestureDetector(
onTap: () {
Navigator.push(context, JobDetailPage.getJobDetail());
},
child: AspectRatio(
aspectRatio: 1.3,
child: Container(
decoration: BoxDecoration(
color: isActive ? KColors.primary : Colors.white,
borderRadius: BorderRadius.circular(7),
),
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 40,
width: 40,
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: isActive ? Colors.white : KColors.lightGrey,
borderRadius: BorderRadius.circular(7),
),
child: Image.asset(img),
),
SizedBox(height: 16),
Text(
company,
style: TextStyle(
fontSize: 12,
color: isActive ? Colors.white38 : KColors.subtitle,
),
),
SizedBox(height: 6),
Text(
title,
style: TextStyle(
fontSize: 14,
color: isActive ? Colors.white : KColors.title,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 6),
Text(
sub,
style: TextStyle(
fontSize: 12,
color: isActive ? Colors.white38 : KColors.subtitle,
),
),
],
),
),
),
),
);
}
Widget _jobSearch(BuildContext context) {
return new Container(
child: FutureBuilder(
future: _getJobs(),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Center(
child: Text('Loading...'),
));
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data[index].location),
);
},
);
}
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: KColors.background,
bottomNavigationBar: BottomMenuBar(),
body: SafeArea(
child: Container(
width: MediaQuery.of(context).size.width,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_appBar(context),
_header(context),
_recommendedSection(context),
_jobSearch(context)
],
),
),
),
),
);
}
}

Dart Null safety error : Null check operator used on a null value [duplicate]

This question already has answers here:
Null check operator used on a null value
(12 answers)
Closed last year.
I got this error, i understood it but i don't know how to fix it
This error occurs when I try to use the variables of the profilPicker class.
class MyDrawerPages extends StatefulWidget {
final ValueChanged<DrawerItem> onSelectedItem;
final VoidCallback? onClick;
const MyDrawerPages({
Key? key,
required this.onSelectedItem,
this.onClick,
}) : super(key: key);
#override
_MyDrawerPagesState createState() => _MyDrawerPagesState();
}
class _MyDrawerPagesState extends State<MyDrawerPages> {
final signUpKey = GlobalKey<_ProfilPickerState>();
var stringName = '';
var stringTeam = '';
#override
Widget build(BuildContext context) {
final name = signUpKey.currentState!.name;
final team = signUpKey.currentState!.team;
final bool isSignin = signUpKey.currentState!.isSignin;
return Scaffold(
body: Container(
color: const Color(0xFFE26A2C),
child: Column(
children: [
Padding(
key: signUpKey,
padding: const EdgeInsets.only(top: 20, bottom: 10),
child: ListTile(
leading: GestureDetector(
onTap: () {
Navigator.pushNamed(context, '/profil_picker');
},
child: const CircleAvatar(
backgroundColor: Color(0xFF463E3E),
child: Icon(
Icons.person,
size: 40,
color: Colors.white,
),
radius: 22,
),
),
title: Text(
isSignin ? name.toString().toUpperCase() : stringName,
style: const TextStyle(color: Colors.white),
),
subtitle: Text(
isSignin
? team.toString()
: stringTeam,
style: const TextStyle(color: Colors.white)),
),
),
SingleChildScrollView(
child: Column(children: [listTileDrawer(context)]),
),
],
),
),
);
}
here is the ProfilPicker class
class _ProfilPickerState extends State<ProfilPicker> {
bool visible = false;
File? image;
late String name;
late String team;
TextEditingController nameController = TextEditingController();
TextEditingController teamController = TextEditingController();
var isSignin = true;
Future pickeImage(ImageSource source) async {
final image = await ImagePicker().pickImage(source: source);
if (image == null) return;
final saveImage = await saveImagepermanently(image.path);
try {
setState(() {
this.image = saveImage;
});
} on Exception catch (e) {
// ignore: avoid_print
print('failed to pick image $e');
}
}
bool signUp = true;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
iconTheme: const IconThemeData(color: Colors.black),
backgroundColor: Colors.transparent,
elevation: 0,
),
backgroundColor: const Color(0xFFFFFFFF),
body: Center(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Column(
children: [
Container(
height: 150,
width: 150,
decoration: BoxDecoration(
color: Colors.blueGrey[200],
borderRadius: BorderRadius.circular(200)),
child: image != null
? ClipOval(
child: Image.file(
image!,
width: 150,
height: 150,
fit: BoxFit.cover,
),
)
: const Icon(
Icons.add_a_photo,
size: 30,
),
),
],
),
const SizedBox(
height: 100,
),
signUp
? Column(
children: [
Card(
margin:
const EdgeInsets.symmetric(horizontal: 40),
child: ListTile(
onTap: () {
setState(() {
pickeImage(ImageSource.gallery);
signUp = false;
});
},
leading: const Icon(Icons.image_outlined),
title: const Text("Gallery"),
),
color: Colors.blue[100]),
const SizedBox(
height: 10,
),
Card(
color: Colors.blue[100],
margin: const EdgeInsets.symmetric(horizontal: 40),
child: ListTile(
onTap: () {
setState(() {
pickeImage(ImageSource.camera);
signUp = false;
});
},
leading: const Icon(Icons.camera),
title: const Text("Camera"),
),
),
],
)
: Column(
children: [
_listTileBuilder(),
const SizedBox(
height: 30,
)
],
)
],
),
),
),
),
);
}
_listTileBuilder() {
return SingleChildScrollView(
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(10),
child: Column(
children: [
Container(
alignment: Alignment.topLeft,
padding: const EdgeInsets.fromLTRB(0, 10, 0, 4),
child: const Text('Profil')),
const Padding(
padding: EdgeInsets.only(right: 50),
child: Divider(
indent: 4,
color: Colors.black,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(10),
child: Column(
children: [
TextField(
controller: nameController,
maxLines: 1,
keyboardType: TextInputType.name,
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
filled: true,
fillColor: Colors.blue[100],
border: const OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.all(Radius.circular(10))),
label: const Text('name',
style: TextStyle(fontStyle: FontStyle.italic)),
),
),
const Padding(padding: EdgeInsets.all(4)),
TextField(
controller: teamController,
maxLines: 1,
keyboardType: TextInputType.name,
style: const TextStyle(fontSize: 14),
decoration: InputDecoration(
filled: true,
fillColor: Colors.blue[100],
border: const OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.all(Radius.circular(10))),
label: const Text(
'Team',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
)
],
),
),
const Padding(
padding: EdgeInsets.all(20),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {
// Navigator.pop();
},
child: Text(
'cancel'.toUpperCase(),
style: const TextStyle(fontWeight: FontWeight.bold),
)),
TextButton(
onPressed: () {
setState(() {
isSignin;
name = nameController.text;
team = teamController.text;
});
},
child: Text('ok'.toUpperCase(),
style: const TextStyle(fontWeight: FontWeight.bold)))
],
)
],
),
);
}
}
I don't have more details
thanks in advance!
I am listening to you,
be indulgent I am a beginner thank you!
error code
════════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building MyDrawerPages(dirty, state: _MyDrawerPagesState#a6f02):
Null check operator used on a null value
the problem is here
final name = signUpKey.currentState!.name;
final team = signUpKey.currentState!.team;
you're trying to access name and team where they are supposed to be not null, because they are marked late, but you don't assign them a value until you click on the ok button, which in the build method above they are null.
so you should make them nullable and check wether they are null or not instead. like this:
String? name;
String? team;
...
final name = signUpKey.currentState!.name ?? '';
final team = signUpKey.currentState!.team ?? '';
try this and tell me if it worked!
This error is caused When Null check operator (!) is used on variable with a null value.
You must track all the variable and find this null value or use other operator to solve the problem or check if the value is not null.
You can use ?? operator and give an alternative value if null like this
Text(name ?? 'Not Found')
You can find every thing you need about null aware operators in this article Go To Article

How update SharedPreferences value every time flutter

I am trying to get some values saved in the SharedPreferences . I have a few textfields with hint text and bottom navigation. Text entered into the textfield will be saved to shared preferences. I created class named loadUserData(); to save data locally using SharedPreferences .
void initState() {
super.initState();
isButtonDisabled = false;
loadUserData();
myFocusNode = FocusNode();
telephoneNode = FocusNode();
adresseNode = FocusNode();
emailNode = FocusNode();
passwordNode = FocusNode();
// future = boxApi.getUser();
// future = loadUserData();
}
loadUserData() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
var user = jsonDecode(localStorage.getString('user'));
if (user != null) {
setState(() {
name = user['name'];
phone = user['phone'];
adress = user['adress'];
email = user['email'];
});
}
}
After that , I tried to fetch data from SharedPreferences and display it on screen like that :
as you see the user can modify his name , adress... My problem is when the user modify some data ==> the data not updated until he login next time . I want the user can modify and update the new value at the same time ( don't need leave page) .
this my code ;
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return SafeArea(
/* minimum: const EdgeInsets.only(
top: 20.0, right: 5.0, left: 5.0, bottom: 10.0),*/
child: Center(
child: Scaffold(
resizeToAvoidBottomInset: true,
backgroundColor: Color(0xFFF6F7F8),
body: SingleChildScrollView(
child: Form(
key: _formKey,
child: FutureBuilder(
future: future,
// boxApi.getUser(),
//print(adress);
builder: (context, snapshot) {
// ignore: missing_return
// print(snapshot.data);
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('no connection');
case ConnectionState.active:
case ConnectionState.waiting:
return Center(
child: CircularProgressIndicator(),
);
break;
case ConnectionState.done:
if (snapshot.hasError) {
return Text('error');
} else if (snapshot.hasData) {
// String price = snapshot.data['body'].;
// print("${snapshot.data}");
return Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: [
Container(
padding: EdgeInsets.only(top: 16),
width: MediaQuery.of(context).size.width,
height:
MediaQuery.of(context).size.height / 4,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.white60,
blurRadius: 15.0,
offset: Offset(0.0, 0.75))
],
gradient: LinearGradient(
begin: Alignment(0.5, 0.85),
end: Alignment(0.48, -1.08),
colors: [
const Color(0xFF0B0C3A),
const Color(0xFF010611),
],
stops: [
0.0,
0.5,
],
),
//color: blue,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(32),
bottomLeft: Radius.circular(32))),
child: Column(
children: [
Row(
children: [
SizedBox(
width: 30,
),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
"$name",
style: TextStyle(
color: Colors.white,
fontSize: 25,
fontWeight:
FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(
"$phone",
style: TextStyle(
color: Colors.white60,
fontSize: 18,
//fontWeight: FontWeight.w300
),
),
])
],
),
Row(
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Container(
margin: EdgeInsets.symmetric(
vertical: 10),
width: size.width * 0.4,
child: ElevatedButton(
onPressed: () {
if (_nameController.text ==
"" &&
_emailController.text ==
"" &&
_adressController
.text ==
"") {
setState(() =>
isButtonDisabled =
true);
} else {
editUserProfile();
}
},
// editUserProfile();
child: Text('Enregistrer'),
style:
ElevatedButton.styleFrom(
primary: Colors.transparent,
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
20),
side: BorderSide(
color: Colors
.white)),
),
)),
SizedBox(
width: 20,
),
],
)
],
),
),
Container(
height: MediaQuery.of(context).size.height /
1.5,
// padding: EdgeInsets.only(
// top: 32,
// ),
child: Column(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Column(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Container(
width: size.width * 0.94,
child: Column(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.only(
left: 10,
right: 10,
bottom: 20,
top: 20),
child: Column(
mainAxisAlignment:
MainAxisAlignment
.start,
crossAxisAlignment:
CrossAxisAlignment
.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Text(
'Votre nom :',
style: TextStyle(
color: Color(
0xFF4053FCF),
fontSize: 16,
fontWeight:
FontWeight
.w600),
),
IconButton(
icon: Icon(
CommunityMaterialIcons
.pencil,
color: Colors
.grey,
),
onPressed: () {
myFocusNode
.requestFocus();
setState(() {
enableup =
true;
});
})
],
),
TextFormField(
controller:
_nameController,
enabled: enableup,
focusNode:
myFocusNode,
enableInteractiveSelection:
false,
keyboardType:
TextInputType
.text,
decoration: InputDecoration(
hintText: "$name",
hintStyle: TextStyle(
color: Colors
.grey,
fontSize:
14.0)),
),
I think you need to reload the Sharedpreference value.
SharedPreferences localStorage = await SharedPreferences.getInstance();
await localStorage.reload();
You should add the onChanged method to your TextFormField widgets to update the current state whenever a value is changed within.
// Example of adding onChanged to a TextFormField widget
TextFormField(
...,
onChanged: (String? value) {
// Update the state using setState.
setState(() => name = value);
},
),