Как вы обновляете состояние виджета-брата во Flutter?
Например, если у меня есть виджет прямоугольника, я могу изменить его цвет из виджета, вызвав setState()
и изменив цветпеременная (как кнопка «Turn Green» делает ниже).Но, скажем, я хотел кнопку вне прямоугольника, которая бы изменила его цвет.Как мне сообщить Rectangle, что пришло время изменить его цвет, и какой цвет изменить?
Вот мой пример кода.Когда пользователь нажимает кнопку «Синяя», я бы хотел, чтобы прямоугольник стал синим, но у меня нет доступа к его состоянию из виджета «Брат».
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Hello Rectangle',
home: Scaffold(
appBar: AppBar(
title: Text('Hello Rectangle'),
),
body: Column(
children: <Widget>[
HelloRectangle(),
FlatButton(
child: Text('Turn Blue!',
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
),
onPressed: () {
// How to update state of the Rectangle from here?
},
),
]
),
),
),
);
}
class HelloRectangle extends StatefulWidget {
@override
HelloRectangleState createState() {
return new HelloRectangleState();
}
}
class HelloRectangleState extends State<HelloRectangle> {
Color _color;
@override
void initState() {
super.initState();
_color = Colors.red;
}
@override
Widget build(BuildContext context) {
return Center(
child: Container(
color: _color,
height: 400.0,
width: 300.0,
child: Center(
child: FlatButton(
child: Text('Turn Green!',
style: TextStyle(fontSize: 40.0),
textAlign: TextAlign.center,
),
onPressed: () {
// I can update the state from here because I'm inside the widget
setState(() {
_color = Colors.green;
});
},
),
),
),
);
}
}