How to pass function to class attribute in flutter? - flutter

I am trying to assign a function to an class attribute. HOw can i assign that value to that class' attribue.
return MyCartListItem(
cartName: cartList[index]['english_name'],
cartQuantity: 2,
cartImage: path + img,
cartPrice: cartList[index]['mrp'].toString(),
cartIndex: cartList[index],
onItemRemoved: ?? ,
//trying to assing function here
);
const MyCartListItem(
{Key? key,
...
required this.onItemRemoved,
required this.onItemRemoved(index)})
: super(key: key);
final String cartName;
final int cartQuantity;
final String cartImage;
final String cartPrice;
final int cartIndex;
final Function onItemRemoved;
// func here
#override
State<MyCartListItem> createState() => _MyCartListItemState();
}

onItemRemoved(){
}
return MyCartListItem(
cartName: cartList[index]['english_name'],
cartQuantity: 2,
cartImage: path + img,
cartPrice: cartList[index]['mrp'].toString(),
cartIndex: cartList[index],
onItemRemoved: onItemRemoved ,
//trying to assing function here
);

so you have a function like this:
onTap({required String message}){
print(message);
}
in your class pass function argument like this:
class ClassTest extends StatelessWidget {
final Function({required String message}) onTap;
const ClassTest({Key? key, required this.onTap}) : super(key: key);
#override
Widget build(BuildContext context) {
return InkWell(
onTap: ()=>onTap(message: 'your mesage'),
child: Container(),
);
}
}

Related

How to access values from another dart file?

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);
}
}

How to set default value of function in a constructor (Flutter)

I want to set default function in my child Widget in a constructor.
Basically, I have two widgets
Login (Parent Widget)
AppButton (Child Widget)
Here is my AppButton.dart
And I am calling this child widget in Login.dart (Parent) like this:
AppButton(title: "Login")
Please give me a way that to set default function without making "onPress" required for it's Parent (Login.dart)
TIA
Only static value can be set as default value in constructor, so you need define you function as static like this:
class AppButton extends StatefulWidget {
final Function onPress;
const AppButton({Key? key, this.onPress = _onPress}) : super(key: key);
static void _onPress(){}
#override
State<AppButton> createState() => _AppButtonState();
}
just make it nullable:
class MyButton extends StatefulWidget {
final void Function()? onPress;
final String title;
const MyButton({Key? key, this.onPress, required this.title}) : super(key: key);
#override
State<MyButton> createState() => _MyButtonState();
}
class _MyButtonState extends State<MyButton> {
void Function() defaultOnPress = (){
// your default function here
};
#override
Widget build(BuildContext context) {
return ElevatedButton(onPressed: widget.onPress ?? defaultOnPress, child: const Text("my button"));
}
}
still you can get const constructor
you could put "static" before childOnPress()

Flutter Stateful Constructor Const Problem

I'm following tutorial on udemy and i found this weird error and i already read some doccumentation and i still didnt find the right answer to have constructor with initail value.
her is my code
class MapScreen extends StatefulWidget {
final PlaceLocation initialLocation;
final bool isSelecting;
const MapScreen({Key? key, this.initialLocation = PlaceLocation( //here there is an error "The default value of an optional parameter must be constant. (Documentation)"
latittude: 37.422,
longitude: -122.084,
address: "Example stree no 1",
), this.isSelecting = false}) : super(key: key);
#override
_MapScreenState createState() => _MapScreenState();
}
however if i delete those const new error come out
class MapScreen extends StatefulWidget {
final PlaceLocation initialLocation;
final bool isSelecting;
MapScreen({Key? key, this.initialLocation = PlaceLocation( //The default value of an optional parameter must be constant. (Documentation)
latittude: 37.422,
longitude: -122.084,
address: "Jl. Imambonjol",
), this.isSelecting = false}) : super(key: key);
#override
_MapScreenState createState() => _MapScreenState();
}
i also tried to follow the instruction and modify my code like this:
class MapScreen extends StatefulWidget {
final PlaceLocation initialLocation;
final bool isSelecting;
MapScreen({
this.initialLocation =
const PlaceLocation(latitude: 37.422, longitude: -122.084),
this.isSelecting = false,
});
#override
_MapScreenState createState() => _MapScreenState();
}
but the error still came out
I was able to fix your mistake, below I will attach the solution code and a screenshot of the console:
// Fake model:
class PlaceLocation {
final double latittude;
final double longitude;
final String address;
// Make this constructor const to solve your problem:
const PlaceLocation(
{required this.latittude,
required this.longitude,
required this.address});
}
class MapScreen extends StatefulWidget {
final PlaceLocation initialLocation;
final bool isSelecting;
// Also don't forget to put const before PlaceLocation() in this constructor:
const MapScreen(
{Key? key,
this.initialLocation = const PlaceLocation(
latittude: 37.422,
longitude: -122.084,
address: "Example stree no 1",
),
this.isSelecting = false})
: super(key: key);
#override
_MapScreenState createState() => _MapScreenState();
}
class _MapScreenState extends State<MapScreen> {
#override
Widget build(BuildContext context) {
// Console test to check default values:
print("lattitude: " +
MapScreen().initialLocation.latittude.toString() +
"\nlongitude: " +
MapScreen().initialLocation.longitude.toString() +
"\naddress: " +
MapScreen().initialLocation.address.toString());
return Scaffold(body: Container());
}
}
All you have to do is make your model (PlaceLocation) constructor const.

