Flutter之刷新局部控件
2020/12/23 8:08:22
本文主要是介绍Flutter之刷新局部控件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
概述
在flutter开发时,有时候点击某个按钮,只需要刷新指定控件,而不需要将整个页面都刷新.
思路: 在待刷新控件里定义一个点击方法,点击方法里刷新本控件. 点击指定按钮时,去调用此待刷新控件里的点击方法.
流程图
代码
main.dart
import 'package:flutter/material.dart'; import 'new_text.dart'; import 'new_button.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { GlobalKey textKey = GlobalKey(); //设置key,绑定待刷新控件. var _count = 1; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextWidget(textKey), //传入key给待刷新控件 //自定义的ButtonWidget控件,会传入一个onPressed参数.这个参数是名为OnPressed的方法,方法无参数. //该方法最终是传递给了new_button.dart的RaisedButton控件调用. ButtonWidget( onPressed: () { _count++; textKey.currentState.onPressed( _count); ///点击button,调用TextWidget的onPressed方法 }, ), ], ), ), ); } }
new_text.dart
import 'package:flutter/material.dart'; class TextWidget extends StatefulWidget { //! 接收传过来的key TextWidget(Key key) : super(key: key); @override State createState() { return TextWidgetState(); } } class TextWidgetState extends State { String _text="0"; @override Widget build(BuildContext context) { return Center( child: Text(_text,style: TextStyle(fontSize: 20,color:Colors.green), ), ); } //在TextWidget的onPressed中单独调用TextWidget的setState,刷新本控件. void onPressed(int count) { setState(() { _text = count.toString(); }); } }
new_button.dart
import 'new_text.dart'; import 'package:flutter/material.dart'; typedef onPressed_changestate(); class ButtonWidget extends StatefulWidget { //类变量,作为调用类时的参数 onPressed_changestate onPressed; ButtonWidget({this.onPressed}); @override State createState() { return _ButtonWidgetState(onPressed); } } class _ButtonWidgetState extends State { onPressed_changestate new_onPressed; _ButtonWidgetState(this.new_onPressed); @override Widget build(BuildContext context) { return Center( child: RaisedButton( child: Text('count++',style: TextStyle(fontSize: 20),), onPressed: new_onPressed, //new_onPressed是main.dart调用该控件时传递过来的方法 //也就是 onPressed: () { // _count++; // textKey.currentState.onPressed( _count); // }, ), ); } }
这篇关于Flutter之刷新局部控件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-27消息中间件底层原理资料详解
- 2024-11-27RocketMQ底层原理资料详解:新手入门教程
- 2024-11-27MQ底层原理资料详解:新手入门教程
- 2024-11-27MQ项目开发资料入门教程
- 2024-11-27RocketMQ源码资料详解:新手入门教程
- 2024-11-27本地多文件上传简易教程
- 2024-11-26消息中间件源码剖析教程
- 2024-11-26JAVA语音识别项目资料的收集与应用
- 2024-11-26Java语音识别项目资料:入门级教程与实战指南
- 2024-11-26SpringAI:Java 开发的智能新利器