【问题标题】:Why does this FAB not update the state?为什么这个 FAB 不更新状态?
【发布时间】:2020-03-29 13:36:11
【问题描述】:

我已尽我所能关注这个问题:Adding new ListTile item on click

虽然它不一定像它可能的那样可重现,但我创建了一些可以编译但没有按预期运行的东西:

import 'package:flutter/material.dart';

void main() => runApp(SeedBank());

class SeedBank extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.lightGreen,
      ),
      home: Seeds(),
    );
  }
}

class Seeds extends StatefulWidget {
  @override
  SeedsState createState() => SeedsState();
}

class SeedsState extends State<Seeds> {
  var _seedSection = List<Widget>();

  Card seedSectionMethod(String title, String subtitle) {
    return new Card(
      child: ListTile(
          title: Text(
            title,
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          subtitle: Text(subtitle),
          trailing: Icon(Icons.more_vert)),
    );
  }

  void initState() {
    super.initState();
    _seedSection.add(
      seedSectionMethod("Leek", "Bulgaarse Reuzen - Lincoln"),
    );
    _seedSection.add(
      seedSectionMethod("Kale", "Jardin mix"),
    );
    _seedSection.add(
      seedSectionMethod("Sunflower", "Helianthus Red"),
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Seed Bank'),
      ),
      body: ListView(
        children: this._seedSection,
      ),
      floatingActionButton: FloatingActionButton(
        child: Text("+"),
        onPressed: () {
          setState(() {
            _seedSection.add(
              seedSectionMethod("New Seed", "With notes"),
            );
          });
        },
        backgroundColor: Colors.lightGreenAccent,
      ),
    );
  }
}

期望的行为是:

  • 在应用启动时,填充了三个带有种子的“卡片”。
  • 按下按钮时,会添加一个带有值 "new Seed""with notes" 的新“卡片”。

我想我错过了一些关于设置状态的基本知识(昨天才开始),但我对下一步该去哪里了解更多。

V2:

使用@andrea689,我可以编译,但又遇到了同样的问题:

class SeedsState extends State<Seeds> {
  var _seedSection = List<Widget>();

  var _seeds = [
    ["Leek", "Bulgaarse Reuzen - Lincoln"],
    ["Kale", "Jardin mix"],
    ["Sunflower", "Helianthus Red"],
  ];

  Card seedSectionMethod(String title, String subtitle) {
    return new Card(
      child: ListTile(
          title: Text(
            title,
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          subtitle: Text(subtitle),
          trailing: Icon(Icons.more_vert)),
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Seed Bank'),
      ),
      body:  ListView.builder(
        itemCount: _seedSection.length,
        itemBuilder: (context, index) {
          return seedSectionMethod(_seeds[index][0], _seeds[index][1]);
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Text("+"),
        onPressed: () {
          setState(() {
            _seeds.add(["New Seed", "With notes"]);
          });
        },
        backgroundColor: Colors.lightGreenAccent,
      ),
    );
  }
}

这是该类的外观吗?它现在不再添加新项目。

最终解决方案

import 'package:flutter/material.dart';

void main() => runApp(SeedBank());

class SeedBank extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.lightGreen,
      ),
      home: Seeds(),
    );
  }
}

class Seeds extends StatefulWidget {
  @override
  SeedsState createState() => SeedsState();
}

class SeedsState extends State<Seeds> {
  var _seeds = [
    ["Leek", "Bulgaarse Reuzen - Lincoln"],
    ["Kale", "Jardin mix"],
    ["Sunflower", "Helianthus Red"],
  ];

  Card seedSectionMethod(String title, String subtitle) {
    return new Card(
      child: ListTile(
          title: Text(
            title,
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          subtitle: Text(subtitle),
          trailing: Icon(Icons.more_vert)),
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Seed Bank'),
      ),
      body: ListView.builder(
        itemCount: _seeds.length,
        itemBuilder: (context, index) {
          return seedSectionMethod(_seeds[index][0], _seeds[index][1]);
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Text("+"),
        onPressed: () {
          setState(() {
            setState(() {
              _seeds.add(["New Seed", "With notes"]);
            });
          });
        },
        backgroundColor: Colors.lightGreenAccent,
      ),
    );
  }
}

【问题讨论】:

    标签: user-interface flutter dart state


    【解决方案1】:

    由于修改了_seedSection,所以必须使用ListView.builder

    ListView.builder(
         itemCount: _seedSection.length,
         itemBuilder: (context, index) {
              return _seedSection[index];
         },
    ),
    

    此外,最好只在状态中存储值并将小部件放在itemBuilder 中。

    var _seeds = [
        ["Leek", "Bulgaarse Reuzen - Lincoln"],
        ["Kale", "Jardin mix"],
        ["Sunflower", "Helianthus Red"],
      ];
    
    ListView.builder(
         itemCount: _seeds.length,
         itemBuilder: (context, index) {
              return seedSectionMethod(_seeds[index][0], _seeds[index][1]);
         },
    ),
    
    setState(() {
         _seeds.add(["New Seed", "With notes"]);
    });
    

    【讨论】:

    • 谢谢,这行得通。你的意思是:void initState() { super.initState(); _seedSection.add( seedSectionMethod("Leek", "Bulgaarse Reuzen - Lincoln"), ); _seedSection.add( seedSectionMethod("Kale", "Jardin mix"), ); _seedSection.add( seedSectionMethod("Sunflower", "Helianthus Red"), ); } 应该移到脚手架中的FloatingActionButton(....) 调用吗?
    • 我不确定我是否完全理解,请参阅有问题的 V2 编辑。感谢您的帮助理解:)
    • 应该itemCount: _seedSection.lengthitemCount: _seeds.length
    • @DaveRGP 是的,抱歉复制/粘贴错误!
    【解决方案2】:

    像这样试试。

    body: ListView.builder(
      itemCount: this._seedSection.length,
      itemBuilder: (context, index) => this._seedSection[index],
    ),
    

    这是工作演示。 https://dartpad.dev/43a5b08327ed0f64fd084947873a3e52

    【讨论】:

    • 这行得通。你能再补充一点来帮助我理解为什么吗?
    • ListView.builder,当您动态创建列表时。在您的情况下,您正在将项目动态添加到列表中。当您的列表未更新时,ListView 工作,希望这会有所帮助。
    【解决方案3】:

    尝试添加这个:

    body: ListView(
      children: this._seedSection.map((data) {
        return data;
      }).toList(),
    ),
    

    【讨论】:

    • 这也有效。您能否解释一下为什么会这样以及我错过了什么?
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2013-12-27
    • 1970-01-01
    相关资源
    最近更新 更多