How to create method without effecting each others? - flutter

I created a method that named "Button". This method changes container's color and I want to use this method two times but I don't want "Button" method to not effect other methods. I don't know how to do it. Finally i want to create a method and use it several times but i don't want them to effect each others.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
children: [
Button(color1!),
SizedBox(height: 20,),
Button(color1!),
],
),
),
);
}
Color? color1 = Colors.green;
FlatButton Button(Color color) {
return FlatButton(
onPressed: () {
setState(() {
color1 = Colors.blue;
});
},
child: Container(
height: 200,
width: 200,
color: color1,
),
);
}
}

Related

How does the "event" parameter contain data? What should I do if I want to create my "onHover"?

I have a simple flutter application. It's ok, but I'm trying to understand how onHover: (event){...} works, why "event" contains data? How can I make my own widget have function parameters like that?
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
double dx = 0, dy = 0;
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Title',
home: Scaffold(
body: MouseRegion(
onHover: (event) {
setState(() {
dx = event.localPosition.dx;
dy = event.localPosition.dy;
});
},
child: Center(
child: Text('$dx'),
),
),
),
);
}
}
To create your own onChange, or the like we can use ValueChanged.
For example, taking a look at the code for a TextButton() we see:
const TextButton({
Key? key,
required VoidCallback? onPressed,
VoidCallback? onLongPress,
ValueChanged<bool>? onHover,
the onHover uses a ValueChanged.
You can implement your own valueChanged using this example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Buttons(
onHover: (value) {
// Do something
print(value);
},
),
),
),
);
}
}
class Buttons extends StatelessWidget {
final ValueChanged<String> onHover;
Buttons({Key? key, required this.onHover}) : super(key: key);
#override
Widget build(BuildContext context) {
return Column(
children: [
TextButton(
onPressed: () {
onHover('Pressed');
},
child: Text("Click me")),
Text('hi')
],
);
}
}
So this how we pass the data from the widget which is at the bottom of the widget tree.
It's more related to passing the value from bottom to top using callback functions.
Below is the simple example to demonstrate this data sharing.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _parentData = 0;
#override
Widget build(BuildContext context) {
return Column(
children: [
Text(
"Parent State Value: " + _parentData.toString(),
),
ChildWidgetExample(
callbackFn: (data) {
setState(() {
_parentData = data;
});
},
)
],
);
}
}
class ChildWidgetExample extends StatefulWidget {
final Function(int) callbackFn;
const ChildWidgetExample({
Key? key,
required this.callbackFn,
}) : super(key: key);
#override
State<ChildWidgetExample> createState() => _ChildWidgetExampleState();
}
class _ChildWidgetExampleState extends State<ChildWidgetExample> {
int data = 0;
#override
Widget build(BuildContext context) {
return Column(
children: [
Text(
data.toString(),
),
const SizedBox(
height: 30,
),
ElevatedButton(
onPressed: () {
setState(() {
data++;
});
widget.callbackFn(data);
},
child: const Text("Press"),
)
],
);
}
}
In Flutter you can declare Functions with parameters.
void Function(String foo) myFunction;
So you declare in as a variable in your widget component.
MyWidget({required this.myFunction});
Then when you have to call this component you can write :
...
child : MyWidget(myFunction: (String foo) {},),

Flutter - The const widget still rebuild when its parent rebuild

I have a question about when and how a const widget will rebuild.
For example, I have a demo project like this:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool isChecked = false;
#override
Widget build(BuildContext context) {
const child = ChildWidget();
return OrientationBuilder(
builder: (context, orientation) {
debugPrint('$orientation');
final isPortrait = orientation == Orientation.portrait;
return Container(
alignment: Alignment.topCenter,
child: isPortrait
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
SizedBox(height: 200, child: child),
Text('Bellow text'),
])
: child,
);
},
);
}
}
class ChildWidget extends StatefulWidget {
const ChildWidget({Key? key}) : super(key: key);
#override
State<ChildWidget> createState() => _ChildWidgetState();
}
class _ChildWidgetState extends State<ChildWidget> {
int _counter = 0;
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
_counter += 1;
});
},
child: Container(
color: Colors.blue, child: Center(child: Text('$_counter'))),
);
}
}
As you see, I have a const ChildWidget.
const child = ChildWidget();
When I rotate the device, it will trigger the builder function of the OrientationBuilder and return a new Container. But my question is why the child widget is rebuilt again while it is a const.
The reason why I want the child widget is not rebuilt is that I don't want the counter Text to reset to 0 each time I rotate the device.
Please advice.
Thanks a lot.
While the variable and object assigned are constant, the framework will still call the build method on the child widgets. So the actual ChildWidget class is not recreated, but the build will be called.
This is not really a problem. Flutter is really optimized for rebuilding Widgets. If the data has not changed, the actual cost of rebuilding is negligible.

