这是来自官方网站的示例
void main() => runApp(MaterialApp(home: Home()));
class Home extends StatelessWidget {
var count = 0.obs;
@override
Widget build(context) => Scaffold(
appBar: AppBar(title: Text("counter")),
body: Center(
child: Obx(() => Text("$count")),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => count ++,
));
}
我决定让它变得更加困难。当你点击按钮时,方块的颜色应该会改变,但不会改变。为什么?下面是完整的代码和截图。
主要.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'Name App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Name Page'),
),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
var _color = Colors.amber.obs;
@override
Widget build(BuildContext context) {
return Obx(() =>
Stack(
children: [
Align(
alignment: Alignment(0.0, -0.75),
child: AnimatedContainer(
width: 150.0,
height: 150.0,
color: _color.value,
duration: Duration(milliseconds: 500),
),
),
Align(
alignment: Alignment(-1.0, 0.95),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
width: 15.0,
),
Expanded(
flex: 1,
child: Container(
height: 50.0,
child: FlatButton(
onPressed: () { _color = Colors.red.obs; },
splashColor: Colors.blue.withOpacity(0.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
child: Text(
'OK',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
color: Colors.red,
),
),
),
SizedBox(
width: 15.0,
),
Expanded(
flex: 1,
child: Container(
height: 50.0,
child: FlatButton(
onPressed: () { _color = Colors.green.obs; },
splashColor: Colors.blue.withOpacity(0.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
child: Text(
'OK',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
color: Colors.green,
),
),
),
SizedBox(
width: 15.0,
),
Expanded(
flex: 1,
child: Container(
height: 50.0,
child: FlatButton(
onPressed: () { _color = Colors.blue.obs; },
splashColor: Colors.blue.withOpacity(0.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
child: Text(
'OK',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
color: Colors.blue,
),
),
),
SizedBox(
width: 15.0,
),
],
),
),
],
)
);
}
}
在这种情况下,您需要一个 ObxValue。并尽可能在本地使用它,仅在您需要的地方使用:
问题是您没有为正在收听的 Observable (或 Stream / 随心所欲地调用它)设置新值,而是分配一个新值。将按钮操作更改为:
结果:
完整更正的代码: