Flutter HomeScreen(this.user) - Error: Too few positional arguments: 1 required - flutter

good day my fellow coders
I have a little problem where I am running firebase auth and cloud firestore in a flutter app with a curved nav bar.
Now here is my problem on home_screen.dart file I had to add 3 things in order to get my crud function to work see code below:
class HomeScreen extends StatelessWidget {
User user;
HomeScreen(this.user);
FirebaseFirestore firestore = FirebaseFirestore.instance;
#override
Widget build(BuildContext context) {
return Scaffold(........
Now within my main_screen where my curved navigation bar is situated there is a _pageOption = [] there see below:
class _mainScreenState extends State<mainScreen> {
int _page = 0;
final _pageOption = [
add pages here
HomeScreen(),
AddCardScreen(),
];
Where i have the issue is everything is imported and works fine however when i pass this.user on the HomeScreen(), as it should be then I receive the Error:
Can't access 'this' in a field initializer.

Inside HomeScreen() you already specify the required parameter User user Because of that when you init HomeScreen its throws an error.
So for solution, you can set User in HomeScreen as null-check operator.
class HomeScreen extends StatelessWidget {
User? user; // null check operator ?
HomeScreen(this.user);
}
Via this error will be cleared but before access user must check whether its null or not is mandatory.

Related

Flutter - Navigator.push() giving error "Context does not include a Navigator" on extends State<Main>

I've been creating a flutter app for a society and i'm using flutter.
I have created two "window" (I don't really know the technical terms on flutter),
The first one will display correctly with a button to switch on the second.
If you click on the button the other window will display correctly.
But, i want to use DeepLinks (for the notifications), and if i click on the link, the redirect in the _AccueilPageState to the Pub class (I'm using
Navigator.push(context,MaterialPageRoute(builder: (context) => Pub()));
I got the error
Navigator operation requested with a context that does not include a
Navigator
Someone can explain me what is wrong ? And maybe how to fix this issue !
Thanks,
Here you can see the hierachi of my code (I can't show all of it because of confidentiality):
void main() async{...}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return this;
}
#override
State<StatefulWidget> createState() => _AccueilPageState();
}
//Loading properties for MyApp(with the navigator.push in it)
class _AccueilPageState extends State<MyApp>{...}
//class loading FenetrePrincipale
class WebView extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(home : FenetrePrincipale(),
);
}
}
//Pub that return a MaterialApp(home:Builder:(context)=>Scaffold())
class Pub extends StatelessWidget{...}
//FenetrePrincipale that return a Scaffold
class FenetrePrincipale extends StatelessWidget{...}
//When on FenetrePrincipale we can push a button to open Pub but if you go trough a deeplink : _AccueilPageState
//Does not redirect on Pub and put the error :
//"Navigator operation requested with a context that does not include a Navigator"
Create a global key for the navigator so you can access it from anywhere in the application:
final GlobalKey<NavigatorState> myNavigatorKey = GlobalKey<NavigatorState>();
Assign it to your app when creating MaterialApp:
return MaterialApp(navigatorKey: myNavigatorKey,...);
Use it when pushing routes:
myNavigatorKey.currentState?.pushNamed(...);

Call constructor every time i access in a page Flutter

I want to call a constructor from a class everytime i login in app, the first time it's all ok but the next times is no called.
Im using stateless widget and provider.
Elements:
a simple class whit a constructor
class FetchDataFromTheWeb extends ChangeNotifier{
FetchDataFromTheWeb(){
loadingData();
}
Future loadingData(){
// And more code
}
}
My stateless widget
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
final conferencesServices = Provider.of<FetchDataFromTheWeb>(context);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Hello')),
body: ListWhitFetchedData()
);
}
}
Situation:
Im login in the app and the content is loaded by the method in constructor, but if im logout and login again whit a different account the constructor is not called and the data previously loaded is kept to the new user and they need to be load manually by the new user (and this is not the idea...).
Exist the way to recharge or recall the constructor when i want?
Thanks

in flutter when I pass model class in one of the Tab screen I get error in main Bottom Navigation screen