flutter - change a variable from another class

I would like when I press on the RawMaterialButton, the textField () class changes to the container () class and appears on the screen,
with the code I have now when I press nothing happens ...
can anyone fix it? Thank you.
void main() => runApp(mainApp());
class mainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: chat(),
);
}
}
class chat extends StatefulWidget {
const chat({Key? key}) : super(key: key);
#override
_chatState createState() => _chatState();
}
class _chatState extends State<chat> {
bool changeClass = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: changeClass ? container() : textField(changeClass: changeClass),
);
}
}
class textField extends StatefulWidget {
textField({Key? key, required this.changeClass}) : super(key: key);
bool changeClass = false;
#override
_textFieldState createState() => _textFieldState();
}
class _textFieldState extends State<textField> {
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: [
Container(
width: 300.0,
height: 60.0,
color: Colors.red,
),
RawMaterialButton(
onPressed: () {
setState(() {
widget.changeClass = true;
});
},
child: Icon(Icons.send),
)
],
),
);
}
}
class container extends StatefulWidget {
const container({Key? key}) : super(key: key);
#override
_containerState createState() => _containerState();
}
class _containerState extends State<container> {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
width: double.infinity,
height: 60.0,
color: Colors.grey,
),
);
}
}
hope someone can help me.
Thank you :)
I write this piece because otherwise it won't let me upload itI write this piece because otherwise it won't let me upload itI write this piece because otherwise it won't let me upload it
You are technically changing a local variable in the _textFieldState, so to solve the problem you have multiple options, one of them is to pass a function that change the state in the _chatState, this code would do so:
void main() => runApp(mainApp());
class mainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: chat(),
);
}
}
class chat extends StatefulWidget {
const chat({Key? key}) : super(key: key);
#override
_chatState createState() => _chatState();
}
class _chatState extends State<chat> {
bool changeClass = false;
changeClassValue() {
setState(() {
changeClass = !changeClass;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: changeClass
? container()
: textField(changeClassValue: changeClassValue),
);
}
}
class textField extends StatefulWidget {
textField({Key? key, required this.changeClassValue}) : super(key: key);
Function changeClassValue;
#override
_textFieldState createState() => _textFieldState();
}
class _textFieldState extends State<textField> {
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: [
Container(
width: 300.0,
height: 60.0,
color: Colors.red,
),
RawMaterialButton(
onPressed: () {
setState(() {
widget.changeClassValue();
});
},
child: Icon(Icons.send),
)
],
),
);
}
}
class container extends StatefulWidget {
const container({Key? key}) : super(key: key);
#override
_containerState createState() => _containerState();
}
class _containerState extends State<container> {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
width: double.infinity,
height: 60.0,
color: Colors.grey,
),
);
}
}
where the output would look like:

change a variable from another class

