栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何从Flutter中的其他StatefulWidget设置/更新StatefulWidget的状态?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何从Flutter中的其他StatefulWidget设置/更新StatefulWidget的状态?

OLD :创建_MyHomePageState的全局实例。在_SubState中将此实例用作_myHomePageState.setState

:无需创建全局实例。而是将父实例传递给子窗口小部件

按颤振0.8.2更新的代码

import 'package:flutter/material.dart';void main() => runApp(new MyApp());class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return new MaterialApp(      title: 'Flutter Demo',      theme: new ThemeData(        primarySwatch: Colors.blue,      ),      home: new MyHomePage(),    );  }}EdgeInsets globalMargin =    const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0);TextStyle textStyle = const TextStyle(  fontSize: 100.0,  color: Colors.black,);class MyHomePage extends StatefulWidget {  @override  _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {  int number = 0;  @override  Widget build(BuildContext context) {    return new Scaffold(      appBar: new AppBar(        title: new Text('SO Help'),      ),      body: new Column(        children: <Widget>[          new Text( number.toString(), style: textStyle,          ),          new GridView.count( crossAxisCount: 2, shrinkWrap: true, scrollDirection: Axis.vertical, children: <Widget>[   new InkResponse(     child: new Container(         margin: globalMargin,         color: Colors.green,         child: new Center(child: new Text(  "+",  style: textStyle,),         )),     onTap: () {       setState(() {         number = number + 1;       });     },   ),   new Sub(this), ],          ),        ],      ),      floatingActionButton: new FloatingActionButton(        onPressed: () {          setState(() {});        },        child: new Icon(Icons.update),      ),    );  }}class Sub extends StatelessWidget {  _MyHomePageState parent;  Sub(this.parent);  @override  Widget build(BuildContext context) {    return new InkResponse(      child: new Container(          margin: globalMargin,          color: Colors.red,          child: new Center( child: new Text(   "-",   style: textStyle, ),          )),      onTap: () {        this.parent.setState(() {          this.parent.number --;        });      },    );  }}

请让我知道它是否有效。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/369009.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号