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

Flutter开发报错:A function body must be provided 求助

解决Flutter中「A function body must be provided」错误

你的错误出在CategoryTile类的构造函数定义上,构造函数声明后缺少分号,导致Dart解析器判定你需要提供函数体,从而抛出该错误。

修正后的完整代码

import 'package:flutter/material.dart';

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

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Row(
          children: [
            Text("Flutter"),
            Text(
              "News",
              style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
            )
          ],
        ),
        centerTitle: true,
      ),
      body: Container(),
    );
  }
}

class CategoryTile extends StatelessWidget {
  final image, categoryName;
  // 补充分号完成构造函数声明
  CategoryTile({super.key, this.categoryName, this.image});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack( children: [
        Image.asset(image,
          width: 120,
          height: 60,
        )
      ],),
    );
  }
}

错误原因说明

在Dart中,使用这种直接将构造函数参数绑定到类成员的简洁语法时,必须在构造函数声明末尾添加分号,明确告诉编译器这是一个完整的构造函数定义,无需额外编写函数体。你之前的代码漏掉了这个分号,才触发了语法错误。

额外建议:给image和categoryName成员变量指定明确的类型(比如final String? image;、final String? categoryName;),能提升代码可读性与类型安全性,避免潜在的类型相关问题。

内容的提问来源于stack exchange,提问作者Nikhil Soman Sahu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:03:23