Created
April 27, 2019 02:09
-
-
Save mono0926/0b4e151ed3d1d27675ca6003b22de3d5 to your computer and use it in GitHub Desktop.
ValueNotifier/ValueListenableBuilderの最小構成のサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
const title = 'ValueListenableBuilder Demo'; | |
void main() => runApp(App()); | |
class App extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: title, | |
home: HomePage(), | |
); | |
} | |
} | |
class HomePage extends StatefulWidget { | |
HomePage({Key key}) : super(key: key); | |
@override | |
_HomePageState createState() => _HomePageState(); | |
} | |
class _HomePageState extends State<HomePage> { | |
// カウンター | |
final _counter = ValueNotifier<int>(0); | |
@override | |
void initState() { | |
super.initState(); | |
// Listenable なので addListener で監視もできる | |
_counter.addListener(() { | |
print(_counter.value); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: const Text(title)), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
const Text('You have pushed the button this many times:'), | |
// _counterのvalue変更に応じて呼ばれる | |
ValueListenableBuilder<int>( | |
valueListenable: _counter, | |
builder: (_context, count, _child) => Text( | |
'$count', | |
style: Theme.of(context).textTheme.display1, | |
), | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
// 解説動画(https://youtu.be/s-ZG-jS5QHQ)ではnotifyListeners()を | |
// 明示的に呼んでいるが、valueのsetterで自動的に呼ばれているので、誤りなはず。 | |
// 明示的に呼ぶと、valueを1回更新する度に、2回更新イベントが流れてしまう | |
onPressed: () => _counter.value++, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment