flutter 扑动阻滞:我如何访问树中所有块中的变量?

kq0g1dla  于 2023-03-31  发布在  Flutter
关注(0)|答案(1)|浏览(109)

我想访问一个或多个列表或变量在整个树我的程序,并执行操作的添加,删除,编辑该列表,我解决了这个问题,通过使用提供程序包,如下图:
我在第一次做这门课

class TaskData extends ChangeNotifier {
  List<Task> _tasks = [
    Task(title: 'Buy Milk'),
    Task(title: 'Buy Eggs'),
    Task(title: 'Buy Bread'),
  ];

  UnmodifiableListView<Task> get tasks => UnmodifiableListView(_tasks);

  int get taskCount => _tasks.length;

  toggleDone(index) {
    _tasks[index].toggleDone();
    notifyListeners();
  }

  addTask(data) {
    _tasks.add(Task(title: data));
  }

  removeTask(index) {
    _tasks.removeAt(index);
    notifyListeners();
  }
}

然后提供像这样的树

void main() {
  runApp(ChangeNotifierProvider(
    create: (BuildContext context) => TaskData(),
    child: MaterialApp(
      theme: ThemeData(
        useMaterial3: true,
      ),
      home: TasksScreen(),
    ),
  ));
}

我用这样的代码

class TasksList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<TaskData>(
      builder: (context, taskData, child) {
        return ListView.builder(
          itemCount: taskData.taskCount,
          itemBuilder: (context, index) {
            print(taskData.tasks[index]);
            return TaskTile(
              taskTitle: taskData.tasks[index].title,
              isChecked: taskData.tasks[index].isDone,
              checkboxCallback: (newValue) {
                taskData.toggleDone(index);
              },
              listTileCallback: () {
                taskData.removeTask(index);
              },
            );
          },
        );
      },
    );
  }
}

现在,我需要学习如何使用bloc和flutter_bloc以及模型类、实体类、存储库类等干净架构以及所有干净架构系统来完成此操作?

km0tfn4u

km0tfn4u1#

1.想想可能发生的事件[Event类]
1.可以有多少个状态[State类]

  1. Bloc [Main Bloc]上的处理逻辑
class Task extends Equatable { //import 'package:equatable/equatable.dart';
  const Task({
    required this.title,
    this.isDone = false,
  });
  final String title;
  final bool isDone;

  @override
  List<Object?> get props => [title, isDone];

  Task copyWith({
    String? title,
    bool? isDone,
  }) {
    return Task(
      title: title ?? this.title,
      isDone: isDone ?? this.isDone,
    );
  }
}

abstract class TaskEvent extends Equatable {
  const TaskEvent();

  @override
  List<Object> get props => [];
}

class ToggleDone extends TaskEvent {
  const ToggleDone(this.task);
  final Task task;

  @override
  List<Object> get props => [task];
}

class AddTask extends TaskEvent {
  const AddTask(this.task);
  final Task task;

  @override
  List<Object> get props => [task];
}

class RemoveTask extends TaskEvent {
  const RemoveTask(this.task);
  final Task task;

  @override
  List<Object> get props => [task];
}

///state
class TaskState extends Equatable {
  const TaskState(this.tasks);

  final List<Task> tasks;
  @override
  List<Object> get props => [tasks, identityHashCode(this)];
}

//bloc

class TaskBloc extends Bloc<TaskEvent, TaskState> {
  TaskBloc([List<Task> tasks = const []]) : super(TaskState(tasks)) {
    on<ToggleDone>((event, emit) {
      final item = event.task;
      final tasks = state.tasks;
      final index = tasks.indexWhere((element) => element == item);

      tasks[index] = item.copyWith(isDone: !item.isDone);
      emit(TaskState([...tasks]));
    });

    on<AddTask>(
      (event, emit) {
        final tasks = state.tasks;
        tasks.add(event.task);
        emit(TaskState([...tasks]));
      },
    );

    on<RemoveTask>((event, emit) {
      final tasks = state.tasks;
      tasks.remove(event.task);
      emit(TaskState([...tasks]));
    });
  }
}

和主文件

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

      List<Task> _tasks = [
    Task(title: 'Buy Milk'),
    Task(title: 'Buy Eggs'),
    Task(title: 'Buy Bread'),
  ];
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(create: (context) => TaskBloc(_tasks)),
      ],
      child: MaterialApp(
        home: Scaffold(
          body: TasksList(),
        ),
      ),
    );
  }
}

class TasksList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return BlocBuilder<TaskBloc, TaskState>(
      builder: (context, taskData) {
        return ListView.builder(
          itemCount: taskData.tasks.length,
          itemBuilder: (context, index) {
            print(taskData.tasks[index]);
            return ListTile(
              title: Text(taskData.tasks[index].title),
              leading: Checkbox(
                  value: taskData.tasks[index].isDone,
                  onChanged: (value) {
                    context
                        .read<TaskBloc>()
                        .add(ToggleDone(taskData.tasks[index]));
                  }),
              trailing: IconButton(
                  onPressed: () {
                    context
                        .read<TaskBloc>()
                        .add(RemoveTask(taskData.tasks[index]));
                  },
                  icon: Icon(Icons.delete)),
            );
          },
        );
      },
    );
  }
}

你可以按照bloclibrary和他们的示例代码。

相关问题