Flutter-从其他小部件调用setState()

Flutter-从其他小部件调用setState(),第1张

Flutter-从其他小部件调用setState()

这是使用流的可能解决方案

import 'dart:async';import 'package:flutter/material.dart';void main() => runApp(new MyApp());class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return new MaterialApp(      title: 'Timer',      theme: new ThemeData(        primaryColor: Colors.grey.shade800,      ),      home: new MyHomePage(),    );  }}class MyHomePage extends StatelessWidget {  StreamController<int> _controller = StreamController<int>();  int _seconds = 1;  @override  Widget build(BuildContext context) {    return Scaffold(      appBar: AppBar(        title: Text("title"),      ),      body: Column(        mainAxisAlignment: MainAxisAlignment.spaceAround,        children: <Widget>[          MyTextWidget(stream: _controller.stream), //just update this widget          Divider(),          Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[   IconButton(     icon: Icon(Icons.add_circle),     onPressed: _addPressed,     iconSize: 150.0,   ),   IconButton(     icon: Icon(Icons.remove_circle),     onPressed: ()=> _controller.add(_seconds++),     iconSize: 150.0,   ), ],          )        ],      ),    );  }  void _addPressed() {    //somehow call _updateSeconds()  }}class MyTextWidget extends StatefulWidget{  final Stream<int> stream;  MyTextWidget({this.stream});  @override  _MyTextWidgetState createState() => _MyTextWidgetState();}class _MyTextWidgetState extends State<MyTextWidget> {  int secondsToDisplay = 0;  void _updateSeconds(int newSeconds) {    setState(() {      secondsToDisplay = newSeconds;    });  }  @override  void initState() {    super.initState();    widget.stream.listen((seconds) {      _updateSeconds(seconds);    });  }  @override  Widget build(BuildContext context) {    return Text(      secondsToDisplay.toString(),      textScaleFactor: 5.0,    );  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5090432.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存