Flutter
🍃

Flutter

Categories
Flutter
Text
记录Flutter学习过程
Date
Nov 4, 2024

Controller

controllers允许开发者从外部控制widget的行为,即使该widget深深嵌入在app的结构中。
Controllers工作的逻辑顺序:Controllers的状态更新——》widget的状态更新

Controllers的作用

  • Dynamic Updates:使应用程序可以动态变化
  • Data Persistence:帮助储存与管理与widget关联的数据
  • External Control:在widget外部管理

Controllers的类型

  • TextEditingController:TextField
  • ScrollController:ListView 、 SingleChildScrollView 或 GridView
  • AnimationController
  • TabController:TabBar 和 TabBarView
  • Custom Controllers:通过继承ChangeNotifier 编写自己的Controllers
常用的Controllers会对应一些常用的widget,通过controllers控制这些widget

Controllers的工作原理

  1. Creation: final TextEditingController _textController = TextEditingController( );
  1. Connection: 将TextField的controller属性设置为_textController
  1. Interaction: 编写一个函数,内部有核心监听逻辑
  1. Listening: textController.addListener(updateCount);
  1. disposal:_textController.dispose( );
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const CounterScreen(), ); } } class CounterScreen extends StatefulWidget { const CounterScreen({super.key}); @override _CounterScreenState createState() => _CounterScreenState(); } class _CounterScreenState extends State<CounterScreen> { // Creation final TextEditingController _textController = TextEditingController(); int _count = 0; // The state variable to store the count @override void initState() { super.initState(); // Listening _textController.addListener(_updateCount); // Listen for text changes } // Listener: 一个不断执行的函数 void _updateCount() { setState(() { // Interaction _count = _textController.text.length; // Update count based on text length }); } @override void dispose() { // disposal _textController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Dynamic Counter')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextField( // Connection controller: _textController, ), const SizedBox(height: 20), Text( 'Character Count: $_count', style: const TextStyle(fontSize: 24), ), ], ), ), ), ); } }