使用ValueListenableBuilder和ValueNotifier重写counter程序
import 'package:flutter/material.dart';
void main(List<String> args) {
runApp(const MaterialApp(
home: Homepage(),
));
}
class Homepage extends StatefulWidget {
const Homepage({super.key});
@override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
ValueNotifier<int> count = ValueNotifier<int>(0);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("You clicked : "),
ValueListenableBuilder(
valueListenable: count,
builder: (context, value, child) {
return Text("${count.value}");
},
)
],
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
count.value = count.value + 1;
},
),
);
}
}