Is it possible to call setState()
of particular widget (embedded in other widgets) from other widgets onPressed()
method so only that widget is redrawn?
I want to click on the button and see the state of "MyTextWidget" to change. The rest of the layout is same, nothing changes there so it should not be rewritten.
This is my code:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Timer',
theme: new ThemeData(
primaryColor: Colors.grey.shade800,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
int _seconds = 1;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("title"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
MyTextWidget(), //just update this widget
Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.add_circle),
onPressed: _addPressed,
iconSize: 150.0,
),
IconButton(
icon: Icon(Icons.remove_circle),
onPressed: ()=> print("to be implemented"),
iconSize: 150.0,
),
],
)
],
),
);
}
void _addPressed() {
//somehow call _updateSeconds()
}
}
And this is statefull MyTextWidget which I want to update.
class MyTextWidget extends StatefulWidget{
@override
_MyTextWidgetState createState() => _MyTextWidgetState();
}
class _MyTextWidgetState extends State<MyTextWidget> {
int secondsToDisplay = 0;
void _updateSeconds(int newSeconds) {
setState(() {
secondsToDisplay = newSeconds;
});
}
@override
Widget build(BuildContext context) {
return Text(
secondsToDisplay.toString(),
textScaleFactor: 5.0,
);
}
}
It seems like something quite simple what I want to achieve but I'm not able to figure it out. Imagine if "MyTextWidget" was buried in huge layout tree and every time I want to update it I would need to redraw whole tree again.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…