Tutorials

Multiple Views

Build apps with multiple screens and navigation between them.

Create multi-screen applications!

The Pattern

package main

import (
    tea "github.com/charmbracelet/bubbletea/v2"
)

type view int

const (
    menuView view = iota
    gameView
    settingsView
)

type model struct {
    currentView view
    // ... view-specific state
}

func (m model) Init() tea.Cmd { return nil }

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
    switch msg := msg.(type) {
    case tea.KeyPressMsg:
        switch m.currentView {
        case menuView:
            switch msg.String() {
            case "1":
                m.currentView = gameView
            case "2":
                m.currentView = settingsView
            case "q":
                return m, tea.Quit
            }
        case gameView, settingsView:
            if msg.String() == "esc" {
                m.currentView = menuView
            }
        }
    }
    return m, nil
}

func (m model) View() string {
    switch m.currentView {
    case gameView:
        return "🎮 Game View\n\nPress Esc to go back"
    case settingsView:
        return "⚙️  Settings View\n\nPress Esc to go back"
    default:
        return "📋 Menu\n\n1. Play Game\n2. Settings\n\nq to quit"
    }
}

func main() {
    tea.NewProgram(model{}).Run()
}

Tips

  1. Use an enum (iota) for views
  2. Handle view-specific keys in a switch
  3. Keep view-specific state organized
  4. Consider using sub-models for complex views