What I need to pass in BottomNav where I have mentioned all my tabs?
This is More TAB where I want to pass my MODEL class in widget:-
class More extends StatefulWidget{
final UserData currentUser; //UserData is model class
More(this.currentUser,) ;
#override
_MoreState createState() => new _MoreState();
}
And this is BottomNav screen, where I have mentioned all my TAB (I have commented line next to More()where I get error):-
class _BottomNavState extends State<BottomNav> {
int _index = 0;
List<Widget> _items = [
Home(),
UserProfile(FirebaseAuth.instance.currentUser,imageList: [],currentIndex:0),
Notifications(),
Chat(),
More(), /// I get error(red line below More() that I need to pass something here. What is that? So, that I can call my model class in widget.
];
#override
Widget build(BuildContext context) {
You have to provide an UserData to your More stateful widget since you declared that the More widget is expecting a UserData as a parameter
Such as:
final myUserData = UserData();
//...
More(myUserData),
You have defined your constructor like this
More(this.currentUser);
Which makes the currentUser as a mandatory positional parameter at position 0.
So while using your class, you should compulsorily pass an object of UserData like this,
More(UserData());
But in case, it is not mandatory, then you need to change your constructor to this,
More({ this.currentUser });

Flutter and GetxController - How to manage state unreliability?

I currently have many problems in my app with the get package for Flutter (https://pub.dev/packages/get) and the following state scenario:
For example I have a GetxController UserController. I need this controller in different Widgets, so I initialize it with Get.put() in the first widget and for the other child widgets I'll call it with Get.find(). That works.
But: I have some widgets that sometimes load before the controller got initialized and sometimes after. So I get many "UsersController" not found errors. Maybe there exists some workaround for this problem?
You could initialize your UsersController class using a Bindings class, prior to the start of your app.
Example
class UsersController extends GetxController {
static UsersController get i => Get.find();
int userId = 5;
}
class UsersBinding extends Bindings {
#override
void dependencies() {
Get.put<UsersController>(UsersController());
}
}
void main() async {
UsersBinding().dependencies();
runApp(MyApp());
}
Done this way your UsersController is guaranteed to be available everywhere in your app, prior to any Widgets loading.
class MyHomePage extends StatelessWidget {
final UsersController uc = Get.find();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GetX Bindings'),
),
body: Center(
child: Obx(() => Text('userId: ${uc.userId}')),
),
);
}
}
try to add
GetMaterialApp(
smartManagement: SmartManagement.keepFactory,
)
so that it can store factory of those instanse
or make sure add permanent
Get.put<Repo>(Repo(), permanent: true);
so that it never get deleted from memory
if u need to check class is initialized, u most keep the class in memory with permanent:trueand set tag:'anything you want for check this object' property in Get.put function, and now u can check
bool Get.isRegistered<className>(tag: 'TagInPut')
If there's no specific reason, you can just call Get.put(UserController()) at main function and wrap material app with GetMaterialApp.
if you are using get to provide an instance of something across your app
meaby https://pub.dev/packages/get_it could help you more. just be sure that you use allowReassignment==true so you can update your instance if you want save a full new controller, but if you want to use the same always get_it is perfect for you

How to send data from one widget to multiple widgets while Navigating in flutter?

Actually I was working on a GoogleSignIn button, where when signed in, I am navigating and sending data to another widget/page for the Drawer. What I want is that this accessed data from google should be sent to all other drawers built in scaffold for my entire app. I know there is a better approach for Global drawer, but having different drawers for each of my scaffold is my app's requirement.
This is the first widget's code:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
RestaurantHome(detailsUser: details)));
This is code of where I'm getting data using constructor for other widget.
class Home extends StatefulWidget {
final UserDetails detailsUser;
Home({Key key, this.detailsUser}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
In above scenario, I'm only able to send data to Home class using constructor. But I actually want to send data to multiple classes for accessing drawer details there while navigating at once.
Please guide me the best approach in this problem.
Think of me as a beginner. Thanks
you could provide your user details class by the entire app, a recommend using get_it(https://pub.dev/packages/get_it) to that
you create a class like:
class AuthController {
UserDetails detailsUser;
}
on login function:
void login() {
/// do whatherver you want
getIt<AuthController>().detailsUser = details;
}
on anywhere in your app
class Home extends StatefulWidget {
final UserDetails detailsUser = getIt<AuthController>().detailsUser;
Home();
#override
_HomeState createState() => _HomeState();
}
so this way you can acess the user details in any of your drawers.
just take a look at get_it documentation to see how to configure it, it's simple.
You can do this thing with redux ,provider,bloc. there is multiple to get data in any where in app.
If you want to create this pattern I can help your.