Minimal reproducible code:
class MainScreen extends StatefulWidget {
#override
State<MainScreen> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(onPressed: () => setState(() {})),
body: FooPage(key: ValueKey(0)),
);
}
}
class FooPage extends StatelessWidget {
FooPage({super.key});
final int _number = math.Random().nextInt(100);
#override
Widget build(BuildContext context) {
print('number = $_number');
return Container();
}
}
Each time you click the FAB, the number prints a new value. But as I'm already passing same key to the FooPage, why is it the MainScreen creates a new FooPage instance from scratch instead of using the existing one (with key 0)?
NOTE:
Please don't post answers to use const FooPage() after declaring a const constructor in the FooPage or assign FooPage to a final instance field in the MainScreen etc.
Adding a key to a StatelessWidget doesn't make it stateful (remebering the random int).
I.e. the framework will still dispose and rebuild it as a new instance when deemed necessary.
Related
The class below consists of an AppBar but I want to use Text field in place of it, I don't know how to create a class constructor with Text Field and use it. I am just following the example of Appbar but it is limited to one input and I want multiple Text fields in my app.
class CustomLocation extends StatefulWidget {
//final TextField textField;
final AppBar? appBarPicker;
final Widget? topWidgetPicker;
final Widget? bottomWidgetPicker;
CustomLocation({
//this.textField,
required this.controller,
this.appBarPicker,
this.bottomWidgetPicker,
this.topWidgetPicker,
Key? key,
}) : super(key: key);
}
#override
_CustomLocationState createState() => _CustomLocationState();
}
#override
Widget build(BuildContext context) {
return Builder(
builder: (ctx) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: widget.appBarPicker,
//use TextField widget here to call it in another class
//TextField : widget.textField ?
body: Stack(
children: [
),
],
),
);
},
);
}
}
Just Create another dart file named MyTextField.dart, declare your class in it, like MyTextField which extends StatefulWidget and returns TextField like this
class MyTextField extends StatefulWidget {
#override
_MyTextFieldState createState() => _MyTextFieldState();
}
class _MyTextFieldState extends State<MyTextField> {
#override
Widget build(BuildContext context) {
return TextField(
// TextField Properties you want
);
}
}
now Mention it anywhere you want to create this TextField like
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
#override
Widget build(BuildContext context) {
return Container(
child: MyTextField(), //your custom TextField
);
}
}
You have to import that MyTextField.dart file wherever you want to use your custom textfield. you can pass value like length of characters allowed, border, error, hint, counter text and more properties using MyTextField class constructor.
It will be easy to make changes by modifying only one file.
I am trying to refresh the parent widget from sub children widget. Actually, there are a number of widgets in between like A uses B and B uses C. I would like to refresh A widget on an event in C widget.I researched a lot but couldn't find an exact answer. A code snipped will be really helpful. Thanks in advance
There are a few solutions:
A pass a callback that does a setState to B, which then pass it to C:
class A extends StatefulWidget {
#override
_AState createState() => _AState();
}
class _AState extends State<A> {
#override
Widget build(BuildContext context) {
return B(
onSomething: () => setState(() {}),
);
}
}
class B extends StatelessWidget {
final VoidCallback onSomething;
const B({Key key, this.onSomething}) : super(key: key);
#override
Widget build(BuildContext context) {
return C(onSomething: onSomething);
}
}
class C extends StatelessWidget {
final VoidCallback onSomething;
const C({Key key, this.onSomething}) : super(key: key);
#override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: onSomething,
);
}
}
use NotificationListener in A, and dispatch a Notification from C:
class MyNotification extends Notification {}
class A extends StatefulWidget {
#override
_AState createState() => _AState();
}
class _AState extends State<A> {
#override
Widget build(BuildContext context) {
return NotificationListener<MyNotification>(
onNotification: (_) {
setState(() {});
},
child: B(),
);
}
}
class C extends StatelessWidget {
#override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
MyNotification().dispatch(context);
},
);
}
}
Why do you want to refresh? You updated any data and wanted the new ones to be displayed?
You could try to use Provider widget. With it you can modify any data and notify everyone interested in that data that it changed.
In your setup you could put the provider on the A widget, on the C widget you could get the value, updated and notify everyone. When doing that, A widget will automatically rebuild with the updated information.
The code would be something like this:
class AppState with ChangeNotifier {
AppState();
YourData _data;
void setData(YourData data) {
_data = data;
notifyListeners();
}
}
ChangeNotifierProvider.value(
value: AppState(),
child: WidgetA()
)
WidgetC() {
Provider.of<AppState>(context).setData(yourChangedDataHere);
}
I was wondering what would be the best way to access/pass variables between widgets. For example,
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
int number = 0;
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Jungle Book',
home: new Scaffold(
appBar: new AppBar(title: new Text('Jungle Book')),
drawer: new AppMenu(),
body: new MainPageManager(),
floatingActionButton: new FloatingActionButton(onPressed: null,child: new Icon(Icons.shuffle),),
),
);
}
}
class MainPageManager extends StatefulWidget {
#override
_MainPageManagerState createState() => _MainPageManagerState();
}
class _MainPageManagerState extends State<MainPageManager> {
List<String> keys = ["flamingo"]; // more to add later
final _random = new Random();
#override
Widget build(BuildContext context) {
return Center(
child: new Image.asset('images/'+keys[_random.nextInt(keys.length)]+'.jpg',
fit: BoxFit.fill,)
);
}
}
If I need to pass a value during the floatingActionButton.OnPressed to the MainPageManager, what would be best way to do it.
What am attempting to do is, when the FloatingActionButton is pressed, i need to update the MainPageManager with a new image.
I read somewhere that using Global keys is not a good idea. What could be alternative ?
PS: am more of a beginner with flutter.
Flutter is not opinionated about how you approach state management.
Since MainPageManager is a direct child of MyApp you could turn MyApp into a stateful widget and MainPageManager into a stateless widget instead, as you are not using the setState method at all in your MainPageManager. Then, in your onPressed callback you'd use the setState method to set the state of your MyApp component, which will cause flutter to rebuild MyApp and all child widgets (so MainPageManager will be rebuild as well).
The last thing to do would be to add a property to your now stateless MainPageManager, that you'd pass down to that component.
Example:
class MainPageManager extends StatelessWidget {
final String value;
MainPageManager({this.value});
#override
Widget build(BuildContext context) {
return Container(
child: Text("$value"),
);
}
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _valueBinding;
#override
void initState() {
_valueBinding = "Test";
super.initState();
}
#override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
MainPageManager(
value: _valueBinding,
),
MaterialButton(onPressed: () {
setState(() {
_valueBinding = "This will be shown in MainPageManager";
});
}, child: Text("Update Value"),)
],
);
}
}
For more complex use-cases:
Flutter comes with a state-management solution called InheritedWidget. However, the API is not that convenient and the flutter team actually promotes using a package called Provider instead, which builds on InheritedWidget.
If your app grows really big I actually recommend using the BloC pattern instead.
I'm wondering what the recommended way of passing data to a stateful widget, while creating it, is.
The two styles I've seen are:
class ServerInfo extends StatefulWidget {
Server _server;
ServerInfo(Server server) {
this._server = server;
}
#override
State<StatefulWidget> createState() => new _ServerInfoState(_server);
}
class _ServerInfoState extends State<ServerInfo> {
Server _server;
_ServerInfoState(Server server) {
this._server = server;
}
}
This method keeps a value both in ServerInfo and _ServerInfoState, which seems a bit wasteful.
The other method is to use widget._server:
class ServerInfo extends StatefulWidget {
Server _server;
ServerInfo(Server server) {
this._server = server;
}
#override
State<StatefulWidget> createState() => new _ServerInfoState();
}
class _ServerInfoState extends State<ServerInfo> {
#override
Widget build(BuildContext context) {
widget._server = "10"; // Do something we the server value
return null;
}
}
This seems a bit backwards as the state is no longer stored in _ServerInfoSate but instead in the widget.
Is there a best practice for this?
Don't pass parameters to State using it's constructor.
You should only access the parameters using this.widget.myField.
Not only editing the constructor requires a lot of manual work ; it doesn't bring anything. There's no reason to duplicate all the fields of Widget.
EDIT :
Here's an example:
class ServerIpText extends StatefulWidget {
final String serverIP;
const ServerIpText ({ Key? key, this.serverIP }): super(key: key);
#override
_ServerIpTextState createState() => _ServerIpTextState();
}
class _ServerIpTextState extends State<ServerIpText> {
#override
Widget build(BuildContext context) {
return Text(widget.serverIP);
}
}
class AnotherClass extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: ServerIpText(serverIP: "127.0.0.1")
);
}
}
Best way is don't pass parameters to State class using it's constructor. You can easily access in State class using widget.myField.
For Example
class UserData extends StatefulWidget {
final String clientName;
final int clientID;
const UserData(this.clientName,this.clientID);
#override
UserDataState createState() => UserDataState();
}
class UserDataState extends State<UserData> {
#override
Widget build(BuildContext context) {
// Here you direct access using widget
return Text(widget.clientName);
}
}
Pass your data when you Navigate screen :
Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserData("WonderClientName",132)));
Another answer, building on #RĂ©miRousselet's anwser and for #user6638204's question, if you want to pass initial values and still be able to update them in the state later:
class MyStateful extends StatefulWidget {
final String foo;
const MyStateful({Key key, this.foo}): super(key: key);
#override
_MyStatefulState createState() => _MyStatefulState(foo: this.foo);
}
class _MyStatefulState extends State<MyStateful> {
String foo;
_MyStatefulState({this.foo});
#override
Widget build(BuildContext context) {
return Text(foo);
}
}
For passing initial values (without passing anything to the constructor)
class MyStateful extends StatefulWidget {
final String foo;
const MyStateful({Key key, this.foo}): super(key: key);
#override
_MyStatefulState createState() => _MyStatefulState();
}
class _MyStatefulState extends State<MyStateful> {
#override
void initState(){
super.initState();
// you can use this.widget.foo here
}
#override
Widget build(BuildContext context) {
return Text(foo);
}
}
Flutter's stateful widgets API is kinda awkward: storing data in Widget in order to access it in build() method which resides in State object đŸ¤¦ If you don't want to use some of bigger state management options (Provider, BLoC), use flutter_hooks (https://pub.dev/packages/flutter_hooks) - it is a nicer and cleaner substitute for SatefullWidgets:
class Counter extends HookWidget {
final int _initialCount;
Counter(this._initialCount = 0);
#override
Widget build(BuildContext context) {
final counter = useState(_initialCount);
return GestureDetector(
// automatically triggers a rebuild of Counter widget
onTap: () => counter.value++,
child: Text(counter.value.toString()),
);
}
}
#RĂ©mi Rousselet, #Sanjayrajsinh, #Daksh Shah is also better. but I am also defined this is in from starting point.that which parameter is which value
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
String name = "Flutter Demo";
String description = "This is Demo Application";
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MainActivity(
appName: name,
appDescription: description,
),
);
}
}
class MainActivity extends StatefulWidget {
MainActivity({Key key, this.appName, this.appDescription}) : super(key: key);
var appName;
var appDescription;
#override
_MainActivityState createState() => _MainActivityState();
}
class _MainActivityState extends State<MainActivity> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.appName),
),
body: Scaffold(
body: Center(
child: Text(widget.appDescription),
),
),
);
}
}
The best practice is to define the stateful widget class as immutable which means defining all dependencies (arrival parameter) as final parameters. and getting access to them by widget.<fieldName> in the state class. In case you want to change their values like reassigning you should define the same typed properties in your state class and re-assign them in the initState function. it is highly recommended not to define any not-final property in your stateful widget class and make it a mutable class. something like this pattern:
class SomePage extends StatefulWidget{
final String? value;
SomePage({this.value});
#override
State<SomePage> createState() => _SomePageState();
}
class _SomePageState extends State<SomePage> {
String? _value;
#override
void initState(){
super.initState();
setState(() {
_value = widget.value;
});
}
#override
Widget build(BuildContext context) {
return Text(_value);
}
}
To pass data to stateful widget, first of all, create two pages. Now from the first page open the second page and pass the data.
class PageTwo extends StatefulWidget {
final String title;
final String name;
PageTwo ({ this.title, this.name });
#override
PageTwoState createState() => PageTwoState();
}
class PageTwoStateState extends State<PageTwo> {
#override
Widget build(BuildContext context) {
return Text(
widget.title,
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.w700),
),
}
}
class PageOne extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialButton(
text: "Open PageTwo",
onPressed: () {
var destination = ServicePage(
title: '<Page Title>',
provider: '<Page Name>',
);
Navigator.push(context,
MaterialPageRoute(builder: (context) => destination));
},);
}
}
I'm wondering what the recommended way of passing data to a stateful widget, while creating it, is.
The two styles I've seen are:
class ServerInfo extends StatefulWidget {
Server _server;
ServerInfo(Server server) {
this._server = server;
}
#override
State<StatefulWidget> createState() => new _ServerInfoState(_server);
}
class _ServerInfoState extends State<ServerInfo> {
Server _server;
_ServerInfoState(Server server) {
this._server = server;
}
}
This method keeps a value both in ServerInfo and _ServerInfoState, which seems a bit wasteful.
The other method is to use widget._server:
class ServerInfo extends StatefulWidget {
Server _server;
ServerInfo(Server server) {
this._server = server;
}
#override
State<StatefulWidget> createState() => new _ServerInfoState();
}
class _ServerInfoState extends State<ServerInfo> {
#override
Widget build(BuildContext context) {
widget._server = "10"; // Do something we the server value
return null;
}
}
This seems a bit backwards as the state is no longer stored in _ServerInfoSate but instead in the widget.
Is there a best practice for this?
Don't pass parameters to State using it's constructor.
You should only access the parameters using this.widget.myField.
Not only editing the constructor requires a lot of manual work ; it doesn't bring anything. There's no reason to duplicate all the fields of Widget.
EDIT :
Here's an example:
class ServerIpText extends StatefulWidget {
final String serverIP;
const ServerIpText ({ Key? key, this.serverIP }): super(key: key);
#override
_ServerIpTextState createState() => _ServerIpTextState();
}
class _ServerIpTextState extends State<ServerIpText> {
#override
Widget build(BuildContext context) {
return Text(widget.serverIP);
}
}
class AnotherClass extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Center(
child: ServerIpText(serverIP: "127.0.0.1")
);
}
}
Best way is don't pass parameters to State class using it's constructor. You can easily access in State class using widget.myField.
For Example
class UserData extends StatefulWidget {
final String clientName;
final int clientID;
const UserData(this.clientName,this.clientID);
#override
UserDataState createState() => UserDataState();
}
class UserDataState extends State<UserData> {
#override
Widget build(BuildContext context) {
// Here you direct access using widget
return Text(widget.clientName);
}
}
Pass your data when you Navigate screen :
Navigator.of(context).push(MaterialPageRoute(builder: (context) => UserData("WonderClientName",132)));
Another answer, building on #RĂ©miRousselet's anwser and for #user6638204's question, if you want to pass initial values and still be able to update them in the state later:
class MyStateful extends StatefulWidget {
final String foo;
const MyStateful({Key key, this.foo}): super(key: key);
#override
_MyStatefulState createState() => _MyStatefulState(foo: this.foo);
}
class _MyStatefulState extends State<MyStateful> {
String foo;
_MyStatefulState({this.foo});
#override
Widget build(BuildContext context) {
return Text(foo);
}
}
For passing initial values (without passing anything to the constructor)
class MyStateful extends StatefulWidget {
final String foo;
const MyStateful({Key key, this.foo}): super(key: key);
#override
_MyStatefulState createState() => _MyStatefulState();
}
class _MyStatefulState extends State<MyStateful> {
#override
void initState(){
super.initState();
// you can use this.widget.foo here
}
#override
Widget build(BuildContext context) {
return Text(foo);
}
}
Flutter's stateful widgets API is kinda awkward: storing data in Widget in order to access it in build() method which resides in State object đŸ¤¦ If you don't want to use some of bigger state management options (Provider, BLoC), use flutter_hooks (https://pub.dev/packages/flutter_hooks) - it is a nicer and cleaner substitute for SatefullWidgets:
class Counter extends HookWidget {
final int _initialCount;
Counter(this._initialCount = 0);
#override
Widget build(BuildContext context) {
final counter = useState(_initialCount);
return GestureDetector(
// automatically triggers a rebuild of Counter widget
onTap: () => counter.value++,
child: Text(counter.value.toString()),
);
}
}
#RĂ©mi Rousselet, #Sanjayrajsinh, #Daksh Shah is also better. but I am also defined this is in from starting point.that which parameter is which value
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
String name = "Flutter Demo";
String description = "This is Demo Application";
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MainActivity(
appName: name,
appDescription: description,
),
);
}
}
class MainActivity extends StatefulWidget {
MainActivity({Key key, this.appName, this.appDescription}) : super(key: key);
var appName;
var appDescription;
#override
_MainActivityState createState() => _MainActivityState();
}
class _MainActivityState extends State<MainActivity> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.appName),
),
body: Scaffold(
body: Center(
child: Text(widget.appDescription),
),
),
);
}
}
The best practice is to define the stateful widget class as immutable which means defining all dependencies (arrival parameter) as final parameters. and getting access to them by widget.<fieldName> in the state class. In case you want to change their values like reassigning you should define the same typed properties in your state class and re-assign them in the initState function. it is highly recommended not to define any not-final property in your stateful widget class and make it a mutable class. something like this pattern:
class SomePage extends StatefulWidget{
final String? value;
SomePage({this.value});
#override
State<SomePage> createState() => _SomePageState();
}
class _SomePageState extends State<SomePage> {
String? _value;
#override
void initState(){
super.initState();
setState(() {
_value = widget.value;
});
}
#override
Widget build(BuildContext context) {
return Text(_value);
}
}
To pass data to stateful widget, first of all, create two pages. Now from the first page open the second page and pass the data.
class PageTwo extends StatefulWidget {
final String title;
final String name;
PageTwo ({ this.title, this.name });
#override
PageTwoState createState() => PageTwoState();
}
class PageTwoStateState extends State<PageTwo> {
#override
Widget build(BuildContext context) {
return Text(
widget.title,
style: TextStyle(
fontSize: 18, fontWeight: FontWeight.w700),
),
}
}
class PageOne extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialButton(
text: "Open PageTwo",
onPressed: () {
var destination = ServicePage(
title: '<Page Title>',
provider: '<Page Name>',
);
Navigator.push(context,
MaterialPageRoute(builder: (context) => destination));
},);
}
}