How to access values from another dart file? - flutter

I am new to flutter .Here I stored a value to a variable doc_id ,I want to use this value in another file called comments.dart . So I did something like below but it gives null value in comment.dart .
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));
Comment.dart
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
#override
Widget build(BuildContext context) {
return
Text(widget.postid);
}
}

Just create a global variable and assign from there
String postid = "";
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
#override
Widget build(BuildContext context) {
return
Text(postid);
}
}
void setPostID(String s) { // get value
postid = s;
}
Finally assign the value
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
setPostID(value.id); // set value
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));

You can use: https://pub.dev/packages/shared_preferences
await FirebaseFirestore.instance
.collection('blogs')
.add({
'title': titleController.text,
}).then((value) {
doc_id = value.id;
await prefs.setString('doc_id', postid); // set value
comment(postid: docid);
successAlert(context);
}).catchError((error) =>
errorAlert(context));
Finally use it in your class
class comment extends StatefulWidget {
final String? postid;
const comment({Key? key, this.postid}) : super(key: key);
_commentState createState() => _commentState();
}
class _commentState extends State<comment> {
#override
void initState() {
super.initState();
widget.postid = prefs.getString('doc_id'); // get the value
setState(() {});
}
#override
Widget build(BuildContext context) {
return
Text(postid);
}
}

Related

Flutter: Cannot pass a boolean type parameter through GoRouter

I want to pass a bool type parameter through GoRouter but I get this message error:
The argument type String cannot be assigned to the parameter type "bool"
But I can't really figure out where this error comes from.
Is String the only allowed type in queryParams ?
Here's my code:
main.dart
final GoRouter _router = GoRouter(routes: [
GoRoute(name: 'home', path: '/home', builder: ((context, state) => Home(
location: state.queryParams['location']!,
time: state.queryParams['time']!,
flag: state.queryParams['flag']!,
isDaytime: state.queryParams['isDaytime']!,
)
)
),
]);
world_time.dart
class WorldTime {
String _url = 'https://api-urlxxxxxxx';
String location;
String flag;
String time = '';
bool isDaytime = true;
WorldTime({ required this.location, required this.flag });
...
}
home.dart
class Home extends StatefulWidget {
String location;
String time;
String flag;
State isDaytime;
Home({
Key? key,
required this.location,
required this.time,
required this.flag,
required this.isDaytime,
}) : super(key: key);
#override
// ignore: library_private_types_in_public_api
_HomeState createState() => _HomeState();
}
loading.dart
class Loading extends StatefulWidget {
const Loading({Key? key}) : super(key: key);
#override
_LoadingState createState() => _LoadingState();
}
class _LoadingState extends State<Loading> {
void setupWorldTime() async {
WorldTime instance = WorldTime(location: 'London', flag: 'england.png');
await instance.getTime();
...
context.goNamed('home', queryParams: {
'location': instance.location,
'time': instance.time,
'flag': instance.flag,
'isDaytime': instance.isDaytime,
});
}
}

"'key' is required, but there's no corresponding argument" flutter error

