1
votes

I know Stack Widgets render their children from the ground up, however, I couldn't explain to myself why a BlocBuilder cannot efficiently rebuild them.

Here is an example:

@override
Widget build(BuildContext context) {
  return Container(
    child: BlocBuilder<TestCubit, int>(
      builder: (context, state) {
        return GestureDetector(
          onTapDown: (tapDetails) {
            context.read<TestCubit>().incrementCubit();
          },
          child: Stack(children: [Text('Counter: $state')]),
        );
      },
    )
  );
}

When TestCubit has its incrementCubit method called, the state changes - I tested it with a simple Container based UI, but once we are dealing with a Stack, nothing happens on the screen. Any ideas?

Thanks in advance!

1

1 Answers

1
votes

I tested your code and it works with both Stack as well as Container. Please see my code below :

main.dart

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

void main() {
  runApp(
    const CounterApp(),
  );
}

class CounterApp extends MaterialApp {
  const CounterApp({Key key}) : super(key: key, home: const CounterPage());
}

class CounterPage extends StatelessWidget {
  const CounterPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => TestCubit(),
      child: CounterView(),
    );
  }
}

class CounterView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(child: BlocBuilder<TestCubit, int>(
      builder: (context, state) {
        return GestureDetector(
          onTapDown: (tapDetails) {
            context.read<TestCubit>().incrementCubit();
          },
          child: Stack(children: [Text('Counter: $state')]),
          //child: Text('Counter: $state'),
          //child: Scaffold(
          //   appBar: AppBar(title: const Text("Cubit Demo")),
          //   body: Center(
          //       child: Stack(
          //     children: [
          //       Text('Counter: $state'),
          //     ],
          //   )),
          //),
        );
      },
    ));
  }
}

class TestCubit extends Cubit<int> {
  TestCubit() : super(0);
  void incrementCubit() => emit(state + 1);
  void decrementCubit() => emit(state - 1);
}

pubspec.yaml

name: test_http
description: A new Flutter application.

publish_to: 'none'

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_bloc:

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true