概述
在 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<MyHomePage> {GlobalKey<TextWidgetState> 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: <Widget>[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<StatefulWidget> createState() {return TextWidgetState();
}
}
class TextWidgetState extends State<TextWidget> {
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<StatefulWidget> createState() {return _ButtonWidgetState(onPressed);
}
}
class _ButtonWidgetState extends State<ButtonWidget> {
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 写的 app, 须要源码能够私信~~
- 简繁火星字体转换
- 哄女友神器
- 号码测吉凶
- 电视节目直播表
最好的笔记软件
https://www.wolai.com/signup?…