Flutter - code snippet for Retry widget

in #india2 years ago

Following piece of code can be placed as is in side your code base in one file. Once done, import it to re-use.

import 'package:flutter/material.dart';

class RetryScreen extends StatelessWidget {
  const RetryScreen({
    Key? key,
    required this.error,
    required this.onRetry,
  }) : super(key: key);

  final Function() onRetry;
  final String error;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          ElevatedButton(onPressed: onRetry, child: const Text('Retry')),
          Text(error)
        ],
      ),
    );
  }
}

// here is an example of how to use it.

Widget _body() {
    return FutureBuilder<List<CommunityItem>>(
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return RetryScreen(
                error: snapshot.error?.toString() ?? "Something went wrong",
                onRetry: getData, // a function reference to reload
              );
            } 
// cutting additional unwanted code