gpt4 book ai didi

Flutter Bloc 状态无论如何都不会更新

转载 作者:行者123 更新时间:2023-12-05 02:53:41 26 4
gpt4 key购买 nike

我目前正在尝试学习 flutter 的状态管理,我有以下代码,但由于某种原因,状态从未更新过,我是否遗漏了什么?

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

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: BlocProvider(
create: (context) => ItemBloc(),
child: MyHomePage(),
),
);
}
}

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bloc Demo"),
),
body: Lister(),
floatingActionButton: FloatingActionButton(
onPressed: () {
ItemBloc().add(AddEvent());
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

class Lister extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<ItemBloc, ListState>(
builder: (context, state) {
if (state is ListAdded) {
return ListView.builder(
itemCount: state.items.length,
itemBuilder: (context, index) {
return Text("item"); // This never increases in count
},
);
}
return Center(
child: Text('err'),
);
},
);
}
}

// BLOC
class ItemBloc extends Bloc<ListEvent, ListState> {
@override
get initialState => ListAdded(items: ["initial"]);

@override
Stream<ListState> mapEventToState(ListEvent event) async* {
if (event is AddEvent) {
final lister = ["first", "second"];
yield ListAdded(items: lister);
}
}
}

abstract class ListEvent extends Equatable {
@override
List<Object> get props => [];
}

class AddEvent extends ListEvent {}

abstract class ListState extends Equatable {
const ListState();

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

class ListAdded extends ListState {
final List<String> items;

const ListAdded({
this.items,
});

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

@override
String toString() => 'ItemsLoaded { items: ${items.length} }';
}

请注意:我已经尝试将代码分成单独的文件,并在 Bloc 文件中导入 bloc.dart 包而不是 flutter_bloc.dart

最佳答案

当你做的时候

ItemBloc().add(AddEvent())

您正在创建新的 bloc 实例并向其添加事件。它与在 MyApp 中创建并在 Lister 中使用的应用程序无关。

您应该获取创建的 bloc:

BlocProvider.of<ItemBloc>(context).add(AddEvent())

关于Flutter Bloc 状态无论如何都不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62072916/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com