How to send data from one widget to multiple widgets while Navigating in flutter? - 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.

Related

Need help removing favorites from SharedPreferences

Im recreating the Google Translate app for a school project. When you translate a text the user can save userInput and translation so that they can go back to se it. The problem with my code starts when the user wants to remove the previous saved translation. When the user presses StarButton the isStarred value changes and I want to delete this previously saved translation and userInput. The problem is that I need to get the index of where the user pressed StarButton and then send it to removeFromSharedPreferences(). I have tried multiple options and I will be grateful for every help.
Since there is no code provided i will assume that StarButton is a custom widget that you created. You could simply put an attribute index to its class and then pass it in the constructor. In this way, every time you initialize a StarButton, you're gonna pass and index that identifies its position.
class StarButton extends StatefulWidget {
final int index;
const StarButton ({ super.key, required this.index});
#override
State<StarButton> createState() => _StarButtonState();
}
class _StarButtonState extends State<StarButton> {
#override
Widget build(BuildContext context) {
return YourWidget();
}
}

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

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.

Flutter : how to fetch data and manage app state

I'm trying Flutter and I need (I think I do) an app state management to share datas across widgets and dont have to make an http request each time a route is called.
I have Places and Events, so I first load my Places to list them at creation of app state with :
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => AppStateModel()..fetchPlaces(),
...
)
);
}
When I click on a Place, I go on place/id screen and as Places doesnt have events props yet, I'm trying to load them with :
class PlacePageArguments {
final String id;
PlacePageArguments(this.id);
}
class PlacePage extends StatefulWidget {
const PlacePage({Key? key}) : super(key: key);
#override
State<PlacePage> createState() => _PlacePageState();
}
class _PlacePageState extends State<PlacePage> {
String id = '';
#override
Widget build(BuildContext context) {
final args =
ModalRoute.of(context)!.settings.arguments as PlacePageArguments;
return Consumer<AppStateModel>(builder: (context, appState, child) {
id = args.id;
appState.fetchEvents(id);
final place = appState.getPlaceById(id);
return Scaffold(...);
})
}
}
But for sure, as I notifyChange to update widget, It does an infinite loop on fetch events.
What should I do ?
What is the best to achieve something like that, maybe a simple futurBuilder will work, but I want to add events and stay on the same page (add event with modal) and want instant result.
thanks for all
You have two options for bringing in the data for this and none of them require ChangeNotifierProvider.
You can pass data via constructors. This works fine for small widget trees but it can easily get complicated.
You can use Providers. Providers allow you to manage data and functions in one class that stays in one file. For more deals please look here.

How can I use SharedPreferences to save a list of Strings in Flutter

I am trying to save a list of strings in flutter by using SharedPreferences. But my problem is that I have 8 different class in one .dart page and I want to display the saved strings on all the classes, so the SharedPreferences fonction has to be written outside of any class.
Here's one part of my 3000 line of code.
*`So my SharedPreferences fonction has to be outside of any classes (in this case here) and I need to be able to read it from the inside of the _MainScreenState class (in the text)`*
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
#override
Widget build(BuildContext context) {
return Container(
child: Text('one of the saved string value has to appear here');
);
}
}
Inserting a List into shared preferences is pretty straight forward. Have a look here: Can i put List into SharedPreferences in Flutter?
As for accessing it. SharedPreferences are available from anywhere in your App. So getting them to your classes should not be an issue. I would try with a static function, something like this:
class TestClass{
//This is available from anywhere in your project
//TestClass.getList();
static List<String> getList(){
//Get your list from preferences
//and return it.
}
}

How do I preserve the data in my textfield when navigating to another tabview

How do I preserve my data when I navigate between two different tabs in Flutter... Basically what I want to achieve is, on one side of the tab, I see users data, and on the other side of the tab, I want to be able to copy some of those user data and paste into some textfields on the other tab without losing the data in the text fields when I navigate back and forth and still also preserving the level of scrolling I might have done on the tab where the users data show.
You need to use AutomaticKeepAliveClientMixin This will ensure the State instance is not destroyed when leaving the screen.Extend your every tabview's state class with it and create an override method wannaKeepAlive and set it to true.Here is an example of a widget using AutomaticKeepAliveClientMixin.
class Example extends StatefulWidget {
#override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
return Container(
);
}
#override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
}