I\'ve the below custom widget that make a Switch
and reads its status (true/false)
Then I add this one to my main app widget (parent), how can I make th
In 2020, the function in the highest voted answer is marked deprecated. So here is the modified solution based on that answer:
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
@override
State createState() => new MyStatefulWidgetState();
// --> NOTE this! <--
static MyStatefulWidgetState of(BuildContext context) =>
context.findAncestorStateOfType();
}
class MyStatefulWidgetState extends State {
String _string = "Not set yet";
set string(String value) => setState(() => _string = value);
@override
Widget build(BuildContext context) {
return new Column(
children: [
new Text(_string),
new MyChildClass(callback: (val) => setState(() => _string = val))
],
);
}
}
typedef void StringCallback(String val);
class MyChildClass extends StatelessWidget {
final StringCallback callback;
MyChildClass({this.callback});
@override
Widget build(BuildContext context) {
return new Column(
children: [
new FlatButton(
onPressed: () {
callback("String from method 1");
},
child: new Text("Method 1"),
),
new FlatButton(
onPressed: () {
MyStatefulWidget.of(context).string = "String from method 2";
},
child: new Text("Method 2"),
)
],
);
}
}
void main() => runApp(
new MaterialApp(
builder: (context, child) => new SafeArea(child: new Material(color: Colors.white, child: child)),
home: new MyStatefulWidget(),
),
);