i am quite a beginner with flutter. i hope someone can help me solve this problem...
I have this code, how can I make that when i press the RawMaterialButton of the textField() class, the changeClass variable of the chat() class changes from textField() to container() ?
void main() => runApp(mainApp());
class mainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: chat(),
);
}
}
class chat extends StatefulWidget {
const chat({Key? key}) : super(key: key);
#override
_chatState createState() => _chatState();
}
class _chatState extends State<chat> {
var changeClass = textField();
#override
Widget build(BuildContext context) {
return Scaffold(
body: changeClass,
);
}
}
class textField extends StatefulWidget {
const textField({Key? key}) : super(key: key);
#override
_textFieldState createState() => _textFieldState();
}
class _textFieldState extends State<textField> {
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: [
Container(
width: 300.0,
height: 60.0,
color: Colors.red,
),
RawMaterialButton(
onPressed: () {
// on pressed change this row into container
},
child: Icon(Icons.send),
)
],
),
);
}
}
class container extends StatefulWidget {
const container({Key? key}) : super(key: key);
#override
_containerState createState() => _containerState();
}
class _containerState extends State<container> {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
width: double.infinity,
height: 60.0,
color: Colors.grey,
),
);
}
}
hope someone can help me
Thank you :)
Define a state variable changeClass in _chatState
In the build method check if the changeClass is true then return the container Widget otherwise return Row widget.
setState the changeClass = trueinonPressed`
_
import 'package:flutter/material.dart';
void main() => runApp(mainApp());
class mainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: chat(),
);
}
}
class chat extends StatefulWidget {
const chat({Key? key}) : super(key: key);
#override
_chatState createState() => _chatState();
}
class _chatState extends State<chat> {
bool changeClass = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: changeClass
? container()
: textField(
changeClass: changeClass,
callback: () {
setState(() {
changeClass = true;
});
},
),
);
}
}
class textField extends StatefulWidget {
textField({Key? key, required this.changeClass, required this.callback})
: super(key: key);
bool changeClass = false;
VoidCallback callback;
#override
_textFieldState createState() => _textFieldState();
}
class _textFieldState extends State<textField> {
#override
Widget build(BuildContext context) {
return Center(
child: Row(
children: [
Flexible(
child: Container(
width: 300.0,
height: 60.0,
color: Colors.red,
),
),
RawMaterialButton(
onPressed: widget.callback,
child: Icon(Icons.send),
)
],
),
);
}
}
class container extends StatefulWidget {
const container({Key? key}) : super(key: key);
#override
_containerState createState() => _containerState();
}
class _containerState extends State<container> {
#override
Widget build(BuildContext context) {
return Center(
child: Container(
width: double.infinity,
height: 60.0,
color: Colors.grey,
),
);
}
}

How do I call a method from a stateful widget inside of a stateful widget

I am trying to clean up my code and want to place one of my methods from a stateful widget inside of a different class that is also a stateful widget but whenever I try to call the method it does not recognize it unless the class that I am calling it from it a stateless widget. I was wondering what the best way to get around this would be without changing the class?
Here is a simple example of my problem, I am trying to call
exampleStatefulWidget.testWidget() inside of MyHomePage which is a stateful widget.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
ExampleStatefulWidget exampleStatefulWidget = ExampleStatefulWidget();
ExampleStatelessWidget exampleStatelessWidget = ExampleStatelessWidget();
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
exampleStatefulWidget.testWidget(), // Can not call method that is inside of a stateful widget
exampleStatelessWidget.testWidget(); // Will call method but only if inside of a stateless widget
},
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class ExampleStatefulWidget extends StatefulWidget {
const ExampleStatefulWidget({Key? key}) : super(key: key);
#override
_ExampleStatefulWidgetState createState() => _ExampleStatefulWidgetState();
}
class _ExampleStatefulWidgetState extends State<ExampleStatefulWidget> {
MyHomePage myHomePage = MyHomePage();
Widget testWidget() {
return Container(); // Do Something
}
#override
Widget build(BuildContext context) {
return Container();
}
}
class ExampleStatelessWidget extends StatelessWidget {
const ExampleStatelessWidget({ Key? key }) : super(key: key);
Widget testWidget() {
return Container(); // Do Something
}
#override
Widget build(BuildContext context) {
return Container(
);
}
}
ExampleStatefulWidget and _ExampleStatefulWidgetState are different class, you can create instance of _ExampleStatefulWidgetState instead. And use the method.
_ExampleStatefulWidgetState exampleStatefulWidget =
_ExampleStatefulWidgetState();
In this case, uses will be like
_MyHomePageState
class _MyHomePageState extends State<MyHomePage> {
Widget? widgetFromMethod;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (widgetFromMethod != null) widgetFromMethod!,
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
exampleStatelessWidget
.testWidget(); // Will call method but only if inside of a stateless widget
final gotWidget = exampleStatefulWidget.testWidget();
setState(() {
widgetFromMethod = gotWidget;
});
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
_ExampleStatefulWidgetState
class _ExampleStatefulWidgetState extends State<ExampleStatefulWidget> {
MyHomePage myHomePage = MyHomePage();
Widget testWidget() {
return Container(
color: Colors.purple,
width: 100,
height: 100,
child: Text("generated method from statefull"),
); // Do Something
}
#override
Widget build(BuildContext context) {
return Container();
}
}
if _ExampleStatefulWidgetState are on separate file, make it public removing _.
it will be ExampleStatefulWidgetState
Calling a printLog method of SecondWidget (Child) from FirstWidget(Parent)
Note: This is not recommended. Use any state management lib to achive this (flutter_bloc, provider etc)
import 'package:flutter/material.dart';
class FirstWidget extends StatefulWidget {
#override
_FirstWidgetState createState() => _FirstWidgetState();
}
class _FirstWidgetState extends State<FirstWidget> {
final key = GlobalKey<_SecondWidgetState>();
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
alignment: Alignment.center,
child: Column(
children: [
ElevatedButton(
onPressed: () {
key.currentState?.printLog();
},
child: Text("Click"),
),
SecondWidget(key)
],
),
),
),
);
}
}
class SecondWidget extends StatefulWidget {
SecondWidget(Key key) : super(key: key);
#override
_SecondWidgetState createState() => _SecondWidgetState();
}
class _SecondWidgetState extends State<SecondWidget> {
#override
Widget build(BuildContext context) {
return Container(padding: EdgeInsets.all(20), child: Container());
}
void printLog() {
print("I am called");
}
}