Null value in Flutter widget inside initState method

It's the first time a use Flutter (2.8.1) and I'having problems trying to undestrand what's going wrong.
I have a Stateful widget like this:
class SimpleWidget extends StatefulWidget {
const SimpleWidget({Key key, #required this.aValue}) : super(key: key);
final Type2 aValue;
#override
_SimpleWidgetState createState() => _SimpleWidgetState();
}
class _SimpleWidgetState extends State<SimpleWidget> {
Type1 from;
Type1 to;
#override
void initState() {
print('mounted: $mounted'); // true
print('widget.aValue: ${widget.aValue}'); // null <-- WHY IS THIS NULL?
super.initState();
from = ...;
to = ...;
}
...
}
that I call in this way:
List<Type1> breakTimes = await showDialog(
context: context,
builder: (context) {
print('currentElement.aValue: ${currentElement.aValue}'); // not null
return SimpleWidget(aValue: currentElement.aValue);
},
);
Why is widget.aValue == null in initInstance()? How can I solve it?
There is wrong in your code :
Chane this to this:
class SimpleWidget extends StatefulWidget {
final Type2 aValue; // initialize 1st
const SimpleWidget({Key key, #required this.aValue}) : super(key: key);
#override
_SimpleWidgetState createState() => _SimpleWidgetState();
}

How does flutter VSCode snippets to extract widget work?

When I use VSCode snippet Extract Widget, I have the following :
class MyExtractedWidget extends StatelessWidget {
const MyExtractedWidget({
Key key,
#required T someVariable,
}) : _someVariable = someVariable,
super(key: key);
final T _someVariable;
#override
Widget build(BuildContext context){ return Container(); }
}
However, I am used to write constructors the following way :
class MyExtractedWidget extends StatelessWidget {
const MyExtractedWidget({
Key key,
#required this.someVariable, // Directly accessing variable using "this"
}) : super(key: key);
final T someVariable;
#override
Widget build(BuildContext context){ return Container(); }
}
Do you know why snippets' constructors use a temporary variable instead of directly writing in the variable?
Is it related to encapsulation? If yes, I cannot understand why, as an extracted Widget is written in the same file, and that "underscored" variables are accessible in whole file.
EDIT
I tried with another widget and I have a kind of mix :
class Test extends StatelessWidget {
const Test({
Key key,
#required List<SortedExpense> sortedExpenses,
#required this.expensesSink,
}) : _sortedExpenses = sortedExpenses, super(key: key);
final List<SortedExpense> _sortedExpenses;
final StreamSink<List<Expense>> expensesSink;
...
This is based on the privacy of the variables you're extracting.
For example, the following widget:
Text(_count.toString())
will generate:
class MyName extends StatelessWidget {
const MyName({
Key key,
#required int count,
}) : _count = count, super(key: key);
final int _count;
#override
Widget build(BuildContext context) {
return Text(_count.toString());
}
}
while this widget:
Text(count.toString())
will create:
class MyName extends StatelessWidget {
const MyName({
Key key,
#required this.count,
}) : super(key: key);
final int count;
#override
Widget build(BuildContext context) {
return Text(count.toString());
}
}