The flutter docs on restorablePush says that "Any object that is serializable via the StandardMessageCodec can be passed as arguments. Often, a Map is used to pass key-value pairs." But I am struggling to do this, as the route builder needs to be static.
I've made a small example below that illustrates the problem - basically, I want to be able to pass title as an argument from Screen1 to Screen2 and display it in the AppBar. Not sure where and how to put the argument in.
class Screen1 extends StatefulWidget {
const Screen1({Key? key}) : super(key: key);
#override
State<Screen1> createState() => _Screen1State();
}
class _Screen1State extends State<Screen1> {
String title = 'blah';
static Route<void> _myRouteBuilder(BuildContext context, Object? arguments) {
return MaterialPageRoute<void>(
builder: (BuildContext context) => const Screen2(),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
onPressed: () {
Navigator.restorablePush(context, _myRouteBuilder);
// Put somewhere... arguments: {'appBarTitle': title}
},
child: const Text('Go to Screen 2')),
),
);
}
}
class Screen2 extends StatefulWidget {
const Screen2({Key? key}) : super(key: key);
#override
State<Screen2> createState() => _Screen2State();
}
class _Screen2State extends State<Screen2> {
String _string = '';
#override
Widget build(BuildContext context) {
final args =
ModalRoute.of(context)!.settings.arguments as Map<String, String>;
_string = args['appBarTitle'] ?? 'error';
return Scaffold(
appBar: AppBar(title: Text(_string)),
);
}
}
You need to add the settings parameter to MaterialPageRoute so that ModalRoute receives the argument on screen 2.
class Screen1 extends StatefulWidget {
const Screen1({Key? key}) : super(key: key);
#override
State<Screen1> createState() => _Screen1State();
}
class _Screen1State extends State<Screen1> {
String title = 'blah';
static Route<void> _myRouteBuilder(BuildContext context, Object? arguments) {
return MaterialPageRoute<void>(
settings: RouteSettings(name: '/screen2', arguments: arguments),
builder: (BuildContext context) => const Screen2(),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
onPressed: () {
Navigator.restorablePush(context, _myRouteBuilder, arguments: {'appBarTitle': title});
// Put somewhere... arguments: {'appBarTitle': title}
},
child: const Text('Go to Screen 2')),
),
);
}
}
class Screen2 extends StatefulWidget {
const Screen2({Key? key}) : super(key: key);
#override
State<Screen2> createState() => _Screen2State();
}
class _Screen2State extends State<Screen2> {
String _string = 'Test';
#override
Widget build(BuildContext context) {
final args =
ModalRoute.of(context)?.settings.arguments;
if(args is Map){
_string = args['appBarTitle'] ?? 'error';
}
return Scaffold(
appBar: AppBar(title: Text(_string)),
);
}
}
Related
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) {},),
i tried to change the state of Page2 builded from HomePage with Navigator and MaterialPageRoute but the state didn't change. it seems that i can't change the state of another page, is there any solution to change the state of th Page2 from HomePage?
NB: i changed the page before the delay done.
HomePage :
class MyHomePage extends StatefulWidget {
const MyHomePage({
Key? key,
}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var text = 'pp';
#override
void initState () {
super.initState();
_changeStateAfterDelay();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text("ggg"),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _showPages,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
void _showPages() {
Navigator.of(context).push(MaterialPageRoute(
maintainState: false,
builder: (context) => Page2(title: text)
));
}
void _changeStateAfterDelay() {
Future.delayed(const Duration(milliseconds: 10000), () {
setState(() {
text += "tt";
});
});
}
}
Page2:
class Page2 extends StatefulWidget {
final String title;
const Page2({
Key? key,
required this.title,
}) : super(key: key);
#override
_Page2State createState() => _Page2State();
}
class _Page2State extends State<Page2> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text(widget.title)
),
);
}
}
One possible way to change the state of Page2 from Page1 (in your case HomePage), it is to use a state manager like Provider.
If you want to change the state of Page1 from Page2, you can use a Callback set to Page2 as a parameter.
right widget has gesterdetector that adds a String ("ZzZ") to List;
left widget shows all String there in String list by List view Buildder,
right widget adds "ZzZ" to list after pressing the button successfully but it dosent sets ui state...
in android studio after hot reload it shows all added "ZzZ"
import 'package:flutter/material.dart';
List<String> ListOfZzZ=[];
class homescreen extends StatefulWidget {
#override
_homescreenState createState() => _homescreenState();
}
class _homescreenState extends State<homescreen> {
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
body: Row(children: [
Expanded(child:RightSidewidget()),
Expanded(child:LeftSidewidget())
],
)),
);
}
}
class RightSidewidget extends StatefulWidget {
#override
_RightSidewidgetState createState() => _RightSidewidgetState();
}
class _RightSidewidgetState extends State<RightSidewidget> {
#override
Widget build(BuildContext context) {
return GestureDetector(
child: Container(child:Text("add new ZzZ"),),
**onTap: (){
setState(() {
ListOfZzZ.add("ZzZ");
});},);**
}
}
class LeftSidewidget extends StatefulWidget {
#override
_LeftSidewidgetState createState() => _LeftSidewidgetState();
}
class _LeftSidewidgetState extends State<LeftSidewidget> {
#override
Widget build(BuildContext context) {
return Container(child:
ListView.builder(
itemCount: ListOfZzZ.length,
itemBuilder: (context,index)=>Text(ListOfZzZ[index])),);
}
}
check the Provider package it can help you achieve what you want, ere is a really good tutorial by the flutter devs showing how to use manage the state of your app and notify widgets of the changes other widgets have.
setState rebuild in very specyfic way. you can read about this in here:
https://api.flutter.dev/flutter/widgets/State/setState.html
in simple world setState call the nearest build (I think this is not full true, but this intuitions works for me)
In your code when you tap right widget and call setState only rightwidget will be rebuild.
So this is the easy solutions:
Make left and right widget statless.
In homescreen in row add gestureDetector(or textButton like in my example) and here call setState. When you do that, all homeSreen will be rebuild so left and right widget too. and your list will be actual. Here is example:
List<String> ListOfZzZ = [];
class homescreen extends StatefulWidget {
#override
_homescreenState createState() => _homescreenState();
}
class _homescreenState extends State<homescreen> {
#override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
body: Row(
children: [
Expanded(
child: TextButton(
onPressed: () => setState(() {
ListOfZzZ.add("ZzZ");
}),
child: RightSidewidget())),
Expanded(child: LeftSideWidget())
],
)),
);
}
}
class RightSidewidget extends StatelessWidget {
const RightSidewidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
color: Colors.amber[50],
child: Text("add new ZzZ"),
);
}
}
class LeftSideWidget extends StatelessWidget {
const LeftSideWidget({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
child: ListView.builder(
itemCount: ListOfZzZ.length,
itemBuilder: (context, index) => Text(ListOfZzZ[index])),
);
}
}
The hard way, but more elegant and better is to use some state manager like bloc. Here is official site: https://bloclibrary.dev/#/gettingstarted
there is a lot of tutorials and explanations. But this is not solutions for 5 minutes.
Edit: I make some solution with BLoC. I hope this help. I use flutter_bloc and equatable packages in version 7.0.1
void main() {
EquatableConfig.stringify = kDebugMode;
Bloc.observer = SimpleBlocObserver();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('myList'),
),
body: BlocProvider(
create: (context) => MylistBloc()..add(AddToList('Start')),
child: Row(
children: [
Expanded(flex: 1, child: buttonsPanel()),
Expanded(flex: 1, child: ListOfZzZ()),
],
),
),
),
);
}
}
class ListOfZzZ extends StatefulWidget {
const ListOfZzZ({Key? key}) : super(key: key);
#override
_ListOfZzZState createState() => _ListOfZzZState();
}
class _ListOfZzZState extends State<ListOfZzZ> {
late MylistBloc _mylistBloc;
#override
Widget build(BuildContext context) {
return BlocBuilder<MylistBloc, MylistState>(
//builder: (context, state) {return ListView.builder(itemBuilder: (BuildContext context,int index){return ListTile(title: state.positions[index];)},);},
builder: (context, state) {
if (state.positions.isEmpty) {
return const Center(child: Text('no posts'));
} else {
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return ListTile(title: Text(state.positions[index]));
},
itemCount: state.positions.length,
);
}
},
);
}
}
class buttonsPanel extends StatefulWidget {
const buttonsPanel({Key? key}) : super(key: key);
#override
_buttonsPanelState createState() => _buttonsPanelState();
}
class _buttonsPanelState extends State<buttonsPanel> {
late MylistBloc _mylistBloc;
#override
void initState() {
super.initState();
_mylistBloc = context.read<MylistBloc>();
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextButton(
onPressed: () => {_mylistBloc.add(AddToList('Spam'))},
child: Text('Spam')),
TextButton(
onPressed: () => {_mylistBloc.add(AddToList('Ham'))},
child: Text('Ham')),
],
);
}
class SimpleBlocObserver extends BlocObserver {
#override
void onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
print(transition);
}
#override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
print(error);
super.onError(bloc, error, stackTrace);
}
}
class MylistState extends Equatable {
final List<String> positions;
final int lenght;
const MylistState({this.positions = const <String>[], this.lenght = 0});
#override
List<Object> get props => [positions];
#override
String toString() => 'Lenght: {$lenght} Positions: {$positions}';
#override
MylistState copyWith(List<String>? positions) {
return MylistState(positions: positions ?? this.positions);
}
}
abstract class MylistEvent extends Equatable {
const MylistEvent();
#override
List<Object> get props => [];
}
class AddToList extends MylistEvent {
final String posToAdd;
#override
AddToList(this.posToAdd);
}
class MylistBloc extends Bloc<MylistEvent, MylistState> {
MylistBloc() : super(MylistState(positions: const <String>[]));
#override
Stream<MylistState> mapEventToState(
MylistEvent event,
) async* {
if (event is AddToList) {
yield await _mapListToState(state, event.posToAdd);
}
}
Future<MylistState> _mapListToState(
MylistState state, String posToAdd) async {
List<String> positions = [];
positions.addAll(state.positions);
positions.add(posToAdd);
return MylistState(positions: positions, lenght: positions.length);
}
}
}
I declare a class variable for a StatefulWidget - in the code below it's someString.
Is it possible to use this variable in the build(…)-method without declaring it as static?
class MyClass extends StatefulWidget {
String someString;
MyClass() {
this.someString = "foo";
}
#override
_MyClassState createState() => _MyClassState();
}
class _MyClassState extends State<MyClass> {
_MyClassState();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("someString - how to access it here?!"),
// title: Text(someString), is not possible, obviously
),
);
}
}
Thanks in advance for help!
Attention: MyClass should be immutable.
1. If someString will never change
Keep it inside MyClass but define it as final.
class MyClass extends StatefulWidget {
final String someString;
const MyClass({Key key, this.someString = 'foo'}) : super(key: key);
#override
_MyClassState createState() => _MyClassState();
}
Then, inside the State, you can use it as widget.someString:
class _MyClassState extends State<MyClass> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('${widget.someString} is accessed here?!')),
);
}
}
2. If someString will change
It should be defined in the state.
class MyClass extends StatefulWidget {
final String initialValue;
const MyClass({Key key, this.initialValue = 'foo'}) : super(key: key);
#override
_MyClassState createState() => _MyClassState();
}
class _MyClassState extends State<MyClass> {
String someString;
#override
void initState() {
someString = widget.initialValue;
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('$someString is accessed here?!')),
body: Center(
child: OutlinedButton(
onPressed: () => setState(() => someString = 'NEW Value'),
child: Text('Update value'),
),
),
);
}
}
I would like to get some help.
I don't understand why something is not rebuilding properly.
I have an app.dart which provides all stores and the body of the Scafold is a home page,
class HomePage extends StatelessWidget {
const HomePage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Consumer<AuthStore>(
builder: (__, AuthStore authStore, _) {
debugPrint('--- $authStore');
return SafeArea(
child: authStore.authenticated
? const AuthenticatedScreen()
: const LoginScreen(),
);
},
);
}
}
the login screen does its job, and updates the store correctly, I don't understand why the home screen is not updated when authenticated changes to true
I tried adding an observer with the same result e.g. no rebuild
class HomePageStateless extends StatelessWidget {
const HomePageStateless({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Consumer<AuthStore>(builder: (__, AuthStore authStore, _) {
debugPrint('--- $authStore');
return Observer(
builder: (_) => SafeArea(
child: authStore.authenticated
? const AuthenticatedScreen()
: const LoginScreen(),
),
);
});
}
}
what I'm missing here
while this widget works as expected
class HomePage extends StatefulWidget {
const HomePage({
Key key,
}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
AuthStore _authStore;
final List<ReactionDisposer> _disposers = <ReactionDisposer>[];
bool _authenticated = false;
#override
void didChangeDependencies() {
super.didChangeDependencies();
for (ReactionDisposer disposer in _disposers) {
disposer();
}
_disposers.clear();
_authStore ??= Provider.of<AuthStore>(context);
_disposers.add(
autorun(
(_) {
print('home store $_authStore');
if (_authenticated != _authStore.authenticated) {
setState(() {
_authenticated = _authStore.authenticated;
});
}
},
),
);
}
#override
void dispose() {
for (ReactionDisposer disposer in _disposers) {
disposer();
}
super.dispose();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: _authenticated ? const AuthenticatedScreen() : const LoginScreen(),
);
}
}
And I know this shouldn't be the correct way, but the autorun fire consistently when the store changes
Use what you u want to rebuild in a void method below the state and statefull widget instead of stateless one.