日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Flutter有狀態組件使用詳解_Android

作者:s-010101 ? 更新時間: 2022-03-30 編程語言

有狀態組件

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

欄目分類
最近更新