passing value to the classes without navigating - android

For the code below, on the press of the icon of the first class, I want to send data to the second class. First-class just contains the data that needs to pass to the second class. There is no way or not allowed to navigate from first to second class. The only option to navigate to the second class is from the third class. I tried creating a constructor in the second class and implemented
second page(data:_getData.text). But there is no way i am getting the value. I am just getting null.
**First class**
onPressed: () { setState(() => _getData.text);
**SecondPage(data:_getData.text);**
}
**Second class**
class SecondPage extends StatefulWidget {
String? data;
SecondPage({this.data});
#override
_SecondPageState createState() => _SecondPageState(data);
}
class _SecondPageState extends State<SecondPage> {
String? data;
_SecondPageState(this.data);
**Third class**
Get.to(SecondPage)

if you change a lot of states, you would use bloc or any state management. because it is good for the app. if you want only this thing, you use the below code.
First Screen
class FirstScreen extends StatefulWidget {
const FirstScreen({Key? key}) : super(key: key);
#override
State<FirstScreen> createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
String title = "no value_f";
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
ElevatedButton(
onPressed: () {
setState(() {
title = "value";
});
},
child: Text("Press")),
SecondScreen(title: title),
],
),
);
}
}
Second Screen
class SecondScreen extends StatefulWidget {
String title;
SecondScreen({Key? key, required this.title}) : super(key: key);
#override
State<SecondScreen> createState() => _SecondScreenState();
}
class _SecondScreenState extends State<SecondScreen> {
#override
void initState() {
widget.title = "no value";
super.initState();
}
#override
Widget build(BuildContext context) {
return Text(widget.title);
}
}

Related

Changing an attribute in a parent widget from a child widget

I am trying to create an app. I want to change an attribute in a parent class (so it can display a Visibility item, SlidingUpPanel) after submitting a query in the child class (which is a search bar).
I have tried using a callback function and followed How can I pass the callback to another StatefulWidget? but it doesn't seem to do anything when I submit my query in the search bar. Previously, I have also tried to use Navigator.push to call SlidingUpPanel directly but it resulted in a black screen with only SlidingUpPanel.
Parent class (Map):
class MapPage extends StatefulWidget {
const MapPage({Key? key}) : super(key: key);
#override
_MapPageState createState() => _MapPageState();
}
class _MapPageState extends State<MapPage> {
bool IsVisible = false;
void callbackFunction() {
setState(() {
IsVisible = true;
});
}
...
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Stack(
children: [
...
Visibility(
visible: IsVisible,
child: SlidingUpPanel()),
SearchPage(callbackFunction),
]),
);
}
}
Child class (Search Bar):
class SearchPage extends StatefulWidget {
final Function callback;
SearchPage(this.callback);
#override
_SearchPageState createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
...
#override
Widget build(BuildContext context) {
return FloatingSearchBar(
...
onSubmitted: (query) {
// callback here, but doesn't seem to do anything
widget.callback;
controller.close();
},
...
);
}
}
To actually call a function (execute it) you must use ().
Try calling the callback function like this:
onSubmitted: (query) {
// use () to actually call the function
widget.callback();
controller.close();
},

How to send a "button is pressed signal" to a higher class in widget tree hierarchy in flutter?

