You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter报错:'HomePage'类型不是'bool'类型的子类型

解决Flutter中type 'HomePage' is not a subtype of type 'bool'错误

错误原因

错误出在MainPage的build方法中:Scaffold组件的extendBody参数要求传入布尔值(bool类型),但你错误地传入了pages[0](即HomePage的实例,属于Widget类型),类型不匹配直接触发了该类型转换错误。

修复方案

1. 修正extendBody参数

将extendBody: pages[0]替换为布尔值,比如默认的false,或者直接删除该参数(因为extendBody默认值就是false)。

2. 正确展示页面内容

如果需要在Scaffold的body中显示首页内容,把当前body里的占位Container替换为pages[0],后续还可以添加索引变量实现底部导航栏切换页面的功能。

修正后的完整Main代码

import 'package:flutter/material.dart';
import 'package:medreminder/home_page.dart';
import 'package:medreminder/profile_page.dart';
import 'package:medreminder/settings_page.dart';

void main() => runApp(const MainPage());

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  // 控制当前显示页面的索引
  int _currentIndex = 0;
  final List<Widget> pages = [
    const HomePage(),
    const SettingPage(),
    const ProfilePage()
  ];
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        // 显示当前选中的页面
        body: pages[_currentIndex],
        // 修正extendBody为布尔值,或直接删除该参数
        extendBody: false,
        bottomNavigationBar: BottomNavigationBar(
          selectedItemColor: Colors.black,
          currentIndex: _currentIndex,
          // 添加导航切换逻辑
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
          items: const [
            BottomNavigationBarItem(label: "Home", icon: Icon(Icons.home)),
            BottomNavigationBarItem(label: "Settings", icon: Icon(Icons.settings)),
            BottomNavigationBarItem(label: "Profile", icon: Icon(Icons.account_circle)),
          ],
        ),
      ),
    );
  }
}

额外说明

  • 原代码中runApp(MainPage())缺少MaterialApp包裹,修正后添加了该根组件,符合Flutter应用结构规范;
  • 新增的_currentIndex变量和BottomNavigationBar的onTap回调,实现了底部导航栏切换页面的基础功能,可根据需求进一步扩展。

内容的提问来源于stack exchange,提问作者NyK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:25:21