flutter 屏幕不更新(setState),直到窗口调整大小

dxxyhpgq  于 2022-11-25  发布在  Flutter
关注(0)|答案(1)|浏览(116)

我没有经验的关键和刚刚开始,下面的代码是完全可复制的代码,并在dartpad上工作,
代码是一个基本的列表应用程序,但floatingActionButton添加项目到列表,是坏的,onPressed函数有一个print(ctr)语句,它工作正常,但应用程序屏幕不更新(或改变),除非浏览器的窗口被调整大小,请看,
请注意,它很少能正确工作,但在多次尝试中,

import "package:flutter/material.dart";

void main() {
  runApp(MaterialApp(home: SimpleListPage()));
}

class SimpleListPage extends StatefulWidget {
  const SimpleListPage({super.key});

  @override
  State<SimpleListPage> createState() {
    return _SimpleListPageState();
  }
}

class _SimpleListPageState extends State<SimpleListPage> {
  int counter = 0;

  List<Widget> items = <Widget>[];

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

    items.add(Text("Simple list"));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: items,
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          int ctr = counter++;
          print(ctr);

          setState(() {
            items.add(SimpleListItem(
              key: ValueKey<int>(ctr), // even `UniqueKey()` NOT work
              data: Data(null),
            ));
          });
        },
      ),
    );
  }
}

class Data {
  Data(this.text);
  String? text;
}

class SimpleListItem extends StatefulWidget {
  const SimpleListItem({
    super.key,
    required this.data,
  });

  final Data data;

  @override
  State<SimpleListItem> createState() {
    return _SimpleListItemState();
  }
}

class _SimpleListItemState extends State<SimpleListItem> {
  @override
  Widget build(BuildContext context) {
    String? text = widget.data.text;

    if (text != null) {
      return ListTile(
        title: Text(text),
      );
    } else {
      return TextField(
        decoration: InputDecoration(
          border: OutlineInputBorder(),
        ),
        autofocus: true,
        onSubmitted: (String input) {
          setState(() {
            widget.data.text = input;
          });
        },
      );
    }
  }
}

还有,请建议,是使用ValueKey<int>(counter++),好的方法,还是其他一些,也是ValueKey,好的方法,
谢谢你
我尝试使用UniqueKey代替ValueKey,但没有任何进展,
我看了几个媒体的帖子,Youtube视频,特别是官方的关键视频,但无济于事

s4n0splo

s4n0splo1#

更改ListView的用法

body: ListView(
  children: items,
),

使用ListView.builder

body: ListView.builder( 
  itemCount: items.length,
  itemBuilder: (_, i) => items[i],
),

相关问题