How to solve this error?
The named parameter 'key' is required, but there's no corresponding argument. (Documentation) Try adding the required argument.
error
Future<void> onJoin() async {
// update input validation
setState(() {
_channelController.text.isEmpty
? _validateError = true
: _validateError = false;
});
if (_channelController.text.isNotEmpty) {
await _handleCameraAndMic(Permission.camera);
await _handleCameraAndMic(Permission.microphone);
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoCall(
channelName: _channelController.text,
role: _role,
),
),
);
}
}
class VideoCall
class VideoCall extends StatefulWidget {
final String channelName;
final ClientRole role;
const VideoCall({Key key, required this.channelName, required this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}
class _VideoCallState extends State<VideoCall> {
final _users = <int>[];
final _infoStrings = <String>[];
bool muted = false;
late RtcEngine _engine;
#override
void dispose() {
// clear users
_users.clear();
// destroy sdk
_engine.leaveChannel();
_engine.destroy();
super.dispose();
}
#override
void initState() {
super.initState();
// initialize agora sdk
initialize();
}
this is the videoCall class in there no any error shows.
when add "key" show this
When remove required property from key in video call class
show this error
In VideoCall class, key property set as a required, change it to optional:
class VideoCall extends StatefulWidget {
final String? channelName;
final ClientRole? role;
const VideoCall({Key? key, this.channelName, this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}

Flutter - cubit: ProviderNotFoundException

Im am trying to get userData by id to show userProfile. I create a cubitProfile for this reason but when I go to the profile page the app ProviderNotFoundException(T, context.widget.runtimeType) apears. Can u help me with this error?
Here is my code:
profile
class ProfileScreen extends StatelessWidget {
final String id;
const ProfileScreen({Key? key, required this.id}) : super(key: key);
#override
Widget build(BuildContext context) {
return BlocBuilder<ProfileCubit, ProfileStates>(builder: (context, state) {
var cubit = ProfileCubit.get(context);
return Scaffold(
...
profileCubit
class ProfileCubit extends Cubit<ProfileStates> {
ProfileCubit() : super(ProfileInitState());
static ProfileCubit get(context) => BlocProvider.of(context);
late UserData userData;
void getUserDataById(String id) {
emit(ProfileGetUserLoadingState());
FirebaseFirestore.instance.collection('users').doc(id).get().then((value) {
userData = UserData.fromJson(jsonDecode(jsonEncode(value.data())));
emit(ProfileGetUserSuccessState());
}).catchError((error) {
print(error);
emit(ProfileGetUserErrorState());
});
}
bool isSameUser(String uid) {
if (FirebaseAuth.instance.currentUser!.uid != uid) {
return false;
} else {
return true;
}
}
}

Store the filters selected in a variable

I have a code that is responsible for filtering data: the user choose the criteria that are important to him and clicks "Apply". And sees a list based on the selected filters.
But the applied filters are not saved for subsequent filtrations. And the next time user click on the "filters" button, the user cannot continue working with them from the last moment. He has to choose all the filters again.
How to make the filters to be saved and the user to continue working with the filters based on the previous selection?
filter_dialog.dart
class FilterDialog extends StatefulWidget {
final void Function(Map<String, List<String>?>) onApplyFilters;
const FilterDialog({Key? key, required this.onApplyFilters}) : super(key: key);
#override
State<FilterDialog> createState() => _FilterDialogState();
}
class _FilterDialogState extends State<FilterDialog> {
Map<String, List<String>?> filters = {};
void _handleCheckFilter(bool checked, String key, String value) {
final currentFilters = filters[key] ?? [];
if(checked) {
currentFilters.add(value);
} else {
currentFilters.remove(value);
}
filters[key] = currentFilters;
}
#override
.......
main_page.dart
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
#override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
List<Phone> filteredPhones = phoneList;
void _filter(Map<String, List<String>?> filters) {
setState(() {
filteredPhones = phoneList;
filters.forEach((key, value) {
if((value ?? []).isNotEmpty) {
filteredPhones = filteredPhones.where((phone) {
switch(key) {
case 'brand':
return value!.contains(phone.brand);
case 'version_OS':
return value!.contains(phone.version_OS);
case 'operation_system':
return value!.contains(phone.operation_system);
default:
return false;
}
}).toList();
}
});
});
}
#override
....
}
class Filter {
String name;
bool Function(Phone) filterFn;
Filter({required this.name, required this.filterFn});
}
custom_checkbox_tile.dart
class CustomCheckboxTile extends StatefulWidget {
final String label;
final void Function(bool)? onChange;
const CustomCheckboxTile({Key? key, required this.label, this.onChange}) : super(key: key);
#override
State<CustomCheckboxTile> createState() => _CustomCheckboxTileState();
}
class _CustomCheckboxTileState extends State<CustomCheckboxTile> {
bool checked = false;
#override
Widget build(BuildContext context) {
return Row(
children: [
Checkbox(
visualDensity: VisualDensity.compact,
value: checked,
onChanged: (_) {
setState(() {
checked = !checked;
if(widget.onChange != null) {
widget.onChange!(checked);
}
});
},
),
Text(widget.label),
],
);
}
}
its not simple to answer your qustion.
More changes should made.
I'm done it all.
Please Check Github

Assigning the sharedPreference value to a variable within the build

I have successfully stored a value as a string in the localStorage as below:
var acceptedCompany = jsonEncode('${item.company!.name!}');
print('storedCompany: $acceptedCompany'); // succesfully prints value as 'abc'
await sharedPref.save('savedCompany', acceptedCompany);
And now I want to read the stored value from another screen and assign it to a variable which I can then bind to my Text() widget. I have successfully accessed the value within my console. However when I try to assign the stored value to a variable, I get an error:
"Instance of Future<dynamic>"
Here is how am getting back the stored value:
class _SideBarState extends State < SideBar > {
SharedPref sharedPref = SharedPref();
var savedCompany;
String key = 'storedCompany';
#override
#override
void didChangeDependencies() {
getCompany();
super.didChangeDependencies();
}
getCompany() async {
savedCompany = await sharedPref.read(key);
print('getComp: $savedCompany'); // this returns the stored value i.e 'abc' but I can't assign this to the Text widget
}
#override
Widget build(BuildContext context) {
var savedCompany2 = getCompany();
print('getComp2: $savedCompany2'.toString()); // generates an error 'Instance of Future<dynamic>'
return Text($savedCompany2);
}
}
My SharedPref Class looks like this:
read(key) async {
final prefs = await SharedPreferences.getInstance();
final value = prefs.getString(key) ? ? 0;
// print('retrievedValue: ' + '$value');
return value;
}
save(key, value) async {
final prefs = await SharedPreferences.getInstance();
// prefs.setString(key, json.encode(value));
prefs.setString(key, value);
// print('savedToken:' + '$key');
}
How can I access the sharedPreference value and assign it to the variable that I can then bind to the Text widget?
To overcome the problem, you can either set the value after the initState or using FutureBuilder.
FutureBuilder:
class SideBar extends StatefulWidget {
const SideBar({Key? key}) : super(key: key);
#override
State<SideBar> createState() => _SideBarState();
}
class _SideBarState extends State<SideBar> {
SharedPref sharedPref = SharedPref();
String key = 'storedCompany';
Future<String> getCompany() async {
return await sharedPref.read(key);
}
#override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: getCompany(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return Text('Result: ${snapshot.data}');
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Center(child: CircularProgressIndicator());
}
},
);
}
}
After initState():
class SideBar extends StatefulWidget {
const SideBar({Key? key}) : super(key: key);
#override
State<SideBar> createState() => _SideBarState();
}
class _SideBarState extends State<SideBar> {
SharedPref sharedPref = SharedPref();
String key = 'storedCompany';
String? _companyName;
Future<void> getCompany() async {
var name = await sharedPref.read(key);
setState(() {
_companyName = name;
});
}
#override
void initState() {
super.initState();
getCompany();
}
#override
Widget build(BuildContext context) {
if(_companyName == null) return Center(child:CircularProgressIndicator());
return Text(_companyName!);
}
}