2. The First Screen

Building the View and ViewModel separately

Goals of this chapter

1

Create the State

An immutable state class with freezed

2

Create the ViewModel

A Notifier with @riverpod

3

Create the View

A HookConsumerWidget that only displays

Roles of the View and ViewModel

View (screen)

  • Only display and button handling
  • Holds no state
  • Reads state with ref.watch

ViewModel

  • Holds the screen’s state (State)
  • Handles what happens when buttons are pressed
  • Replaces the whole state with state = state.copyWith(...)

flowchart LR
  V["View"] -- "ref.watch(state)" --> VM["ViewModel"]
  V -- "notifier.addUser()" --> VM
  VM -- "updates state" --> V

ViewModel and State

lib/ui/user_list/view_model/user_list_view_model.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'user_list_view_model.g.dart';
part 'user_list_view_model.freezed.dart';

@freezed
abstract class UserListState with _$UserListState {
  const factory UserListState({
    @Default([]) List<String> names,
    String? errorMessage,
  }) = _UserListState;
}

@riverpod
class UserListViewModel extends _$UserListViewModel {
  @override
  UserListState build() => const UserListState();

  // true if added
  bool addUser(String name) {
    final trimmed = name.trim();
    if (trimmed.isEmpty) {
      state = state.copyWith(errorMessage: '名前を入力してください');
      return false;
    }
    state = state.copyWith(
      names: [...state.names, trimmed],
      errorMessage: null,
    );
    return true;
  }
}

Key points

  • @freezed abstract class → copyWith and == are generated automatically
  • @Default(...) sets the initial value
  • @riverpod → userListViewModelProvider is generated automatically
  • part '...g.dart' / part '...freezed.dart' are generated files. It’s fine if they’re red at first
dart run build_runner build

View

lib/ui/user_list/view/user_list_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/ui/user_list/view_model/user_list_view_model.dart';

class UserListPage extends HookConsumerWidget {
  const UserListPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(userListViewModelProvider);
    final notifier = ref.read(userListViewModelProvider.notifier);
    final nameController = useTextEditingController();

    return Scaffold(
      appBar: AppBar(title: const Text('ユーザー一覧')),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: nameController,
                    decoration: InputDecoration(
                      labelText: '名前',
                      errorText: state.errorMessage,
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                FilledButton(
                  onPressed: () {
                    if (notifier.addUser(nameController.text)) {
                      nameController.clear();
                    }
                  },
                  child: const Text('追加'),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView(
              children: [
                for (final name in state.names)
                  ListTile(leading: const Icon(Icons.person), title: Text(name)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Key points of the View

Code Meaning
ref.watch(provider) Reads the state. Redraws the screen when it changes
ref.read(provider.notifier) Calls ViewModel methods
useTextEditingController() Controller for the input field. Cleanup is automatic too

What if you don’t use watch?

Without watch (StatefulWidget + setState)

class _UserListPageState extends State<UserListPage> {
  final _names = <String>[];

  void _add(String name) {
    // Every time you change the data, you must
    // ask for a "redraw" yourself
    setState(() {
      _names.add(name);
    });
  }
  // Delete, edit, load… setState is needed everywhere
}

With watch (Riverpod)

// View: just reads
final state = ref.watch(userListViewModelProvider);

// ViewModel: just replaces state
state = state.copyWith(
  names: [...state.names, trimmed],
);
// → screens watching it are redrawn automatically

The problem without watch

  • Without watch, every time you change data you must call “update the screen” yourself
  • Forget it once and “the data changed but the screen is stale”. The more places change data, the easier it is to miss one
  • The same applies when reading state with ref.read: it isn’t redrawn when the value changes → always use ref.watch for values you display

Show it in the app

Set home in app.dart to const UserListPage().

lib/app.dart
import 'package:flutter/material.dart';
import 'package:motion_app/ui/user_list/view/user_list_page.dart';

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Motion Note',
      theme: ThemeData(colorSchemeSeed: Colors.teal),
      home: const UserListPage(),
    );
  }
}

Checkpoint

CHECK 0 / 4