網站首頁 編程語言 正文
有狀態組件
flutter 主要有分有狀態組件 StatefulWidget 和無狀態組件 StatelessWidget,前面我們使用到的都是無狀態組件,沒有讓頁面上的內容發生變化,當我們有需要對頁面的內容進行動態修改的時候 ,如果我們使用無狀態組件,頁面上的內容就不會被更新,這時需要用到有狀態組件。
有狀態組件就是繼承了StatefulWidget的組件,內容更改時調用
setState(() { 更改的內容});
// ignore_for_file: prefer_const_constructors, prefer_collection_literals, deprecated_member_use, unused_local_variable, must_be_immutable, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; void main() { ? runApp(MyApp()); } class MyApp extends StatelessWidget { ? const MyApp({Key? key}) : super(key: key); ? @override ? Widget build(BuildContext context) { ? ? return MaterialApp( ? ? ? home: Scaffold( ? ? ? ? appBar: AppBar( ? ? ? ? ? title: const Text('Flutter Demo'), ? ? ? ? ), ? ? ? ? body: const HomeContent(), ? ? ? ), ? ? ? theme: ThemeData( ? ? ? ? primarySwatch: Colors.yellow, ? ? ? ), ? ? ); ? } } //有狀態自定義組件有兩個類,我們需要返回的寫在第二個類中 class HomeContent extends StatefulWidget { ? const HomeContent({Key? key}) : super(key: key); ? @override ? _HomeContentState createState() => _HomeContentState(); } class _HomeContentState extends State<HomeContent> { ? int count = 0; ? @override ? Widget build(BuildContext context) { ? ? return Center( ? ? ? child: Column( ? ? ? children: [ ? ? ? ? Chip( ? ? ? ? ? label: Text("$count"), ? ? ? ? ), ? ? ? ? ElevatedButton( ? ? ? ? ? ? onPressed: () { ? ? ? ? ? ? ? setState(() { ? ? ? ? ? ? ? ? count++; ? ? ? ? ? ? ? }); ? ? ? ? ? ? }, ? ? ? ? ? ? child: Text("點擊加一")) ? ? ? ], ? ? ), ? ? ); ? } }
原文鏈接:https://blog.csdn.net/m0_46527751/article/details/122485141
相關推薦
- 2022-10-11 oracle 12c和plsql的詳細安裝和配置過程(超級詳細,小白也能懂)
- 2023-10-14 uniapp 將base64字符串保存為圖片、Word、Excel、音頻、視頻等文件
- 2022-11-13 Python反射機制案例超詳細講解_python
- 2023-05-18 Kotlin?ViewModelProvider.Factory的使用實例詳解_Android
- 2022-12-21 C語言中continue的用法詳解_C 語言
- 2022-08-30 python在文件中倒序查找個關鍵詞
- 2023-10-09 markdown和富文本編輯器的區別
- 2022-07-18 BeanUtils工具類
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支