Flutter有状态组件StatefulWidget

当继承StatelessWidget组件时,在组件中更新数据时页面不会立即刷新。

如果继承StatefulWidget时,只要在setState方法中更新数据后页面会实时更新数据。

Flutter有状态组件StatefulWidget

完整代码:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Flutter"),
        ),
        body: const MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _HomePageState();
  }
}

///StatefulWidget:状态组件,改变页面数据状态
class _HomePageState extends StatefulWidget {
  const _HomePageState();

  @override
  State<_HomePageState> createState() => _HomePageStateState();
}

class _HomePageStateState extends State<_HomePageState> {
  final List _list = ["数据一", "数据二", "数据三"];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: _list.map((v) {
          return ListTile(title: Text(v));
        }).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _list.add("新增数据");
          });
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

你可能感兴趣的:(flutter)