You need to enable JavaScript to run this app. Flutter实现左上角模拟时钟遇RenderBox未布局错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Flutter实现左上角模拟时钟遇RenderBox未布局错误求助

问题原因
  • 重复嵌套MaterialApp组件:main.dart中已经将MyApps作为MaterialApp的home参数传入,MyApps内部又定义了一层MaterialApp,双重嵌套导致布局约束传递异常,触发hasSize渲染错误
  • 缺少对齐定位组件:直接使用Padding包裹时钟组件,没有父级对齐规则,无法将组件固定到左上角位置,同时导致尺寸约束传递异常
修复方案

直接修改MyApps组件代码,删除冗余的MaterialApp,使用Align组件实现左上角定位,配合Padding调整边距即可,修改后代码如下:

import 'package:analog_clock/analog_clock.dart';
import 'package:flutter/material.dart';

class MyApps extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApps> {
  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.green[900],
          title: Text('CLOCK'),
        ),
        backgroundColor: Colors.green,
        // 用Align实现左上角定位
        body: Align(
          alignment: Alignment.topLeft,
          child: Padding(
            padding: const EdgeInsets.only(top: 10, left: 10), // 可自行调整左上间距
            child: AnalogClock(
              decoration: BoxDecoration(
                  border: Border.all(width: 3.0, color: Colors.black),
                  color: Colors.black,
                  shape: BoxShape.circle),
              width: 200.0,
              isLive: true,
              hourHandColor: Colors.white,
              minuteHandColor: Colors.white,
              showSecondHand: true,
              numberColor: Colors.white,
              showNumbers: true,
              textScaleFactor: 1.5,
              showTicks: true,
              showDigitalClock: true,
              digitalClockColor: Colors.white,
              // 如果需要时钟实时走时,删除下面的固定datetime配置
              // datetime: DateTime(2020, 8, 4, 9, 11, 0),
            ),
          ),
        ),
      );
}
验证效果

修改后运行项目即可看到时钟固定在页面左上角,不会再抛出布局渲染错误,可通过调整Padding的top和left参数微调时钟的位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 14:15:03