如何直接将bloc添加到视图小部件

时间:2020-04-23 21:12:44

标签: flutter dart bloc

我有一个创建小部件的屏幕。

如何在我的窗口小部件中添加集团?

class UserView extends StatelessWidget {
   final AnimationController aController;
   final Animation animation;

   @override
   Widget build(BuildContext context) {
     // Add Scafold here?
      return AnimationBuilder(
         animation: aController;
         builder: (BuildContext context, Widget child) {
            ...
         },
      );
   }
}

集团

class UserBloc extends Bloc<UserEvent, UserState> {
    final UserRepo userRepo;
    UserBloc({@required this.userRepo}) : assert(userRepo != null);
}

如果我添加Scaffold(),则会收到一条错误消息,提示“对象在布局期间被赋予了无限大小”。

我正在将此https://bloclibrary.dev/#/用于集团。

如有必要,我可以显示更多代码,我试图使其简洁易读。请询问,我可以添加更多。


应用

void main() async {
  final UserRepo userRepo = UserRepo();
  BlocSupervisor.delegate = SimpleBlocDelegate();

  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations(<DeviceOrientation>[
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]).then((_) => runApp(MultiBlocProvider(
        providers: [
          BlocProvider<UserBloc>(
            create: (context) => UserBloc(userRepo: userRepo),
          )
        ],
        child: MyApp(),
      )));
}

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

    return MaterialApp(
      title: 'Test App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        textTheme: AppTheme.textTheme,
        platform: TargetPlatform.iOS,
      ),
      home: HomeScreen(),
    );
  }
}

主屏幕

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with TickerProviderStateMixin {
  AnimationController animationController;

  Widget tabBody = Container(
    color: AppTheme.background,
  );

  @override
  void initState() {
    animationController = AnimationController(
        duration: const Duration(milliseconds: 800), vsync: this);
    tabBody = DashboardScreen(animationController: animationController);
    super.initState();
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppTheme.background,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: FutureBuilder<bool>(
          future: getData(),
          builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
            if (!snapshot.hasData) {
              return const SizedBox();
            } else {
              return Stack(
                children: <Widget>[
                  tabBody
                ],
              );
            }
          },
        ),
      ),
    );
  }
}

仪表板

class DashboardScreen extends StatefulWidget {
  const DashboardScreen({Key key, this.animationController}) : super(key: key);

  final AnimationController animationController;
  @override
  _DashboardScreenState createState() => _DashboardScreenState();
}

class _DashboardScreenState extends State<DashboardScreen>
    with TickerProviderStateMixin {
  Animation<double> topBarAnimation;

  List<Widget> listViews = <Widget>[];
  final ScrollController scrollController = ScrollController();
  double topBarOpacity = 0.0;

  @override
  void initState() {
    listViews.add(
      UserView(
        animation: Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation(
            parent: widget.animationController,
            curve:
                Interval((1 / count) * 1, 1.0, curve: Curves.fastOutSlowIn))),
        animationController: widget.animationController,
      ),
    );
    super.initState();
  }

}

1 个答案:

答案 0 :(得分:1)

我将假设UserBloc必须可用于整个应用程序,否则,只需将下面提供者的级别更改为恰好在其应涵盖的小部件之上:

您在此处提供位于MaterialApp小部件上方的块,以便稍后在此小部件的任何后代中使用它:(内部App文件)

 return BlocProvider(
    create: (_)=>UserBloc(userRepo:UserRep()),
    child: MaterialApp(
      title: 'Test App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        textTheme: AppTheme.textTheme,
        platform: TargetPlatform.iOS,
      ),
      home: HomeScreen(),
    ),
  );

现在,如果您想使用自己的集团来发出事件并监听MaterialApp的任何后代小部件中的状态,只需用BlocListenerBlocConsumer或{{ 1}}(请查看它们之间的区别here):

我想您想在BlocBuilder中这样做:

HomeScreen

就是这样。

查看上面的链接以获取更多文档。