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

setState不会更新用户界面

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

setState不会更新用户界面

这是怎么回事:

  • A
    State
    绝对不能有任何构造函数参数。使用该
    widget
    属性可以访问关联的的最终属性
    StatefulWidget
  • Flutter
    正在重用您的
    _textClass
    实例,因为类名和键匹配。这是一个问题,因为您仅进行了设置
    widget.word
    initState
    因此您不会选择新的word配置信息。您可以通过为
    StatefulWidget
    实例提供唯一的键来消除它们的歧义并导致旧
    State
    的东西被处置来解决此问题,或者可以保留旧的东西
    State
    并加以实施
    didUpdateWidget
    。后一种方法如下所示。

    import ‘dart:async’;
    import ‘package:flutter/material.dart’;

    void main() {
    runApp(new MaterialApp(
    home: new Scaffold(
    appBar: new AppBar(title: new Text(‘Example App’)),
    body: new textList(),
    ),
    ));
    }

    class textList extends StatefulWidget {

    @override
    State createState() =>
    new _textListState();
    }

    class _textListState extends State
    with TickerProviderStateMixin {

    List items = new List();
    Widget lorem = new textClass(“Lorem”);
    Timer timer;

    @override
    void initState() {
    super.initState();

    items.add(new textClass("test"));items.add(new textClass("test"));timer = new Timer.periodic(new Duration(seconds: 5), (Timer timer) {  setState(() {    items.removeAt(0);    items.add(lorem);  });});

    }

    @override
    void dispose() {
    super.dispose();
    timer.cancel();
    }

    @override
    Widget build(BuildContext context) {
    Iterable content = ListTile.divideTiles(
    context: context, tiles: items).toList();

    return new Column(  children: content,);

    }
    }

    class textClass extends StatefulWidget {
    textClass(this.word);

    final String word;

    @override
    State createState() =>
    new _textClass();
    }

    class _textClass extends State
    with TickerProviderStateMixin {
    _textClass();

    String word;
    Timer timer;

    @override
    void didUpdateWidget(textClass oldWidget) {
    if (oldWidget.word != widget.word) {
    word = widget.word;
    }
    super.didUpdateWidget(oldWidget);
    }

    @override
    void initState() {
    super.initState();
    word = widget.word;

    timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) {  setState(() {    word += "t";  });});

    }

    @override
    void dispose() {
    super.dispose();
    timer.cancel();
    }

    @override
    Widget build(BuildContext context) {
    return new Text(word);
    }
    }



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

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

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