今天要實作一個透過ValueListenableBuilder
,建立一個按鈕計數的小功能
首先先建立一個StatelessWidget
的檔案value_notifier_demo_screen.dart
counterNotifier
來存放ValueNotifier
counterNotifier
放在ValueListenableBuilder
裡面,當counterNotifier.value
的值變化時,畫面就會被刷新import 'package:flutter/material.dart';
class ValueNotifierDemoScreen extends StatelessWidget {
ValueNotifierDemoScreen({Key? key}) : super(key: key);
final ValueNotifier counterNotifier = ValueNotifier<int>(0); //Set<int>()初始值
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(
Icons.arrow_back_ios,
),
onPressed: () {
Navigator.of(context).pop();
},
),
title: const Text(
"ValueListenableBuilder",
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
const SizedBox(
height: 50,
),
ValueListenableBuilder(
valueListenable: counterNotifier,
builder: (context, counter, child) {
return Text("$counter");
},
),
const SizedBox(
height: 50,
),
ElevatedButton(
onPressed: () {
counterNotifier.value = counterNotifier.value + 1;
},
child: const Text("Button"),
)
],
),
),
);
}
}