Skip to content

Instantly share code, notes, and snippets.

@yenru
Created April 8, 2019 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yenru/7e55bd3d3ee900dde0b443c3e3f31a8f to your computer and use it in GitHub Desktop.
Save yenru/7e55bd3d3ee900dde0b443c3e3f31a8f to your computer and use it in GitHub Desktop.
將計數器Sample的StatefulWidget修改成只有數字的部份。方法二:使用ValueNotifier物件通知更新。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
//建立ValueNotifier物件
final ValueNotifier<int> counter = ValueNotifier<int>(0);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
//將ValueNotifier傳遞給StatefulWidget物件
CounterField(counter: counter),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
counter.value++; //事件觸發時,直接更新ValueNotifier裡的值
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class CounterField extends StatefulWidget {
//取得傳入的ValueNotifier物件
final ValueNotifier<int> counter;
CounterField({Key key, this.counter}) : super(key: key);
@override
_CounterFieldState createState() => _CounterFieldState();
}
class _CounterFieldState extends State<CounterField> {
@override
void initState() {
super.initState();
//初始化時,訂閱ValueNotifier的更新狀態
//當ValueNotifier的值異動時,直接刷新物件
widget.counter?.addListener(() => setState(() {}));
}
@override
Widget build(BuildContext context) {
return Text(
'${widget.counter.value}', //顯示ValueNotifier的值
style: Theme.of(context).textTheme.display1,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment