首页 > 解决方案 > 如何修改现有的自定义列表项并访问其修改后的值?

问题描述

我有一个带有自定义磁贴小部件的 listView。每块瓷砖都有:

我想总结每个图块中文本小部件的修改值。

问题:ListView 是动态的,意味着图块可能会增加。我正在维护一个用于保存列表视图项目的列表。插入图块后,用户可以通过点击 iconButton 来增加文本的值。

由于 tile 的对象已经插入到列表中,我只能通过使用 setState() 在点击 iconButton 时更新屏幕上的 Text 小部件值。

如何将 perticalar tile 对象的值更新到列表中?

请在下面找到问题的简化代码:

class mainWidgetState extends State<mainWidget> {

//  list of the child widget
  List<ChildWidget> listChildWidget = [];    // <- this needs to be updated when user tap the button

// total of the text value from every list item 
  int totalCount = 0;   

// add child widget to list view 
 void addChildWidget() {
    setState(() {
      listChildWidget.add(ChildWidget());
    });
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('Test'),
      ),

     // add a new list item
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            addChildWidget();
          }),
      body: new Column(
        children: <Widget>[
          Expanded(
              child: new ListView.builder(
                  itemCount: listChildWidget.length,
                  itemBuilder: (context, index) {
                    return new ListTile(
                      title: new ChildWidget(),
                    );
                  })),

          // view total of the counters
          IconButton(
              icon: Icon(Icons.slideshow),
              onPressed: () {
                getTotalCount();
              }),
          Text(this.totalCount.toString())
        ],
      ),
    );
  }
}

class ChildWidgetState extends State<ChildWidget> {
  int textValue = 0;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Row(
      children: <Widget>[
        // one text
        Text(textValue.toString()),

        // one add button
        IconButton(
            icon: Icon(Icons.add_circle),
            onPressed: () {
              setState(() {
                this.textValue += 1;
              });
            })
      ],
    );
  }
}

标签: flutterdart

解决方案


我不知道我是否理解了这个问题。1)您不需要在ListView中创建ChildWidget,因为您已经在listChildWidget中有小部件,因此您可以简单地执行以下操作:

Expanded(
              child: new ListView.builder(
                  itemCount: listChildWidget.length,
                  itemBuilder: (context, index) {
                    return new ListTile(title: listChildWidget[0]);
                  })),

2)如果你想更新totalCount,你可以创建一个函数来增加用户每次点击图标时的值,例如

_increaseTotalCount() {
    setState(() {
      totalCount = totalCount + 1;
    });
  }

现在,当您创建另一个 ChildWidget 时,您必须传递 func

void addChildWidget() {
    setState(() {
      listChildWidget.add(ChildWidget(
        increaseTotalCount: _increaseTotalCount,
      ));
    });
  }

当用户按下时,您只需要调用该函数

onPressed: () {
              widget.increaseTotalCount();
              setState(() {
                this.textValue += 1;
              });
            }

您可以在此处找到示例:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<ChildWidget> listChildWidget =
      []; // <- this needs to be updated when user tap the button

// total of the text value from every list item
  int totalCount = 0;

// add child widget to list view
  void addChildWidget() {
    setState(() {
      listChildWidget.add(ChildWidget(
        increaseTotalCount: _increaseTotalCount,
      ));
    });
  }

  _increaseTotalCount() {
    setState(() {
      totalCount = totalCount + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text('Test'),
      ),

      // add a new list item
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            addChildWidget();
          }),
      body: new Column(
        children: <Widget>[
          Expanded(
              child: new ListView.builder(
                  itemCount: listChildWidget.length,
                  itemBuilder: (context, index) {
                    return new ListTile(title: listChildWidget[0]);
                  })),

          // view total of the counters
          IconButton(icon: Icon(Icons.slideshow), onPressed: () {}),
          Text(this.totalCount.toString())
        ],
      ),
    );
  }
}

class ChildWidget extends StatefulWidget {
  final Function() increaseTotalCount;

  const ChildWidget({Key key, this.increaseTotalCount}) : super(key: key);
  @override
  _ChildWidgetState createState() => _ChildWidgetState();
}

class _ChildWidgetState extends State<ChildWidget> {
  int textValue = 0;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Row(
      children: <Widget>[
        // one text
        Text(textValue.toString()),

        // one add button
        IconButton(
            icon: Icon(Icons.add_circle),
            onPressed: () {
              widget.increaseTotalCount();
              setState(() {
                this.textValue += 1;
              });
            })
      ],
    );
  }
}

希望能帮助到你 ;)


推荐阅读