Flutter|更新 ListView

Flutter|Updating a ListView

各位! 我有一个主屏幕,代码如下:

return SafeArea(
          child: Scaffold(
            body: Stack(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 8, right: 8),
                  child: Column(children: [
                    ActiveTaskInfo(
                      task: tasks.first,
                    ),
                    const TextWidget(),
                    Expanded(child: TasksList()),
                    const SizedBox(height: 80),
                  ]),
                ),
                BottomBarClass(),
              ],
            ),
        ),
    );

TasksList() - ListView。

BottomBarClass() - 它是一个容器,里面有一个按钮。

如果您 return 将代码本身添加到主 HomeScreen 文件中,一切正常,但是如果您将它放在一个单独的 class 中并且当您向列表中添加一个新项目时(通过按钮)没有任何反应,但如果您按下 Hot Reload,则会显示列表中的新项目。

代码BottomBarClass():

Positioned(
        bottom: 0, left: 0,
        child: ClipRRect(
          borderRadius: const BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30)),
          child: Container(
            height: 80, width: MediaQuery.of(context).size.width,
            color: const Color(0xff070417),
            child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Icon(Icons.watch_later, color: Colors.white.withOpacity(0.4)),
                IconButton(icon: Icon(Icons.add, color: Colors.white.withOpacity(0.4),), iconSize: 32, onPressed: () async {
                  bool result = await Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return TaskAdding();
                  }));
                  if (result == true) {
                    setState(() {
                    });
                  }
                }),
                Icon(Icons.pie_chart_rounded, color: Colors.white.withOpacity(0.4), size: 24,),
              ],),
          ),
        ));

Вот пример GIF: https://gifyu.com/image/Spp1O

任务添加():

import 'package:flutter/material.dart';

import '../expansions/task_tags_decorations.dart';
import '../expansions/tasks_data.dart';

class TaskAdding extends StatefulWidget {
  const TaskAdding({Key? key}) : super(key: key);

  @override
  State<TaskAdding> createState() => _TaskAddingState();
}

class _TaskAddingState extends State<TaskAdding> {
  late String _addField;
  late Widget _selectedValue;
  late bool _active;
  late int _selectedIndex;

  @override
  void initState() {
    _addField = 'Empty';
    _active = false;
    _selectedValue = tasks[0].icon;
    _selectedIndex = 0;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Add'), backgroundColor: Colors.pink),
      body: Column(children: [
        Text('Add Task', style: TextStyle(color: Colors.white, fontSize: 24),),
        TextField(onChanged: (String value) {
          _addField = value;
        }),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            DropdownButton<Widget>(
              value: _selectedValue,
              onChanged: (newValue) {
                setState(() {
                  _selectedValue = newValue!;
                });
              },
              items: dropdownItems,
            ),
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    tasks.addAll({
                      TaskData(
                        taskName: _addField,
                        tagOne: _active
                            ? tasks[0].tagOne
                            : tasks[1].tagOne,
                        tagTwo: tagTwoContainer[_selectedIndex],
                        icon: _selectedValue,
                        taskTime: '00:32:10',
                      )
                    });
                    decorations.addAll({
                      TaskTagsDecorations(
                          iconColor: const Color(0xff7012CF))
                    });
                  });
                  Navigator.of(context).pop(true);
                },
                child: const Text('Add')),
          ],
        ),
        Center(
          child: ListTile(
            title: _active
                ? Center(
              child: tasks[0].tagOne,
            )
                : Center(child: tasks[1].tagOne),
            selected: _active,
            onTap: () {
              setState(() {
                _active = !_active;
              });
            },
          ),
        ),
        SizedBox(
          height: 52,
          child: ListView.builder(
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
              itemCount: tagTwoContainer.length,
              itemBuilder: (context, index) {
                var tagTwoList = tasks[index].tagTwo;
                return SizedBox(
                  height: MediaQuery.of(context).size.height, width: 160,
                  child: ListTile(
                    visualDensity: VisualDensity.compact,
                    selected: index == _selectedIndex,
                    selectedTileColor: Colors.indigo.withOpacity(0.6),
                    title: Align(
                      alignment: Alignment.topCenter,
                        child: tagTwoList),
                    onTap: () {
                      setState(() {
                        _selectedIndex = index;
                      });
                    },
                  ),
                );
              }),
        ),
      ],),
    );
  }
  List<DropdownMenuItem<Widget>> get dropdownItems {
    List<DropdownMenuItem<Widget>> menuItems = [
      DropdownMenuItem(
        child: const Icon(Icons.free_breakfast),
        value: iconCircle[0],
      ),
      DropdownMenuItem(
          child: const Icon(Icons.grade_outlined), value: iconCircle[1]),
      DropdownMenuItem(child: const Icon(Icons.gamepad), value: iconCircle[2]),
      DropdownMenuItem(
          child: const Icon(Icons.face_rounded), value: iconCircle[3]),
    ];
    return menuItems;
  }
}

你的问题不清楚。尝试添加 TasksList()

我的解决方案:

 Navigator.push(context,
                    MaterialPageRoute(builder: (context) {
                      return HomeScreen();
                    }));