即使没有渲染,小部件也会抛出错误

时间:2021-05-17 10:34:09

标签: flutter dart

我有一个自定义的 ErrorBuilder 小部件,如果没有错误则返回子小部件,如果有错误则显示错误消息。实现如下:

import 'package:flutter/material.dart';

class ErrorBuilder extends StatelessWidget {
  const ErrorBuilder(
      {Key? key,
      required this.child,
      required this.error,
      required this.onRetry})
      : super(key: key);
  final Widget child;
  final Exception? error;
  final void Function() onRetry;

  @override
  Widget build(BuildContext context) {
    // This build method is Never Reached if there is error
    if (error == null) {
      return child;
    } else {
      return Builder(builder: (c) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text('An error occured'),
              TextButton(onPressed: onRetry, child: Text('Retry'))
            ],
          ),
        );
      });
    }
  }
}

如果没有错误它可以工作,但如果有错误则不显示错误消息。

class Overview extends StatelessWidget {
  const Overview({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<NepseIndex>(
      id: "IndexHeader",
      builder: (index) {
        if (index.indices.isEmpty && index.exception == null) {
          return const Center(
            child: const CircularProgressIndicator(),
          );
        }

        print(index.exception == null); // false

        return ErrorBuilder(
          error: index.exception,
          onRetry: () {
            index.retry();
          },
          child: Card(
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0)),
            child: Container(
              padding:
                  const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        'NEPSE',
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                      _getIndexString(index.nepse), // I get error here because index.nepse throws error if there is some exception
                      _getCard(index.isMarketOpen),
                    ],
                  ),
                  AutoSizeText(
                    'As of ' + Dates.mDYT(index.marketStat['asOf']),
                    maxLines: 2,
                    textAlign: TextAlign.center,
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }

那么,当出现错误时,为什么在 ErrorBuilder 中传递的子小部件会被构建?它应该显示错误消息。 当我用 Builder 包装子小部件 Card 时,一切都按预期工作。可能是什么原因?

0 个答案:

没有答案