網站首頁 編程語言 正文
有狀態組件
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-04-12 el-tree 踩過最深的坑,沒有之一。設置與上級嚴格關聯、下級不嚴格關聯,CV即用
- 2022-11-21 Golang?Mutex互斥鎖源碼分析_Golang
- 2021-12-02 深入了解c語言的循環語句_C 語言
- 2022-08-27 解決react中useState狀態異步更新的問題_React
- 2021-12-09 C語言求兩個正整數的最大公約數示例代碼_C 語言
- 2022-02-25 Servlet配置啟動級別loadOnStartup注意事項
- 2022-11-12 C語言內存操作函數使用示例梳理講解_C 語言
- 2022-02-13 使用paddlepaddle進行手寫數字識別
- 最近更新
-
- 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同步修改后的遠程分支