When inheriting the StatelessWidget component, the page will not refresh immediately when updating data in the component.
If you inherit StatefulWidget, as long as the data is updated in the setState method, the page will update the data in real time.
Flutter stateful component StatefulWidget
Full code:
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<String> _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),
),
);
}
}