当继承StatelessWidget组件时,在组件中更新数据时页面不会立即刷新。
如果继承StatefulWidget时,只要在setState方法中更新数据后页面会实时更新数据。
Flutter有状态组件StatefulWidget文章来源:https://www.toymoban.com/news/detail-586366.html
完整代码:文章来源地址https://www.toymoban.com/news/detail-586366.html
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),
),
);
}
}
到了这里,关于Flutter有状态组件StatefulWidget的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!