build method

  1. @override
Widget build(
  1. BuildContext context
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  // Retrieve the appState notifier.
  final appState = context.gaana;
  final usersNotifier = appState.get<UsersNotifier>();
  if (usersNotifier == null) {
    return const Scaffold(
      body: Center(child: Text("UsersNotifier not found")),
    );
  }
  // Some random greeting texts.
  const List<String> greetings = [
    "Hello",
    "Hi there",
    "Greetings",
    "Welcome",
    "Hey!",
  ];
  final repository = PlotRepository();
  final petrolUseCase = PetrolUseCase(
    repository: repository,
    plotNotifier: GaanaService.instance.get<PlotNotifier>() ?? PlotNotifier(),
  );
  return Scaffold(
    appBar: AppBar(title: const Text("Gaana state machine")),
    body: Column(
      children: [
        // A row of horizontally scrollable pills.
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children:
                  usersNotifier.users.map((user) {
                    return GestureDetector(
                      onTap: () {
                        // When a user pill is tapped, check if a ChatNotifier exists.
                        ChatNotifier? chatNotifier =
                            appState.get<ChatNotifier>();
                        // If not, create one and add it.
                        if (chatNotifier == null) {
                          chatNotifier = ChatNotifier();
                          appState.add(ChatNotifier());
                        }
                        // Generate a random greeting.
                        final greeting =
                            greetings[Random().nextInt(greetings.length)];
                        final message = Message(
                          id: DateTime.now().millisecondsSinceEpoch,
                          sender: user,
                          content: "$greeting from $user!",
                          timestamp: DateTime.now(),
                        );
                        chatNotifier.add(message);
                      },
                      child: Card(
                        child: Container(
                          margin: const EdgeInsets.symmetric(horizontal: 4),
                          padding: const EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 8,
                          ),

                          child: Text(
                            user,
                            style: TextStyle(
                              color:
                                  Theme.of(
                                    context,
                                  ).textTheme.bodyMedium?.color,
                            ),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
            ),
          ),
        ),
        // Button to shuffle the users list.
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              buildStyledButton(
                context: context,
                label: "Shuffle users",
                onPressed: () {
                  GaanaService.instance.get<PlotNotifier>()?.clean();
                  if (Platform.isIOS) HapticFeedback.lightImpact();
                  usersNotifier.shuffle();
                  final usersNotifier2 =
                      GaanaService.instance.get<UsersNotifier>();
                  debugPrint(
                    (usersNotifier2 == Gaana.of(context).get<UsersNotifier>())
                        .toString(),
                  );
                },
                backgroundColor: const Color.fromARGB(255, 149, 54, 244),
              ),
              buildStyledButton(
                context: context,
                label: "Stream data",
                onPressed: () {
                  // For demonstration, instantiate PlotRepository and PetrolUseCase.
                  GaanaService.instance.get<PlotNotifier>()?.clean();
                  if (petrolUseCase.isRunning()) {
                    petrolUseCase.stop();
                  } else {
                    // Start the petrol use case if not already started.
                    petrolUseCase.start();
                  }
                },
                backgroundColor: const Color.fromARGB(255, 0, 142, 114),
              ),
            ],
          ),
        ),

        // Expanded grid view to display chat messages.
        Expanded(
          child: GridView.builder(
            padding: const EdgeInsets.all(8.0),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 1,
              childAspectRatio: 3,
              crossAxisSpacing: 8,
              mainAxisSpacing: 8,
            ),
            itemCount: appState.notifiers.whereType<ChatNotifier>().fold<int>(
              0,
              (sum, notifier) => sum + notifier.messages.length,
            ), //chatNotifier.messages.length,
            itemBuilder: (context, index) {
              final allMessages =
                  appState.notifiers
                      .whereType<ChatNotifier>()
                      .expand((chat) => chat.messages)
                      .toList();
              final message = allMessages[index];
              return GestureDetector(
                onTap: () {
                  // When a message tile is tapped, remove it from its ChatNotifier.
                  final chatNotifier = appState.get<ChatNotifier>(
                    predicate: (cn) => cn.messages.contains(message),
                  );
                  if (chatNotifier != null) {
                    chatNotifier.remove(message);
                  }
                },
                child: Card(
                  child: ListTile(
                    title: Text(message.sender),
                    subtitle: Text(message.content),
                    trailing: Text(
                      "${message.timestamp.hour}:${message.timestamp.minute.toString().padLeft(2, '0')}:${message.timestamp.second.toString().padLeft(2, '0')}",
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        GraphDemo(),
        SizedBox(height: 80),
      ],
    ),
  );
}