In my app tree hierarchy, I have a Stateful widget that represents the elements of a list. Let's call this class Item. This Widget contains an Image, some text, and a remove button that should remove the element when it's pressed. Later in the code, I have another Stateful class that holds the ListView and a List of Item which the ListView is created based on it.
My problem is that the onPressed() attribute of every Item is placed inside the item's class and not the upper class (the ListView) in which the remove operation should be handled. How can I fix this? How can I send a signal whenever the button is pressed to the parent widget in order to initiate removing the item?
import 'package:flutter/material.dart';
class Item extends StatefulWidget {
const Item({ Key? key }) : super(key: key);
#override
_ItemState createState() => _ItemState();
}
class _ItemState extends State<Item> {
#override
Widget build(BuildContext context) {
return Container(
child: Row(children: [
Image(),
Text('abc'),
Text('abc'),
Text('abc'),
ElevatedButton(onPressed: ????? , child: Text('RemoveButton'))
],),
);
}
}
class ListOfItems extends StatefulWidget {
const ListOfItems({ Key? key }) : super(key: key);
#override
_ListOfItemsState createState() => _ListOfItemsState();
}
class _ListOfItemsState extends State<ListOfItems> {
List<Item> ls = [];
int numOfItems = 0;
#override
Widget build(BuildContext context) {
return ListView(children: ls,)
}
}
Try like this
import 'package:flutter/material.dart';
class Item extends StatefulWidget {
final void Function(dynamic data) onPressedHandler;
const Item({ #required this.onPressedHandler, Key? key }) : super(key: key);
#override
_ItemState createState() => _ItemState();
}
class _ItemState extends State<Item> {
#override
Widget build(BuildContext context) {
return Container(
child: Row(children: [
Image(),
Text('abc'),
Text('abc'),
Text('abc'),
ElevatedButton(onPressed: () {
final data = 'Any additional data you want to paas';
widget.onPressedHandler(data);
} , child: Text('RemoveButton'))
],),
);
}
}
class ListOfItems extends StatefulWidget {
const ListOfItems({ Key? key }) : super(key: key);
#override
_ListOfItemsState createState() => _ListOfItemsState();
}
class _ListOfItemsState extends State<ListOfItems> {
List<Item> ls = [];
int numOfItems = 0;
onPressedHandler(data) {
}
#override
Widget build(BuildContext context) {
return ListView(children: [
Item(onPressedHandler: onPressedHandler),
],);
}
}

how to pass a class function to a widget in another class in flutter

i have 3 pages 1,2,3 i want to reach the 3rd page by clicking on a button in the 2nd page that implement a function from the 1st page
so how can i pass the function to the second page
so this is the class that has the function
class SharedPage extends StatefulWidget {
_SharedPageState createState() => _SharedPageState();
}
class _SharedPageState extends State<SharedPage> {
String _information = '';
void updateInformation(String information) {
setState(() => _information = information);
}
void moveToSecondPage() async {
final information = await Navigator.push(
context,
MaterialPageRoute(builder: (context) {
return AddShared(); /// this is the page that i want to reach
}),
);
updateInformation(information);
}
and this is the class that i want to pass the function to
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
var add = [
FlatButton(
shape: CircleBorder(),
child: Icon(
Icons.add,
color: Colors.red,
size: 30,
),
onPressed: () {
/// i want to implement the MoveToSecondScreen here
},
),
];

how to use setState() from another class or file?

I would like to change the body of HomeScreen from CustomDialog and it is another class. how can I do this ? I tried it in anyways but I can't do this.
this is the main file
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: HomeScreen(),));
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return SafeArea(child:Column(
children: <Widget>[
Text( Global.number.toString() ),
RaisedButton(child: Text("Click"),
onPressed: (){
showDialog(context: context,builder: (context){
return CustomDialog();
});
},)
],
));
}
}
And this is the Another File to Store global variable
class Global {
static double number = 10.0;
}
And this file is for Dialog
class CustomDialog extends StatefulWidget {
#override
_CustomDialogState createState() => _CustomDialogState();
}
class _CustomDialogState extends State<CustomDialog> {
#override
Widget build(BuildContext context) {
return Dialog(child: FlatButton(
child: Icon(Icons.add_circle,size: 30,),
onPressed: (){
setState(() {
Global.number++;
});
},
),);
}
}
You can pass the setState method of HomeScreen down to CustomDialog. I have shared a full working example based on the code you provided below.
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: HomeScreen(),));
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
void state() {
setState((){});
}
#override
Widget build(BuildContext context) {
return SafeArea(child:Column(
children: <Widget>[
Text( Global.number.toString() ),
RaisedButton(child: Text("Click"),
onPressed: (){
showDialog(context: context,builder: (context){
return CustomDialog(state);
});
},)
],
));
}
}
class Global {
static double number = 10.0;
}
class CustomDialog extends StatefulWidget {
final Function state;
CustomDialog(this.state);
#override
_CustomDialogState createState() => _CustomDialogState();
}
class _CustomDialogState extends State<CustomDialog> {
#override
Widget build(BuildContext context) {
return Dialog(child: FlatButton(
child: Icon(Icons.add_circle,size: 30,),
onPressed: (){
Global.number++;
widget.state();
},
),);
}
}
As you can see, I create a method parameter for CustomDialog and call that method following the change of Global.number. I created a wrapper to the setState function
void state() {
setState((){});
}
in HomeScreen and passed that method as the parameter to CustomDialog.
The state you set in CustomDialog is, well... the state of the dialog, not of the home screen.
To notify the home screen that some data changed, you can use a ChangeNotifierProvider to provide this data in a common super widget of home screen and the dialog, subscribe the data in the home screen, then access the data in the dialog and change it, then home screen will rebuild automatically.
Please check out Simple app state management for more detail.

AdMob not initialized from flutter notification

So I have a very simple application.
In Main I initialize Admob and call Root Widget.
From Root I show a Stateful Widget "Home".
From Home Call the Notification Logic.
When you "click" on the notification I send you again to Root.
When I first run the application, the adMobBanner works good.
After you receive the notification and you click on it, the app starts again, everything works as expected but the adMobBanner is a black banner now.
I think the Admob is not initialized properly. I tried to "Admob.initialize("appId")" in Root, in LocalNotification widget, everywhere, but still the same result.
Any ideas?
void main() async {
Admob.initialize("appId");
runApp(Root());
}
class Root extends StatelessWidget {
final String title = "Title";
Root();
#override
Widget build(BuildContext context) {
return MaterialApp(
title: title,
),
home: Home(title: title));
}
}
class Home extends StatefulWidget {
final String title;
Home({this.title});
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
final adMobBanner = AdmobBanner(adUnitId: "id", adSize: AdmobBannerSize.BANNER);
return Scaffold(
appBar: appBar,
body: Column(
children: <Widget>[
Container(),
adMobBanner,
LocalNotification()
],
),
);
}
}
class LocalNotification extends StatefulWidget {
#override
_LocalNotificationState createState() => _LocalNotificationState();
}
class _LocalNotificationState extends State<LocalNotification> {
void initState() {
super.initState();
//initialization notification plugin
showNotification(); //the notification with onSelectNotification callback
}
Future onSelectNotification(String payload) async {
await Navigator.push(context, MaterialPageRoute(builder: (context) {
return Root(); // send you to Root again
}));
}
#override
Widget build(BuildContext context) {
return Container();
}
}

Categories

Resources